blob: 320d93a99ad6a2ae9fa8724bb29e05b9168cd2a5 [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 Smith852c9db2013-04-20 22:23:05 +0000575 if (Init < NumInits)
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000576 ILE->setInit(Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000577 else {
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000578 ILE->updateInit(SemaRef.Context, Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000579 RequiresSecondPass = true;
580 }
581 return;
582 }
583
Douglas Gregor2bb07652009-12-22 00:05:34 +0000584 if (Field->getType()->isReferenceType()) {
585 // C++ [dcl.init.aggr]p9:
586 // If an incomplete or empty initializer-list leaves a
587 // member of reference type uninitialized, the program is
588 // ill-formed.
589 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
590 << Field->getType()
591 << ILE->getSyntacticForm()->getSourceRange();
592 SemaRef.Diag(Field->getLocation(),
593 diag::note_uninit_reference_member);
594 hadError = true;
595 return;
596 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000597
Richard Smith454a7cd2014-06-03 08:26:00 +0000598 ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
Manman Ren073db022016-03-10 18:53:19 +0000599 /*VerifyOnly*/false,
600 TreatUnavailableAsInvalid);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000601 if (MemberInit.isInvalid()) {
602 hadError = true;
603 return;
604 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000605
Douglas Gregor2bb07652009-12-22 00:05:34 +0000606 if (hadError) {
607 // Do nothing
608 } else if (Init < NumInits) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000609 ILE->setInit(Init, MemberInit.getAs<Expr>());
Richard Smith454a7cd2014-06-03 08:26:00 +0000610 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
611 // Empty initialization requires a constructor call, so
Douglas Gregor2bb07652009-12-22 00:05:34 +0000612 // extend the initializer list to include the constructor
613 // call and make a note that we'll need to take another pass
614 // through the initializer list.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000615 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000616 RequiresSecondPass = true;
617 }
618 } else if (InitListExpr *InnerILE
619 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Richard Smith454a7cd2014-06-03 08:26:00 +0000620 FillInEmptyInitializations(MemberEntity, InnerILE,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000621 RequiresSecondPass, ILE, Init, FillWithNoInit);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000622 else if (DesignatedInitUpdateExpr *InnerDIUE
623 = dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init)))
624 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
Richard Smithf3b4ca82018-02-07 22:25:16 +0000625 RequiresSecondPass, ILE, Init,
626 /*FillWithNoInit =*/true);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000627}
628
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000629/// Recursively replaces NULL values within the given initializer list
630/// with expressions that perform value-initialization of the
Richard Smithf3b4ca82018-02-07 22:25:16 +0000631/// appropriate type, and finish off the InitListExpr formation.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000632void
Richard Smith454a7cd2014-06-03 08:26:00 +0000633InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
Douglas Gregor723796a2009-12-16 06:35:08 +0000634 InitListExpr *ILE,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000635 bool &RequiresSecondPass,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000636 InitListExpr *OuterILE,
637 unsigned OuterIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000638 bool FillWithNoInit) {
Mike Stump11289f42009-09-09 15:08:12 +0000639 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000640 "Should not have void type");
Mike Stump11289f42009-09-09 15:08:12 +0000641
Richard Smithf3b4ca82018-02-07 22:25:16 +0000642 // If this is a nested initializer list, we might have changed its contents
643 // (and therefore some of its properties, such as instantiation-dependence)
644 // while filling it in. Inform the outer initializer list so that its state
645 // can be updated to match.
646 // FIXME: We should fully build the inner initializers before constructing
647 // the outer InitListExpr instead of mutating AST nodes after they have
648 // been used as subexpressions of other nodes.
649 struct UpdateOuterILEWithUpdatedInit {
650 InitListExpr *Outer;
651 unsigned OuterIndex;
652 ~UpdateOuterILEWithUpdatedInit() {
653 if (Outer)
654 Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
655 }
656 } UpdateOuterRAII = {OuterILE, OuterIndex};
657
Richard Smith382bc512017-02-23 22:41:47 +0000658 // A transparent ILE is not performing aggregate initialization and should
659 // not be filled in.
660 if (ILE->isTransparent())
661 return;
662
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000663 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000664 const RecordDecl *RDecl = RType->getDecl();
665 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Richard Smith454a7cd2014-06-03 08:26:00 +0000666 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
Yunzhong Gaocb779302015-06-10 00:27:52 +0000667 Entity, ILE, RequiresSecondPass, FillWithNoInit);
Richard Smith852c9db2013-04-20 22:23:05 +0000668 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
669 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000670 for (auto *Field : RDecl->fields()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000671 if (Field->hasInClassInitializer()) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000672 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
673 FillWithNoInit);
Richard Smith852c9db2013-04-20 22:23:05 +0000674 break;
675 }
676 }
677 } else {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000678 // The fields beyond ILE->getNumInits() are default initialized, so in
679 // order to leave them uninitialized, the ILE is expanded and the extra
680 // fields are then filled with NoInitExpr.
Richard Smith872307e2016-03-08 22:17:41 +0000681 unsigned NumElems = numStructUnionElements(ILE->getType());
682 if (RDecl->hasFlexibleArrayMember())
683 ++NumElems;
684 if (ILE->getNumInits() < NumElems)
685 ILE->resizeInits(SemaRef.Context, NumElems);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000686
Douglas Gregor2bb07652009-12-22 00:05:34 +0000687 unsigned Init = 0;
Richard Smith872307e2016-03-08 22:17:41 +0000688
689 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
690 for (auto &Base : CXXRD->bases()) {
691 if (hadError)
692 return;
693
694 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
695 FillWithNoInit);
696 ++Init;
697 }
698 }
699
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000700 for (auto *Field : RDecl->fields()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000701 if (Field->isUnnamedBitfield())
702 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000703
Douglas Gregor2bb07652009-12-22 00:05:34 +0000704 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000705 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000706
Yunzhong Gaocb779302015-06-10 00:27:52 +0000707 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
708 FillWithNoInit);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000709 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000710 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000711
Douglas Gregor2bb07652009-12-22 00:05:34 +0000712 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000713
Douglas Gregor2bb07652009-12-22 00:05:34 +0000714 // Only look at the first initialization of a union.
Richard Smith852c9db2013-04-20 22:23:05 +0000715 if (RDecl->isUnion())
Douglas Gregor2bb07652009-12-22 00:05:34 +0000716 break;
717 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000718 }
719
720 return;
Mike Stump11289f42009-09-09 15:08:12 +0000721 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000722
723 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000724
Douglas Gregor723796a2009-12-16 06:35:08 +0000725 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000726 unsigned NumInits = ILE->getNumInits();
727 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000728 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000729 ElementType = AType->getElementType();
Richard Smith0511d232016-10-05 22:41:02 +0000730 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000731 NumElements = CAType->getSize().getZExtValue();
Richard Smith0511d232016-10-05 22:41:02 +0000732 // For an array new with an unknown bound, ask for one additional element
733 // in order to populate the array filler.
734 if (Entity.isVariableLengthArrayNew())
735 ++NumElements;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000736 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000737 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000738 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000739 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000740 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000741 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000742 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000743 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000744 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000745
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000746 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000747 if (hadError)
748 return;
749
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000750 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
751 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000752 ElementEntity.setElementIndex(Init);
753
Richard Smith3e268632018-05-23 23:41:38 +0000754 if (Init >= NumInits && ILE->hasArrayFiller())
755 return;
756
Craig Topperc3ec1492014-05-26 06:22:03 +0000757 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000758 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
759 ILE->setInit(Init, ILE->getArrayFiller());
760 else if (!InitExpr && !ILE->hasArrayFiller()) {
761 Expr *Filler = nullptr;
762
763 if (FillWithNoInit)
764 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
765 else {
766 ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(),
767 ElementEntity,
Manman Ren073db022016-03-10 18:53:19 +0000768 /*VerifyOnly*/false,
769 TreatUnavailableAsInvalid);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000770 if (ElementInit.isInvalid()) {
771 hadError = true;
772 return;
773 }
774
775 Filler = ElementInit.getAs<Expr>();
Douglas Gregor723796a2009-12-16 06:35:08 +0000776 }
777
778 if (hadError) {
779 // Do nothing
780 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000781 // For arrays, just set the expression used for value-initialization
782 // of the "holes" in the array.
783 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
Yunzhong Gaocb779302015-06-10 00:27:52 +0000784 ILE->setArrayFiller(Filler);
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000785 else
Yunzhong Gaocb779302015-06-10 00:27:52 +0000786 ILE->setInit(Init, Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000787 } else {
788 // For arrays, just set the expression used for value-initialization
789 // of the rest of elements and exit.
790 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000791 ILE->setArrayFiller(Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000792 return;
793 }
794
Yunzhong Gaocb779302015-06-10 00:27:52 +0000795 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000796 // Empty initialization requires a constructor call, so
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000797 // extend the initializer list to include the constructor
798 // call and make a note that we'll need to take another pass
799 // through the initializer list.
Yunzhong Gaocb779302015-06-10 00:27:52 +0000800 ILE->updateInit(SemaRef.Context, Init, Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000801 RequiresSecondPass = true;
802 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000803 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000804 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000805 = dyn_cast_or_null<InitListExpr>(InitExpr))
Yunzhong Gaocb779302015-06-10 00:27:52 +0000806 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000807 ILE, Init, FillWithNoInit);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000808 else if (DesignatedInitUpdateExpr *InnerDIUE
809 = dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr))
810 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
Richard Smithf3b4ca82018-02-07 22:25:16 +0000811 RequiresSecondPass, ILE, Init,
812 /*FillWithNoInit =*/true);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000813 }
814}
815
Douglas Gregor723796a2009-12-16 06:35:08 +0000816InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000817 InitListExpr *IL, QualType &T,
Manman Ren073db022016-03-10 18:53:19 +0000818 bool VerifyOnly,
819 bool TreatUnavailableAsInvalid)
820 : SemaRef(S), VerifyOnly(VerifyOnly),
821 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid) {
Richard Smith520449d2015-02-05 06:15:50 +0000822 // FIXME: Check that IL isn't already the semantic form of some other
823 // InitListExpr. If it is, we'd create a broken AST.
824
Steve Narofff8ecff22008-05-01 22:18:59 +0000825 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000826
Richard Smith4e0d2e42013-09-20 20:10:22 +0000827 FullyStructuredList =
Craig Topperc3ec1492014-05-26 06:22:03 +0000828 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000829 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000830 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000831
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000832 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000833 bool RequiresSecondPass = false;
Richard Smithf3b4ca82018-02-07 22:25:16 +0000834 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
835 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000836 if (RequiresSecondPass && !hadError)
Richard Smith454a7cd2014-06-03 08:26:00 +0000837 FillInEmptyInitializations(Entity, FullyStructuredList,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000838 RequiresSecondPass, nullptr, 0);
Douglas Gregor723796a2009-12-16 06:35:08 +0000839 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000840}
841
842int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000843 // FIXME: use a proper constant
844 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000845 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000846 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000847 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
848 }
849 return maxElements;
850}
851
852int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000853 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000854 int InitializableMembers = 0;
Richard Smith872307e2016-03-08 22:17:41 +0000855 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
856 InitializableMembers += CXXRD->getNumBases();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000857 for (const auto *Field : structDecl->fields())
Douglas Gregor556e5862011-10-10 17:22:13 +0000858 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000859 ++InitializableMembers;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000860
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000861 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000862 return std::min(InitializableMembers, 1);
863 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000864}
865
Richard Smith283e2072017-10-03 20:36:00 +0000866/// Determine whether Entity is an entity for which it is idiomatic to elide
867/// the braces in aggregate initialization.
868static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
869 // Recursive initialization of the one and only field within an aggregate
870 // class is considered idiomatic. This case arises in particular for
871 // initialization of std::array, where the C++ standard suggests the idiom of
872 //
873 // std::array<T, N> arr = {1, 2, 3};
874 //
875 // (where std::array is an aggregate struct containing a single array field.
876
877 // FIXME: Should aggregate initialization of a struct with a single
878 // base class and no members also suppress the warning?
879 if (Entity.getKind() != InitializedEntity::EK_Member || !Entity.getParent())
880 return false;
881
882 auto *ParentRD =
883 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
884 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD))
885 if (CXXRD->getNumBases())
886 return false;
887
888 auto FieldIt = ParentRD->field_begin();
889 assert(FieldIt != ParentRD->field_end() &&
890 "no fields but have initializer for member?");
891 return ++FieldIt == ParentRD->field_end();
892}
893
Richard Smith4e0d2e42013-09-20 20:10:22 +0000894/// Check whether the range of the initializer \p ParentIList from element
895/// \p Index onwards can be used to initialize an object of type \p T. Update
896/// \p Index to indicate how many elements of the list were consumed.
897///
898/// This also fills in \p StructuredList, from element \p StructuredIndex
899/// onwards, with the fully-braced, desugared form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000900void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000901 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000902 QualType T, unsigned &Index,
903 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000904 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000905 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000906
Steve Narofff8ecff22008-05-01 22:18:59 +0000907 if (T->isArrayType())
908 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000909 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000910 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000911 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000912 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000913 else
David Blaikie83d382b2011-09-23 05:06:16 +0000914 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000915
Eli Friedmane0f832b2008-05-25 13:49:22 +0000916 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000917 if (!VerifyOnly)
918 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
919 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000920 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000921 hadError = true;
922 return;
923 }
924
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000925 // Build a structured initializer list corresponding to this subobject.
926 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000927 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
928 StructuredIndex,
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000929 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregor5741efb2009-03-01 17:12:46 +0000930 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000931 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000932
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000933 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000934 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000935 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000936 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000937 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000938 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000939
Richard Smithde229232013-06-06 11:41:05 +0000940 if (!VerifyOnly) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000941 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000942
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000943 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000944 // Update the structured sub-object initializer so that it's ending
945 // range corresponds with the end of the last initializer it used.
Reid Kleckner4a09e882015-12-09 23:18:38 +0000946 if (EndIndex < ParentIList->getNumInits() &&
947 ParentIList->getInit(EndIndex)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000948 SourceLocation EndLoc
949 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
950 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
951 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000952
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000953 // Complain about missing braces.
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +0000954 if ((T->isArrayType() || T->isRecordType()) &&
Richard Smith283e2072017-10-03 20:36:00 +0000955 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
956 !isIdiomaticBraceElisionEntity(Entity)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000957 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Richard Smithde229232013-06-06 11:41:05 +0000958 diag::warn_missing_braces)
Alp Tokerb6cc5922014-05-03 03:45:55 +0000959 << StructuredSubobjectInitList->getSourceRange()
960 << FixItHint::CreateInsertion(
961 StructuredSubobjectInitList->getLocStart(), "{")
962 << FixItHint::CreateInsertion(
963 SemaRef.getLocForEndOfToken(
964 StructuredSubobjectInitList->getLocEnd()),
965 "}");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000966 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000967 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000968}
969
Richard Smith420fa122015-02-12 01:50:05 +0000970/// Warn that \p Entity was of scalar type and was initialized by a
971/// single-element braced initializer list.
972static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
973 SourceRange Braces) {
974 // Don't warn during template instantiation. If the initialization was
975 // non-dependent, we warned during the initial parse; otherwise, the
976 // type might not be scalar in some uses of the template.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000977 if (S.inTemplateInstantiation())
Richard Smith420fa122015-02-12 01:50:05 +0000978 return;
979
980 unsigned DiagID = 0;
981
982 switch (Entity.getKind()) {
983 case InitializedEntity::EK_VectorElement:
984 case InitializedEntity::EK_ComplexElement:
985 case InitializedEntity::EK_ArrayElement:
986 case InitializedEntity::EK_Parameter:
987 case InitializedEntity::EK_Parameter_CF_Audited:
988 case InitializedEntity::EK_Result:
989 // Extra braces here are suspicious.
990 DiagID = diag::warn_braces_around_scalar_init;
991 break;
992
993 case InitializedEntity::EK_Member:
994 // Warn on aggregate initialization but not on ctor init list or
995 // default member initializer.
996 if (Entity.getParent())
997 DiagID = diag::warn_braces_around_scalar_init;
998 break;
999
1000 case InitializedEntity::EK_Variable:
1001 case InitializedEntity::EK_LambdaCapture:
1002 // No warning, might be direct-list-initialization.
1003 // FIXME: Should we warn for copy-list-initialization in these cases?
1004 break;
1005
1006 case InitializedEntity::EK_New:
1007 case InitializedEntity::EK_Temporary:
1008 case InitializedEntity::EK_CompoundLiteralInit:
1009 // No warning, braces are part of the syntax of the underlying construct.
1010 break;
1011
1012 case InitializedEntity::EK_RelatedResult:
1013 // No warning, we already warned when initializing the result.
1014 break;
1015
1016 case InitializedEntity::EK_Exception:
1017 case InitializedEntity::EK_Base:
1018 case InitializedEntity::EK_Delegating:
1019 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00001020 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Richard Smith7873de02016-08-11 22:25:46 +00001021 case InitializedEntity::EK_Binding:
Richard Smith420fa122015-02-12 01:50:05 +00001022 llvm_unreachable("unexpected braced scalar init");
1023 }
1024
1025 if (DiagID) {
1026 S.Diag(Braces.getBegin(), DiagID)
1027 << Braces
1028 << FixItHint::CreateRemoval(Braces.getBegin())
1029 << FixItHint::CreateRemoval(Braces.getEnd());
1030 }
1031}
1032
Richard Smith4e0d2e42013-09-20 20:10:22 +00001033/// Check whether the initializer \p IList (that was written with explicit
1034/// braces) can be used to initialize an object of type \p T.
1035///
1036/// This also fills in \p StructuredList with the fully-braced, desugared
1037/// form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +00001038void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001039 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001040 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001041 bool TopLevelObject) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001042 if (!VerifyOnly) {
1043 SyntacticToSemantic[IList] = StructuredList;
1044 StructuredList->setSyntacticForm(IList);
1045 }
Richard Smith4e0d2e42013-09-20 20:10:22 +00001046
1047 unsigned Index = 0, StructuredIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001048 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +00001049 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001050 if (!VerifyOnly) {
Eli Friedman91f5ae52012-02-23 02:25:10 +00001051 QualType ExprTy = T;
1052 if (!ExprTy->isArrayType())
1053 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001054 IList->setType(ExprTy);
1055 StructuredList->setType(ExprTy);
1056 }
Eli Friedman85f54972008-05-25 13:22:35 +00001057 if (hadError)
1058 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001059
Eli Friedman85f54972008-05-25 13:22:35 +00001060 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001061 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001062 if (VerifyOnly) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001063 if (SemaRef.getLangOpts().CPlusPlus ||
1064 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001065 IList->getType()->isVectorType())) {
1066 hadError = true;
1067 }
1068 return;
1069 }
1070
Eli Friedmanbd327452009-05-29 20:20:05 +00001071 if (StructuredIndex == 1 &&
Hans Wennborg950f3182013-05-16 09:22:40 +00001072 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1073 SIF_None) {
Richard Smith1b98ccc2014-07-19 01:39:17 +00001074 unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001075 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001076 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +00001077 hadError = true;
1078 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001079 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +00001080 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +00001081 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +00001082 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +00001083 // Don't complain for incomplete types, since we'll get an error
1084 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001085 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001086 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001087 CurrentObjectType->isArrayType()? 0 :
1088 CurrentObjectType->isVectorType()? 1 :
1089 CurrentObjectType->isScalarType()? 2 :
1090 CurrentObjectType->isUnionType()? 3 :
1091 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001092
Richard Smith1b98ccc2014-07-19 01:39:17 +00001093 unsigned DK = diag::ext_excess_initializers;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001094 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanbd327452009-05-29 20:20:05 +00001095 DK = diag::err_excess_initializers;
1096 hadError = true;
1097 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00001098 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman425038c2009-07-07 21:53:06 +00001099 DK = diag::err_excess_initializers;
1100 hadError = true;
1101 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001102
Chris Lattnerb0912a52009-02-24 22:50:46 +00001103 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001104 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001105 }
1106 }
Eli Friedman6fcdec22008-05-19 20:20:43 +00001107
Richard Smith420fa122015-02-12 01:50:05 +00001108 if (!VerifyOnly && T->isScalarType() &&
1109 IList->getNumInits() == 1 && !isa<InitListExpr>(IList->getInit(0)))
1110 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
Steve Narofff8ecff22008-05-01 22:18:59 +00001111}
1112
Anders Carlsson6cabf312010-01-23 23:23:01 +00001113void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001114 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001115 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001116 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001117 unsigned &Index,
1118 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001119 unsigned &StructuredIndex,
1120 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001121 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1122 // Explicitly braced initializer for complex type can be real+imaginary
1123 // parts.
1124 CheckComplexType(Entity, IList, DeclType, Index,
1125 StructuredList, StructuredIndex);
1126 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +00001127 CheckScalarType(Entity, IList, DeclType, Index,
1128 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001129 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001130 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +00001131 StructuredList, StructuredIndex);
Richard Smithe20c83d2012-07-07 08:35:56 +00001132 } else if (DeclType->isRecordType()) {
1133 assert(DeclType->isAggregateType() &&
1134 "non-aggregate records should be handed in CheckSubElementType");
1135 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith872307e2016-03-08 22:17:41 +00001136 auto Bases =
1137 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
1138 CXXRecordDecl::base_class_iterator());
1139 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1140 Bases = CXXRD->bases();
1141 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1142 SubobjectIsDesignatorContext, Index, StructuredList,
1143 StructuredIndex, TopLevelObject);
Richard Smithe20c83d2012-07-07 08:35:56 +00001144 } else if (DeclType->isArrayType()) {
1145 llvm::APSInt Zero(
1146 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1147 false);
1148 CheckArrayType(Entity, IList, DeclType, Zero,
1149 SubobjectIsDesignatorContext, Index,
1150 StructuredList, StructuredIndex);
Steve Naroffeaf58532008-08-10 16:05:48 +00001151 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1152 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001153 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001154 if (!VerifyOnly)
1155 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1156 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +00001157 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +00001158 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +00001159 CheckReferenceType(Entity, IList, DeclType, Index,
1160 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +00001161 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001162 if (!VerifyOnly)
1163 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
1164 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +00001165 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +00001166 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001167 if (!VerifyOnly)
1168 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1169 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +00001170 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +00001171 }
1172}
1173
Anders Carlsson6cabf312010-01-23 23:23:01 +00001174void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001175 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001176 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001177 unsigned &Index,
1178 InitListExpr *StructuredList,
1179 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +00001180 Expr *expr = IList->getInit(Index);
Richard Smith72752e82013-05-31 02:56:17 +00001181
1182 if (ElemType->isReferenceType())
1183 return CheckReferenceType(Entity, IList, ElemType, Index,
1184 StructuredList, StructuredIndex);
1185
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001186 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Yunzhong Gaocb779302015-06-10 00:27:52 +00001187 if (SubInitList->getNumInits() == 1 &&
1188 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1189 SIF_None) {
1190 expr = SubInitList->getInit(0);
1191 } else if (!SemaRef.getLangOpts().CPlusPlus) {
Richard Smith4e0d2e42013-09-20 20:10:22 +00001192 InitListExpr *InnerStructuredList
Richard Smithe20c83d2012-07-07 08:35:56 +00001193 = getStructuredSubobjectInit(IList, Index, ElemType,
1194 StructuredList, StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +00001195 SubInitList->getSourceRange(), true);
Richard Smith4e0d2e42013-09-20 20:10:22 +00001196 CheckExplicitInitList(Entity, SubInitList, ElemType,
1197 InnerStructuredList);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001198
1199 if (!hadError && !VerifyOnly) {
1200 bool RequiresSecondPass = false;
1201 FillInEmptyInitializations(Entity, InnerStructuredList,
Richard Smithf3b4ca82018-02-07 22:25:16 +00001202 RequiresSecondPass, StructuredList,
1203 StructuredIndex);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001204 if (RequiresSecondPass && !hadError)
1205 FillInEmptyInitializations(Entity, InnerStructuredList,
Richard Smithf3b4ca82018-02-07 22:25:16 +00001206 RequiresSecondPass, StructuredList,
1207 StructuredIndex);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001208 }
Richard Smithe20c83d2012-07-07 08:35:56 +00001209 ++StructuredIndex;
1210 ++Index;
1211 return;
1212 }
Richard Smithe20c83d2012-07-07 08:35:56 +00001213 // C++ initialization is handled later.
Richard Smithc4158e862014-07-18 04:47:25 +00001214 } else if (isa<ImplicitValueInitExpr>(expr)) {
Richard Smith8aa561b2014-07-17 23:12:06 +00001215 // This happens during template instantiation when we see an InitListExpr
1216 // that we've already checked once.
Richard Smithc4158e862014-07-18 04:47:25 +00001217 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
Richard Smith8aa561b2014-07-17 23:12:06 +00001218 "found implicit initialization for the wrong type");
1219 if (!VerifyOnly)
1220 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1221 ++Index;
1222 return;
Richard Smithe20c83d2012-07-07 08:35:56 +00001223 }
1224
Richard Smith3c567fc2015-02-12 01:55:09 +00001225 if (SemaRef.getLangOpts().CPlusPlus) {
1226 // C++ [dcl.init.aggr]p2:
1227 // Each member is copy-initialized from the corresponding
1228 // initializer-clause.
1229
1230 // FIXME: Better EqualLoc?
1231 InitializationKind Kind =
1232 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
1233 InitializationSequence Seq(SemaRef, Entity, Kind, expr,
1234 /*TopLevelOfInitList*/ true);
1235
1236 // C++14 [dcl.init.aggr]p13:
1237 // If the assignment-expression can initialize a member, the member is
1238 // initialized. Otherwise [...] brace elision is assumed
1239 //
1240 // Brace elision is never performed if the element is not an
1241 // assignment-expression.
1242 if (Seq || isa<InitListExpr>(expr)) {
1243 if (!VerifyOnly) {
1244 ExprResult Result =
1245 Seq.Perform(SemaRef, Entity, Kind, expr);
1246 if (Result.isInvalid())
1247 hadError = true;
1248
1249 UpdateStructuredListElement(StructuredList, StructuredIndex,
1250 Result.getAs<Expr>());
Richard Smith40574cc2015-02-16 04:42:59 +00001251 } else if (!Seq)
1252 hadError = true;
Richard Smith3c567fc2015-02-12 01:55:09 +00001253 ++Index;
1254 return;
1255 }
1256
1257 // Fall through for subaggregate initialization
1258 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1259 // FIXME: Need to handle atomic aggregate types with implicit init lists.
John McCall5decec92011-02-21 07:57:55 +00001260 return CheckScalarType(Entity, IList, ElemType, Index,
1261 StructuredList, StructuredIndex);
Richard Smith3c567fc2015-02-12 01:55:09 +00001262 } else if (const ArrayType *arrayType =
1263 SemaRef.Context.getAsArrayType(ElemType)) {
John McCall5decec92011-02-21 07:57:55 +00001264 // arrayType can be incomplete if we're initializing a flexible
1265 // array member. There's nothing we can do with the completed
1266 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001267
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001268 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedmand8d7a372011-09-26 19:09:09 +00001269 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001270 CheckStringInit(expr, ElemType, arrayType, SemaRef);
1271 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedmand8d7a372011-09-26 19:09:09 +00001272 }
Douglas Gregord14247a2009-01-30 22:09:00 +00001273 ++Index;
John McCall5decec92011-02-21 07:57:55 +00001274 return;
Douglas Gregord14247a2009-01-30 22:09:00 +00001275 }
John McCall5decec92011-02-21 07:57:55 +00001276
1277 // Fall through for subaggregate initialization.
1278
John McCall5decec92011-02-21 07:57:55 +00001279 } else {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001280 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
Egor Churaev45fe70f2017-05-10 10:28:34 +00001281 ElemType->isOpenCLSpecificType()) && "Unexpected type");
Richard Smith3c567fc2015-02-12 01:55:09 +00001282
John McCall5decec92011-02-21 07:57:55 +00001283 // C99 6.7.8p13:
1284 //
1285 // The initializer for a structure or union object that has
1286 // automatic storage duration shall be either an initializer
1287 // list as described below, or a single expression that has
1288 // compatible structure or union type. In the latter case, the
1289 // initial value of the object, including unnamed members, is
1290 // that of the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001291 ExprResult ExprRes = expr;
Richard Smith3c567fc2015-02-12 01:55:09 +00001292 if (SemaRef.CheckSingleAssignmentConstraints(
1293 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
John Wiegley01296292011-04-08 18:41:53 +00001294 if (ExprRes.isInvalid())
1295 hadError = true;
1296 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001297 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001298 if (ExprRes.isInvalid())
1299 hadError = true;
John Wiegley01296292011-04-08 18:41:53 +00001300 }
1301 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001302 ExprRes.getAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +00001303 ++Index;
1304 return;
1305 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001306 ExprRes.get();
John McCall5decec92011-02-21 07:57:55 +00001307 // Fall through for subaggregate initialization
1308 }
1309
1310 // C++ [dcl.init.aggr]p12:
1311 //
1312 // [...] Otherwise, if the member is itself a non-empty
1313 // subaggregate, brace elision is assumed and the initializer is
1314 // considered for the initialization of the first member of
1315 // the subaggregate.
Yaxun Liua91da4b2016-10-11 15:53:28 +00001316 // OpenCL vector initializer is handled elsewhere.
1317 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1318 ElemType->isAggregateType()) {
John McCall5decec92011-02-21 07:57:55 +00001319 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1320 StructuredIndex);
1321 ++StructuredIndex;
1322 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001323 if (!VerifyOnly) {
1324 // We cannot initialize this element, so let
1325 // PerformCopyInitialization produce the appropriate diagnostic.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001326 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001327 /*TopLevelOfInitList=*/true);
1328 }
John McCall5decec92011-02-21 07:57:55 +00001329 hadError = true;
1330 ++Index;
1331 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +00001332 }
Eli Friedman23a9e312008-05-19 19:16:24 +00001333}
1334
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001335void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1336 InitListExpr *IList, QualType DeclType,
1337 unsigned &Index,
1338 InitListExpr *StructuredList,
1339 unsigned &StructuredIndex) {
1340 assert(Index == 0 && "Index in explicit init list must be zero");
1341
1342 // As an extension, clang supports complex initializers, which initialize
1343 // a complex number component-wise. When an explicit initializer list for
1344 // a complex number contains two two initializers, this extension kicks in:
1345 // it exepcts the initializer list to contain two elements convertible to
1346 // the element type of the complex type. The first element initializes
1347 // the real part, and the second element intitializes the imaginary part.
1348
1349 if (IList->getNumInits() != 2)
1350 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1351 StructuredIndex);
1352
1353 // This is an extension in C. (The builtin _Complex type does not exist
1354 // in the C++ standard.)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001355 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001356 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
1357 << IList->getSourceRange();
1358
1359 // Initialize the complex number.
1360 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1361 InitializedEntity ElementEntity =
1362 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1363
1364 for (unsigned i = 0; i < 2; ++i) {
1365 ElementEntity.setElementIndex(Index);
1366 CheckSubElementType(ElementEntity, IList, elementType, Index,
1367 StructuredList, StructuredIndex);
1368 }
1369}
1370
Anders Carlsson6cabf312010-01-23 23:23:01 +00001371void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001372 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +00001373 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001374 InitListExpr *StructuredList,
1375 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +00001376 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +00001377 if (!VerifyOnly)
1378 SemaRef.Diag(IList->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001379 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smithc8239732011-10-18 21:39:00 +00001380 diag::warn_cxx98_compat_empty_scalar_initializer :
1381 diag::err_empty_scalar_initializer)
1382 << IList->getSourceRange();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001383 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001384 ++Index;
1385 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001386 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001387 }
John McCall643169b2010-11-11 00:46:36 +00001388
1389 Expr *expr = IList->getInit(Index);
1390 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Richard Smithfe9d2c02013-11-19 03:41:32 +00001391 // FIXME: This is invalid, and accepting it causes overload resolution
1392 // to pick the wrong overload in some corner cases.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001393 if (!VerifyOnly)
1394 SemaRef.Diag(SubIList->getLocStart(),
Richard Smithfe9d2c02013-11-19 03:41:32 +00001395 diag::ext_many_braces_around_scalar_init)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001396 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001397
1398 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1399 StructuredIndex);
1400 return;
1401 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001402 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001403 SemaRef.Diag(expr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001404 diag::err_designator_for_scalar_init)
1405 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001406 hadError = true;
1407 ++Index;
1408 ++StructuredIndex;
1409 return;
1410 }
1411
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001412 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001413 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001414 hadError = true;
1415 ++Index;
1416 return;
1417 }
1418
John McCall643169b2010-11-11 00:46:36 +00001419 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001420 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001421 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +00001422
Craig Topperc3ec1492014-05-26 06:22:03 +00001423 Expr *ResultExpr = nullptr;
John McCall643169b2010-11-11 00:46:36 +00001424
1425 if (Result.isInvalid())
1426 hadError = true; // types weren't compatible.
1427 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001428 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001429
John McCall643169b2010-11-11 00:46:36 +00001430 if (ResultExpr != expr) {
1431 // The type was promoted, update initializer list.
1432 IList->setInit(Index, ResultExpr);
1433 }
1434 }
1435 if (hadError)
1436 ++StructuredIndex;
1437 else
1438 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1439 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001440}
1441
Anders Carlsson6cabf312010-01-23 23:23:01 +00001442void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1443 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +00001444 unsigned &Index,
1445 InitListExpr *StructuredList,
1446 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001447 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001448 // FIXME: It would be wonderful if we could point at the actual member. In
1449 // general, it would be useful to pass location information down the stack,
1450 // so that we know the location (or decl) of the "current object" being
1451 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001452 if (!VerifyOnly)
1453 SemaRef.Diag(IList->getLocStart(),
1454 diag::err_init_reference_member_uninitialized)
1455 << DeclType
1456 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +00001457 hadError = true;
1458 ++Index;
1459 ++StructuredIndex;
1460 return;
1461 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001462
1463 Expr *expr = IList->getInit(Index);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001464 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001465 if (!VerifyOnly)
1466 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1467 << DeclType << IList->getSourceRange();
1468 hadError = true;
1469 ++Index;
1470 ++StructuredIndex;
1471 return;
1472 }
1473
1474 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001475 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001476 hadError = true;
1477 ++Index;
1478 return;
1479 }
1480
1481 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001482 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1483 /*TopLevelOfInitList=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001484
1485 if (Result.isInvalid())
1486 hadError = true;
1487
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001488 expr = Result.getAs<Expr>();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001489 IList->setInit(Index, expr);
1490
1491 if (hadError)
1492 ++StructuredIndex;
1493 else
1494 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1495 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001496}
1497
Anders Carlsson6cabf312010-01-23 23:23:01 +00001498void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001499 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001500 unsigned &Index,
1501 InitListExpr *StructuredList,
1502 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001503 const VectorType *VT = DeclType->getAs<VectorType>();
1504 unsigned maxElements = VT->getNumElements();
1505 unsigned numEltsInit = 0;
1506 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001507
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001508 if (Index >= IList->getNumInits()) {
1509 // Make sure the element type can be value-initialized.
1510 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001511 CheckEmptyInitializable(
1512 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1513 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001514 return;
1515 }
1516
David Blaikiebbafb8a2012-03-11 07:00:24 +00001517 if (!SemaRef.getLangOpts().OpenCL) {
John McCall6a16b2f2010-10-30 00:11:39 +00001518 // If the initializing element is a vector, try to copy-initialize
1519 // instead of breaking it apart (which is doomed to failure anyway).
1520 Expr *Init = IList->getInit(Index);
1521 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001522 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001523 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001524 hadError = true;
1525 ++Index;
1526 return;
1527 }
1528
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001529 ExprResult Result =
1530 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
1531 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001532
Craig Topperc3ec1492014-05-26 06:22:03 +00001533 Expr *ResultExpr = nullptr;
John McCall6a16b2f2010-10-30 00:11:39 +00001534 if (Result.isInvalid())
1535 hadError = true; // types weren't compatible.
1536 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001537 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001538
John McCall6a16b2f2010-10-30 00:11:39 +00001539 if (ResultExpr != Init) {
1540 // The type was promoted, update initializer list.
1541 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001542 }
1543 }
John McCall6a16b2f2010-10-30 00:11:39 +00001544 if (hadError)
1545 ++StructuredIndex;
1546 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001547 UpdateStructuredListElement(StructuredList, StructuredIndex,
1548 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001549 ++Index;
1550 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001551 }
Mike Stump11289f42009-09-09 15:08:12 +00001552
John McCall6a16b2f2010-10-30 00:11:39 +00001553 InitializedEntity ElementEntity =
1554 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001555
John McCall6a16b2f2010-10-30 00:11:39 +00001556 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1557 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001558 if (Index >= IList->getNumInits()) {
1559 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001560 CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
John McCall6a16b2f2010-10-30 00:11:39 +00001561 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001562 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001563
John McCall6a16b2f2010-10-30 00:11:39 +00001564 ElementEntity.setElementIndex(Index);
1565 CheckSubElementType(ElementEntity, IList, elementType, Index,
1566 StructuredList, StructuredIndex);
1567 }
James Molloy9eef2652014-06-20 14:35:13 +00001568
1569 if (VerifyOnly)
1570 return;
1571
1572 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1573 const VectorType *T = Entity.getType()->getAs<VectorType>();
1574 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1575 T->getVectorKind() == VectorType::NeonPolyVector)) {
1576 // The ability to use vector initializer lists is a GNU vector extension
1577 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1578 // endian machines it works fine, however on big endian machines it
1579 // exhibits surprising behaviour:
1580 //
1581 // uint32x2_t x = {42, 64};
1582 // return vget_lane_u32(x, 0); // Will return 64.
1583 //
1584 // Because of this, explicitly call out that it is non-portable.
1585 //
1586 SemaRef.Diag(IList->getLocStart(),
1587 diag::warn_neon_vector_initializer_non_portable);
1588
1589 const char *typeCode;
1590 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1591
1592 if (elementType->isFloatingType())
1593 typeCode = "f";
1594 else if (elementType->isSignedIntegerType())
1595 typeCode = "s";
1596 else if (elementType->isUnsignedIntegerType())
1597 typeCode = "u";
1598 else
1599 llvm_unreachable("Invalid element type!");
1600
1601 SemaRef.Diag(IList->getLocStart(),
1602 SemaRef.Context.getTypeSize(VT) > 64 ?
1603 diag::note_neon_vector_initializer_non_portable_q :
1604 diag::note_neon_vector_initializer_non_portable)
1605 << typeCode << typeSize;
1606 }
1607
John McCall6a16b2f2010-10-30 00:11:39 +00001608 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001609 }
John McCall6a16b2f2010-10-30 00:11:39 +00001610
1611 InitializedEntity ElementEntity =
1612 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001613
John McCall6a16b2f2010-10-30 00:11:39 +00001614 // OpenCL initializers allows vectors to be constructed from vectors.
1615 for (unsigned i = 0; i < maxElements; ++i) {
1616 // Don't attempt to go past the end of the init list
1617 if (Index >= IList->getNumInits())
1618 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001619
John McCall6a16b2f2010-10-30 00:11:39 +00001620 ElementEntity.setElementIndex(Index);
1621
1622 QualType IType = IList->getInit(Index)->getType();
1623 if (!IType->isVectorType()) {
1624 CheckSubElementType(ElementEntity, IList, elementType, Index,
1625 StructuredList, StructuredIndex);
1626 ++numEltsInit;
1627 } else {
1628 QualType VecType;
1629 const VectorType *IVT = IType->getAs<VectorType>();
1630 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001631
John McCall6a16b2f2010-10-30 00:11:39 +00001632 if (IType->isExtVectorType())
1633 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1634 else
1635 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001636 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001637 CheckSubElementType(ElementEntity, IList, VecType, Index,
1638 StructuredList, StructuredIndex);
1639 numEltsInit += numIElts;
1640 }
1641 }
1642
1643 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001644 if (numEltsInit != maxElements) {
1645 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001646 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001647 diag::err_vector_incorrect_num_initializers)
1648 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1649 hadError = true;
1650 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001651}
1652
Anders Carlsson6cabf312010-01-23 23:23:01 +00001653void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001654 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001655 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001656 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001657 unsigned &Index,
1658 InitListExpr *StructuredList,
1659 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001660 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1661
Steve Narofff8ecff22008-05-01 22:18:59 +00001662 // Check for the special-case of initializing an array with a string.
1663 if (Index < IList->getNumInits()) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001664 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1665 SIF_None) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001666 // We place the string literal directly into the resulting
1667 // initializer list. This is the only place where the structure
1668 // of the structured initializer list doesn't match exactly,
1669 // because doing so would involve allocating one character
1670 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001671 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001672 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1673 UpdateStructuredListElement(StructuredList, StructuredIndex,
1674 IList->getInit(Index));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001675 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1676 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001677 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001678 return;
1679 }
1680 }
John McCall66884dd2011-02-21 07:22:22 +00001681 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001682 // Check for VLAs; in standard C it would be possible to check this
1683 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1684 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001685 if (!VerifyOnly)
1686 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1687 diag::err_variable_object_no_init)
1688 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001689 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001690 ++Index;
1691 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001692 return;
1693 }
1694
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001695 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001696 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1697 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001698 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001699 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001700 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001701 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001702 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001703 maxElementsKnown = true;
1704 }
1705
John McCall66884dd2011-02-21 07:22:22 +00001706 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001707 while (Index < IList->getNumInits()) {
1708 Expr *Init = IList->getInit(Index);
1709 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001710 // If we're not the subobject that matches up with the '{' for
1711 // the designator, we shouldn't be handling the
1712 // designator. Return immediately.
1713 if (!SubobjectIsDesignatorContext)
1714 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001715
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001716 // Handle this designated initializer. elementIndex will be
1717 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001718 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001719 DeclType, nullptr, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001720 StructuredList, StructuredIndex, true,
1721 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001722 hadError = true;
1723 continue;
1724 }
1725
Douglas Gregor033d1252009-01-23 16:54:12 +00001726 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001727 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001728 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001729 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001730 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001731
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001732 // If the array is of incomplete type, keep track of the number of
1733 // elements in the initializer.
1734 if (!maxElementsKnown && elementIndex > maxElements)
1735 maxElements = elementIndex;
1736
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001737 continue;
1738 }
1739
1740 // If we know the maximum number of elements, and we've already
1741 // hit it, stop consuming elements in the initializer list.
1742 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001743 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001744
Anders Carlsson6cabf312010-01-23 23:23:01 +00001745 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001746 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001747 Entity);
1748 // Check this element.
1749 CheckSubElementType(ElementEntity, IList, elementType, Index,
1750 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001751 ++elementIndex;
1752
1753 // If the array is of incomplete type, keep track of the number of
1754 // elements in the initializer.
1755 if (!maxElementsKnown && elementIndex > maxElements)
1756 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001757 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001758 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001759 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001760 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001761 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Richard Smith73edb6d2017-01-24 23:18:28 +00001762 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001763 // Sizing an array implicitly to zero is not allowed by ISO C,
1764 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001765 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001766 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001767 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001768
Mike Stump11289f42009-09-09 15:08:12 +00001769 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001770 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001771 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001772 if (!hadError && VerifyOnly) {
Richard Smith0511d232016-10-05 22:41:02 +00001773 // If there are any members of the array that get value-initialized, check
1774 // that is possible. That happens if we know the bound and don't have
1775 // enough elements, or if we're performing an array new with an unknown
1776 // bound.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001777 // FIXME: This needs to detect holes left by designated initializers too.
Richard Smith0511d232016-10-05 22:41:02 +00001778 if ((maxElementsKnown && elementIndex < maxElements) ||
1779 Entity.isVariableLengthArrayNew())
Richard Smith454a7cd2014-06-03 08:26:00 +00001780 CheckEmptyInitializable(InitializedEntity::InitializeElement(
1781 SemaRef.Context, 0, Entity),
1782 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001783 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001784}
1785
Eli Friedman3fa64df2011-08-23 22:24:57 +00001786bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1787 Expr *InitExpr,
1788 FieldDecl *Field,
1789 bool TopLevelObject) {
1790 // Handle GNU flexible array initializers.
1791 unsigned FlexArrayDiag;
1792 if (isa<InitListExpr>(InitExpr) &&
1793 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1794 // Empty flexible array init always allowed as an extension
1795 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001796 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedman3fa64df2011-08-23 22:24:57 +00001797 // Disallow flexible array init in C++; it is not required for gcc
1798 // compatibility, and it needs work to IRGen correctly in general.
1799 FlexArrayDiag = diag::err_flexible_array_init;
1800 } else if (!TopLevelObject) {
1801 // Disallow flexible array init on non-top-level object
1802 FlexArrayDiag = diag::err_flexible_array_init;
1803 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1804 // Disallow flexible array init on anything which is not a variable.
1805 FlexArrayDiag = diag::err_flexible_array_init;
1806 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1807 // Disallow flexible array init on local variables.
1808 FlexArrayDiag = diag::err_flexible_array_init;
1809 } else {
1810 // Allow other cases.
1811 FlexArrayDiag = diag::ext_flexible_array_init;
1812 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001813
1814 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001815 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001816 FlexArrayDiag)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001817 << InitExpr->getLocStart();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001818 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1819 << Field;
1820 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001821
1822 return FlexArrayDiag != diag::ext_flexible_array_init;
1823}
1824
Richard Smith872307e2016-03-08 22:17:41 +00001825void InitListChecker::CheckStructUnionTypes(
1826 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
1827 CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field,
1828 bool SubobjectIsDesignatorContext, unsigned &Index,
1829 InitListExpr *StructuredList, unsigned &StructuredIndex,
1830 bool TopLevelObject) {
1831 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001832
Eli Friedman23a9e312008-05-19 19:16:24 +00001833 // If the record is invalid, some of it's members are invalid. To avoid
1834 // confusion, we forgo checking the intializer for the entire record.
1835 if (structDecl->isInvalidDecl()) {
Richard Smith845aa662012-09-28 21:23:50 +00001836 // Assume it was supposed to consume a single initializer.
1837 ++Index;
Eli Friedman23a9e312008-05-19 19:16:24 +00001838 hadError = true;
1839 return;
Mike Stump11289f42009-09-09 15:08:12 +00001840 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001841
1842 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001843 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith852c9db2013-04-20 22:23:05 +00001844
1845 // If there's a default initializer, use it.
1846 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1847 if (VerifyOnly)
1848 return;
1849 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1850 Field != FieldEnd; ++Field) {
1851 if (Field->hasInClassInitializer()) {
1852 StructuredList->setInitializedFieldInUnion(*Field);
1853 // FIXME: Actually build a CXXDefaultInitExpr?
1854 return;
1855 }
1856 }
1857 }
1858
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001859 // Value-initialize the first member of the union that isn't an unnamed
1860 // bitfield.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001861 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1862 Field != FieldEnd; ++Field) {
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001863 if (!Field->isUnnamedBitfield()) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001864 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001865 CheckEmptyInitializable(
1866 InitializedEntity::InitializeMember(*Field, &Entity),
1867 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001868 else
David Blaikie40ed2972012-06-06 20:45:41 +00001869 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001870 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001871 }
1872 }
1873 return;
1874 }
1875
Richard Smith872307e2016-03-08 22:17:41 +00001876 bool InitializedSomething = false;
1877
1878 // If we have any base classes, they are initialized prior to the fields.
1879 for (auto &Base : Bases) {
1880 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
1881 SourceLocation InitLoc = Init ? Init->getLocStart() : IList->getLocEnd();
1882
1883 // Designated inits always initialize fields, so if we see one, all
1884 // remaining base classes have no explicit initializer.
1885 if (Init && isa<DesignatedInitExpr>(Init))
1886 Init = nullptr;
1887
1888 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
1889 SemaRef.Context, &Base, false, &Entity);
1890 if (Init) {
1891 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
1892 StructuredList, StructuredIndex);
1893 InitializedSomething = true;
1894 } else if (VerifyOnly) {
1895 CheckEmptyInitializable(BaseEntity, InitLoc);
1896 }
1897 }
1898
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001899 // If structDecl is a forward declaration, this loop won't do
1900 // anything except look at designated initializers; That's okay,
1901 // because an error should get printed out elsewhere. It might be
1902 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001903 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001904 RecordDecl::field_iterator FieldEnd = RD->field_end();
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00001905 bool CheckForMissingFields =
1906 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
1907
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001908 while (Index < IList->getNumInits()) {
1909 Expr *Init = IList->getInit(Index);
1910
1911 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001912 // If we're not the subobject that matches up with the '{' for
1913 // the designator, we shouldn't be handling the
1914 // designator. Return immediately.
1915 if (!SubobjectIsDesignatorContext)
1916 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001917
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001918 // Handle this designated initializer. Field will be updated to
1919 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001920 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001921 DeclType, &Field, nullptr, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001922 StructuredList, StructuredIndex,
1923 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001924 hadError = true;
1925
Douglas Gregora9add4e2009-02-12 19:00:39 +00001926 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001927
1928 // Disable check for missing fields when designators are used.
1929 // This matches gcc behaviour.
1930 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001931 continue;
1932 }
1933
1934 if (Field == FieldEnd) {
1935 // We've run out of fields. We're done.
1936 break;
1937 }
1938
Douglas Gregora9add4e2009-02-12 19:00:39 +00001939 // We've already initialized a member of a union. We're done.
1940 if (InitializedSomething && DeclType->isUnionType())
1941 break;
1942
Douglas Gregor91f84212008-12-11 16:49:14 +00001943 // If we've hit the flexible array member at the end, we're done.
1944 if (Field->getType()->isIncompleteArrayType())
1945 break;
1946
Douglas Gregor51695702009-01-29 16:53:55 +00001947 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001948 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001949 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001950 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001951 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001952
Douglas Gregora82064c2011-06-29 21:51:31 +00001953 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001954 bool InvalidUse;
1955 if (VerifyOnly)
Manman Ren073db022016-03-10 18:53:19 +00001956 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001957 else
David Blaikie40ed2972012-06-06 20:45:41 +00001958 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001959 IList->getInit(Index)->getLocStart());
1960 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001961 ++Index;
1962 ++Field;
1963 hadError = true;
1964 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001965 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001966
Anders Carlsson6cabf312010-01-23 23:23:01 +00001967 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001968 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001969 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1970 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001971 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001972
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001973 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001974 // Initialize the first field within the union.
David Blaikie40ed2972012-06-06 20:45:41 +00001975 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001976 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001977
1978 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001979 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001980
John McCalle40b58e2010-03-11 19:32:38 +00001981 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001982 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1983 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1984 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001985 // It is possible we have one or more unnamed bitfields remaining.
1986 // Find first (if any) named field and emit warning.
1987 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1988 it != end; ++it) {
Richard Smith852c9db2013-04-20 22:23:05 +00001989 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCalle40b58e2010-03-11 19:32:38 +00001990 SemaRef.Diag(IList->getSourceRange().getEnd(),
Aaron Ballmanb9bb2012014-01-03 14:54:10 +00001991 diag::warn_missing_field_initializers) << *it;
John McCalle40b58e2010-03-11 19:32:38 +00001992 break;
1993 }
1994 }
1995 }
1996
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001997 // Check that any remaining fields can be value-initialized.
1998 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1999 !Field->getType()->isIncompleteArrayType()) {
2000 // FIXME: Should check for holes left by designated initializers too.
2001 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smith852c9db2013-04-20 22:23:05 +00002002 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Richard Smith454a7cd2014-06-03 08:26:00 +00002003 CheckEmptyInitializable(
2004 InitializedEntity::InitializeMember(*Field, &Entity),
2005 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00002006 }
2007 }
2008
Mike Stump11289f42009-09-09 15:08:12 +00002009 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00002010 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002011 return;
2012
David Blaikie40ed2972012-06-06 20:45:41 +00002013 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00002014 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002015 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00002016 ++Index;
2017 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002018 }
2019
Anders Carlsson6cabf312010-01-23 23:23:01 +00002020 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002021 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002022
Anders Carlsson6cabf312010-01-23 23:23:01 +00002023 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002024 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00002025 StructuredList, StructuredIndex);
2026 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002027 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00002028 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00002029}
Steve Narofff8ecff22008-05-01 22:18:59 +00002030
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002031/// Expand a field designator that refers to a member of an
Douglas Gregord5846a12009-04-15 06:41:24 +00002032/// anonymous struct or union into a series of field designators that
2033/// refers to the field within the appropriate subobject.
2034///
Douglas Gregord5846a12009-04-15 06:41:24 +00002035static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00002036 DesignatedInitExpr *DIE,
2037 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002038 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00002039 typedef DesignatedInitExpr::Designator Designator;
2040
Douglas Gregord5846a12009-04-15 06:41:24 +00002041 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002042 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002043 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2044 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2045 if (PI + 1 == PE)
Craig Topperc3ec1492014-05-26 06:22:03 +00002046 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
Douglas Gregord5846a12009-04-15 06:41:24 +00002047 DIE->getDesignator(DesigIdx)->getDotLoc(),
2048 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2049 else
Craig Topperc3ec1492014-05-26 06:22:03 +00002050 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2051 SourceLocation(), SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002052 assert(isa<FieldDecl>(*PI));
2053 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00002054 }
2055
2056 // Expand the current designator into the set of replacement
2057 // designators, so we have a full subobject path down to where the
2058 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00002059 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00002060 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002061}
Mike Stump11289f42009-09-09 15:08:12 +00002062
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002063static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
2064 DesignatedInitExpr *DIE) {
2065 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2066 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2067 for (unsigned I = 0; I < NumIndexExprs; ++I)
2068 IndexExprs[I] = DIE->getSubExpr(I + 1);
David Majnemerf7e36092016-06-23 00:15:04 +00002069 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2070 IndexExprs,
Benjamin Kramerc215e762012-08-24 11:54:20 +00002071 DIE->getEqualOrColonLoc(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002072 DIE->usesGNUSyntax(), DIE->getInit());
2073}
2074
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002075namespace {
2076
2077// Callback to only accept typo corrections that are for field members of
2078// the given struct or union.
2079class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
2080 public:
2081 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
2082 : Record(RD) {}
2083
Craig Toppere14c0f82014-03-12 04:55:44 +00002084 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002085 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2086 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2087 }
2088
2089 private:
2090 RecordDecl *Record;
2091};
2092
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002093} // end anonymous namespace
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002094
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002095/// Check the well-formedness of a C99 designated initializer.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002096///
2097/// Determines whether the designated initializer @p DIE, which
2098/// resides at the given @p Index within the initializer list @p
2099/// IList, is well-formed for a current object of type @p DeclType
2100/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00002101/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002102/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002103///
2104/// @param IList The initializer list in which this designated
2105/// initializer occurs.
2106///
Douglas Gregora5324162009-04-15 04:56:10 +00002107/// @param DIE The designated initializer expression.
2108///
2109/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002110///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002111/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002112/// into which the designation in @p DIE should refer.
2113///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002114/// @param NextField If non-NULL and the first designator in @p DIE is
2115/// a field, this will be set to the field declaration corresponding
2116/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002117///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002118/// @param NextElementIndex If non-NULL and the first designator in @p
2119/// DIE is an array designator or GNU array-range designator, this
2120/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002121///
2122/// @param Index Index into @p IList where the designated initializer
2123/// @p DIE occurs.
2124///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002125/// @param StructuredList The initializer list expression that
2126/// describes all of the subobject initializers in the order they'll
2127/// actually be initialized.
2128///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002129/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002130bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00002131InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002132 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002133 DesignatedInitExpr *DIE,
2134 unsigned DesigIdx,
2135 QualType &CurrentObjectType,
2136 RecordDecl::field_iterator *NextField,
2137 llvm::APSInt *NextElementIndex,
2138 unsigned &Index,
2139 InitListExpr *StructuredList,
2140 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002141 bool FinishSubobjectInit,
2142 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00002143 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002144 // Check the actual initialization for the designated object type.
2145 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00002146
2147 // Temporarily remove the designator expression from the
2148 // initializer list that the child calls see, so that we don't try
2149 // to re-process the designator.
2150 unsigned OldIndex = Index;
2151 IList->setInit(OldIndex, DIE->getInit());
2152
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002153 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002154 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00002155
2156 // Restore the designated initializer expression in the syntactic
2157 // form of the initializer list.
2158 if (IList->getInit(OldIndex) != DIE->getInit())
2159 DIE->setInit(IList->getInit(OldIndex));
2160 IList->setInit(OldIndex, DIE);
2161
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002162 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002163 }
2164
Douglas Gregora5324162009-04-15 04:56:10 +00002165 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002166 bool IsFirstDesignator = (DesigIdx == 0);
2167 if (!VerifyOnly) {
2168 assert((IsFirstDesignator || StructuredList) &&
2169 "Need a non-designated initializer list to start from");
2170
2171 // Determine the structural initializer list that corresponds to the
2172 // current subobject.
Yunzhong Gaocb779302015-06-10 00:27:52 +00002173 if (IsFirstDesignator)
2174 StructuredList = SyntacticToSemantic.lookup(IList);
2175 else {
2176 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2177 StructuredList->getInit(StructuredIndex) : nullptr;
2178 if (!ExistingInit && StructuredList->hasArrayFiller())
2179 ExistingInit = StructuredList->getArrayFiller();
2180
2181 if (!ExistingInit)
2182 StructuredList =
2183 getStructuredSubobjectInit(IList, Index, CurrentObjectType,
2184 StructuredList, StructuredIndex,
2185 SourceRange(D->getLocStart(),
2186 DIE->getLocEnd()));
2187 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2188 StructuredList = Result;
2189 else {
2190 if (DesignatedInitUpdateExpr *E =
2191 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2192 StructuredList = E->getUpdater();
2193 else {
2194 DesignatedInitUpdateExpr *DIUE =
2195 new (SemaRef.Context) DesignatedInitUpdateExpr(SemaRef.Context,
2196 D->getLocStart(), ExistingInit,
2197 DIE->getLocEnd());
2198 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2199 StructuredList = DIUE->getUpdater();
2200 }
2201
2202 // We need to check on source range validity because the previous
2203 // initializer does not have to be an explicit initializer. e.g.,
2204 //
2205 // struct P { int a, b; };
2206 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2207 //
2208 // There is an overwrite taking place because the first braced initializer
2209 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
2210 if (ExistingInit->getSourceRange().isValid()) {
2211 // We are creating an initializer list that initializes the
2212 // subobjects of the current object, but there was already an
2213 // initialization that completely initialized the current
2214 // subobject, e.g., by a compound literal:
2215 //
2216 // struct X { int a, b; };
2217 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2218 //
2219 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2220 // designated initializer re-initializes the whole
2221 // subobject [0], overwriting previous initializers.
2222 SemaRef.Diag(D->getLocStart(),
2223 diag::warn_subobject_initializer_overrides)
2224 << SourceRange(D->getLocStart(), DIE->getLocEnd());
2225
2226 SemaRef.Diag(ExistingInit->getLocStart(),
2227 diag::note_previous_initializer)
2228 << /*FIXME:has side effects=*/0
2229 << ExistingInit->getSourceRange();
2230 }
2231 }
2232 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002233 assert(StructuredList && "Expected a structured initializer list");
2234 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002235
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002236 if (D->isFieldDesignator()) {
2237 // C99 6.7.8p7:
2238 //
2239 // If a designator has the form
2240 //
2241 // . identifier
2242 //
2243 // then the current object (defined below) shall have
2244 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00002245 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002246 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002247 if (!RT) {
2248 SourceLocation Loc = D->getDotLoc();
2249 if (Loc.isInvalid())
2250 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002251 if (!VerifyOnly)
2252 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002253 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002254 ++Index;
2255 return true;
2256 }
2257
Douglas Gregord5846a12009-04-15 06:41:24 +00002258 FieldDecl *KnownField = D->getField();
David Majnemer36ef8982014-08-11 18:33:59 +00002259 if (!KnownField) {
2260 IdentifierInfo *FieldName = D->getFieldName();
2261 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
2262 for (NamedDecl *ND : Lookup) {
2263 if (auto *FD = dyn_cast<FieldDecl>(ND)) {
2264 KnownField = FD;
2265 break;
2266 }
2267 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002268 // In verify mode, don't modify the original.
2269 if (VerifyOnly)
2270 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
David Majnemer36ef8982014-08-11 18:33:59 +00002271 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002272 D = DIE->getDesignator(DesigIdx);
David Majnemer36ef8982014-08-11 18:33:59 +00002273 KnownField = cast<FieldDecl>(*IFD->chain_begin());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002274 break;
2275 }
2276 }
David Majnemer36ef8982014-08-11 18:33:59 +00002277 if (!KnownField) {
2278 if (VerifyOnly) {
2279 ++Index;
2280 return true; // No typo correction when just trying this out.
2281 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002282
David Majnemer36ef8982014-08-11 18:33:59 +00002283 // Name lookup found something, but it wasn't a field.
2284 if (!Lookup.empty()) {
2285 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2286 << FieldName;
2287 SemaRef.Diag(Lookup.front()->getLocation(),
2288 diag::note_field_designator_found);
2289 ++Index;
2290 return true;
2291 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002292
David Majnemer36ef8982014-08-11 18:33:59 +00002293 // Name lookup didn't find anything.
2294 // Determine whether this was a typo for another field name.
Richard Smithf9b15102013-08-17 00:46:16 +00002295 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2296 DeclarationNameInfo(FieldName, D->getFieldLoc()),
David Majnemer36ef8982014-08-11 18:33:59 +00002297 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002298 llvm::make_unique<FieldInitializerValidatorCCC>(RT->getDecl()),
2299 Sema::CTK_ErrorRecovery, RT->getDecl())) {
Richard Smithf9b15102013-08-17 00:46:16 +00002300 SemaRef.diagnoseTypo(
2301 Corrected,
2302 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
David Majnemer36ef8982014-08-11 18:33:59 +00002303 << FieldName << CurrentObjectType);
2304 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
Benjamin Kramerafe718f2011-09-25 02:41:26 +00002305 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002306 } else {
David Majnemer36ef8982014-08-11 18:33:59 +00002307 // Typo correction didn't find anything.
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002308 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
2309 << FieldName << CurrentObjectType;
2310 ++Index;
2311 return true;
2312 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002313 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002314 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002315
David Majnemer58e4ea92014-08-23 01:48:50 +00002316 unsigned FieldIndex = 0;
Akira Hatanaka8eccb9b2017-01-17 19:35:54 +00002317
2318 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2319 FieldIndex = CXXRD->getNumBases();
2320
David Majnemer58e4ea92014-08-23 01:48:50 +00002321 for (auto *FI : RT->getDecl()->fields()) {
2322 if (FI->isUnnamedBitfield())
2323 continue;
Richard Smithfe1bc702016-04-08 19:57:40 +00002324 if (declaresSameEntity(KnownField, FI)) {
2325 KnownField = FI;
David Majnemer58e4ea92014-08-23 01:48:50 +00002326 break;
Richard Smithfe1bc702016-04-08 19:57:40 +00002327 }
David Majnemer58e4ea92014-08-23 01:48:50 +00002328 ++FieldIndex;
2329 }
2330
David Majnemer36ef8982014-08-11 18:33:59 +00002331 RecordDecl::field_iterator Field =
2332 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2333
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002334 // All of the fields of a union are located at the same place in
2335 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00002336 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002337 FieldIndex = 0;
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002338 if (!VerifyOnly) {
2339 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
Richard Smithfe1bc702016-04-08 19:57:40 +00002340 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002341 assert(StructuredList->getNumInits() == 1
2342 && "A union should never have more than one initializer!");
2343
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002344 Expr *ExistingInit = StructuredList->getInit(0);
Vassil Vassilev1a1678e2017-04-14 08:48:08 +00002345 if (ExistingInit) {
2346 // We're about to throw away an initializer, emit warning.
2347 SemaRef.Diag(D->getFieldLoc(),
2348 diag::warn_initializer_overrides)
2349 << D->getSourceRange();
2350 SemaRef.Diag(ExistingInit->getLocStart(),
2351 diag::note_previous_initializer)
2352 << /*FIXME:has side effects=*/0
2353 << ExistingInit->getSourceRange();
2354 }
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002355
2356 // remove existing initializer
2357 StructuredList->resizeInits(SemaRef.Context, 0);
Craig Topperc3ec1492014-05-26 06:22:03 +00002358 StructuredList->setInitializedFieldInUnion(nullptr);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002359 }
2360
David Blaikie40ed2972012-06-06 20:45:41 +00002361 StructuredList->setInitializedFieldInUnion(*Field);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002362 }
Douglas Gregor51695702009-01-29 16:53:55 +00002363 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002364
Douglas Gregora82064c2011-06-29 21:51:31 +00002365 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002366 bool InvalidUse;
2367 if (VerifyOnly)
Manman Ren073db022016-03-10 18:53:19 +00002368 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002369 else
David Blaikie40ed2972012-06-06 20:45:41 +00002370 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002371 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00002372 ++Index;
2373 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002374 }
Douglas Gregora82064c2011-06-29 21:51:31 +00002375
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002376 if (!VerifyOnly) {
2377 // Update the designator with the field declaration.
David Blaikie40ed2972012-06-06 20:45:41 +00002378 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00002379
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002380 // Make sure that our non-designated initializer list has space
2381 // for a subobject corresponding to this field.
2382 if (FieldIndex >= StructuredList->getNumInits())
2383 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2384 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002385
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002386 // This designator names a flexible array member.
2387 if (Field->getType()->isIncompleteArrayType()) {
2388 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00002389 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002390 // We can't designate an object within the flexible array
2391 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002392 if (!VerifyOnly) {
2393 DesignatedInitExpr::Designator *NextD
2394 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002395 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002396 diag::err_designator_into_flexible_array_member)
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002397 << SourceRange(NextD->getLocStart(),
2398 DIE->getLocEnd());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002399 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002400 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002401 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002402 Invalid = true;
2403 }
2404
Chris Lattner001b29c2010-10-10 17:49:49 +00002405 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2406 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002407 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002408 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002409 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002410 diag::err_flexible_array_init_needs_braces)
2411 << DIE->getInit()->getSourceRange();
2412 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002413 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002414 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002415 Invalid = true;
2416 }
2417
Eli Friedman3fa64df2011-08-23 22:24:57 +00002418 // Check GNU flexible array initializer.
David Blaikie40ed2972012-06-06 20:45:41 +00002419 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00002420 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002421 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002422
2423 if (Invalid) {
2424 ++Index;
2425 return true;
2426 }
2427
2428 // Initialize the array.
2429 bool prevHadError = hadError;
2430 unsigned newStructuredIndex = FieldIndex;
2431 unsigned OldIndex = Index;
2432 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00002433
2434 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002435 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002436 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002437 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002438
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002439 IList->setInit(OldIndex, DIE);
2440 if (hadError && !prevHadError) {
2441 ++Field;
2442 ++FieldIndex;
2443 if (NextField)
2444 *NextField = Field;
2445 StructuredIndex = FieldIndex;
2446 return true;
2447 }
2448 } else {
2449 // Recurse to check later designated subobjects.
David Blaikie2d7c57e2012-04-30 02:36:29 +00002450 QualType FieldType = Field->getType();
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002451 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002452
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002453 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002454 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002455 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002456 FieldType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002457 StructuredList, newStructuredIndex,
Alexey Bataev86a489e2016-01-25 05:14:03 +00002458 FinishSubobjectInit, false))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002459 return true;
2460 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002461
2462 // Find the position of the next field to be initialized in this
2463 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002464 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002465 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002466
2467 // If this the first designator, our caller will continue checking
2468 // the rest of this struct/class/union subobject.
2469 if (IsFirstDesignator) {
2470 if (NextField)
2471 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002472 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002473 return false;
2474 }
2475
Douglas Gregor17bd0942009-01-28 23:36:17 +00002476 if (!FinishSubobjectInit)
2477 return false;
2478
Douglas Gregord5846a12009-04-15 06:41:24 +00002479 // We've already initialized something in the union; we're done.
2480 if (RT->getDecl()->isUnion())
2481 return hadError;
2482
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002483 // Check the remaining fields within this class/struct/union subobject.
2484 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002485
Richard Smith872307e2016-03-08 22:17:41 +00002486 auto NoBases =
2487 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
2488 CXXRecordDecl::base_class_iterator());
2489 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2490 false, Index, StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002491 return hadError && !prevHadError;
2492 }
2493
2494 // C99 6.7.8p6:
2495 //
2496 // If a designator has the form
2497 //
2498 // [ constant-expression ]
2499 //
2500 // then the current object (defined below) shall have array
2501 // type and the expression shall be an integer constant
2502 // expression. If the array is of unknown size, any
2503 // nonnegative value is valid.
2504 //
2505 // Additionally, cope with the GNU extension that permits
2506 // designators of the form
2507 //
2508 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00002509 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002510 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002511 if (!VerifyOnly)
2512 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2513 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002514 ++Index;
2515 return true;
2516 }
2517
Craig Topperc3ec1492014-05-26 06:22:03 +00002518 Expr *IndexExpr = nullptr;
Douglas Gregor17bd0942009-01-28 23:36:17 +00002519 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2520 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002521 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00002522 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002523 DesignatedEndIndex = DesignatedStartIndex;
2524 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002525 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00002526
Mike Stump11289f42009-09-09 15:08:12 +00002527 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002528 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002529 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002530 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002531 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002532
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00002533 // Codegen can't handle evaluating array range designators that have side
2534 // effects, because we replicate the AST value for each initialized element.
2535 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2536 // elements with something that has a side effect, so codegen can emit an
2537 // "error unsupported" error instead of miscompiling the app.
2538 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002539 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00002540 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002541 }
2542
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002543 if (isa<ConstantArrayType>(AT)) {
2544 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002545 DesignatedStartIndex
2546 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002547 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00002548 DesignatedEndIndex
2549 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002550 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2551 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00002552 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002553 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002554 diag::err_array_designator_too_large)
2555 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2556 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002557 ++Index;
2558 return true;
2559 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00002560 } else {
Argyrios Kyrtzidis4746c2f2015-07-27 23:16:53 +00002561 unsigned DesignatedIndexBitWidth =
2562 ConstantArrayType::getMaxSizeBits(SemaRef.Context);
2563 DesignatedStartIndex =
2564 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
2565 DesignatedEndIndex =
2566 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002567 DesignatedStartIndex.setIsUnsigned(true);
2568 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002569 }
Mike Stump11289f42009-09-09 15:08:12 +00002570
Eli Friedman1f16b742013-06-11 21:48:11 +00002571 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2572 // We're modifying a string literal init; we have to decompose the string
2573 // so we can modify the individual characters.
2574 ASTContext &Context = SemaRef.Context;
2575 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2576
2577 // Compute the character type
2578 QualType CharTy = AT->getElementType();
2579
2580 // Compute the type of the integer literals.
2581 QualType PromotedCharTy = CharTy;
2582 if (CharTy->isPromotableIntegerType())
2583 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2584 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2585
2586 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2587 // Get the length of the string.
2588 uint64_t StrLen = SL->getLength();
2589 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2590 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2591 StructuredList->resizeInits(Context, StrLen);
2592
2593 // Build a literal for each character in the string, and put them into
2594 // the init list.
2595 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2596 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2597 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002598 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002599 if (CharTy != PromotedCharTy)
2600 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002601 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002602 StructuredList->updateInit(Context, i, Init);
2603 }
2604 } else {
2605 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2606 std::string Str;
2607 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2608
2609 // Get the length of the string.
2610 uint64_t StrLen = Str.size();
2611 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2612 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2613 StructuredList->resizeInits(Context, StrLen);
2614
2615 // Build a literal for each character in the string, and put them into
2616 // the init list.
2617 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2618 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2619 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002620 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002621 if (CharTy != PromotedCharTy)
2622 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002623 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002624 StructuredList->updateInit(Context, i, Init);
2625 }
2626 }
2627 }
2628
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002629 // Make sure that our non-designated initializer list has space
2630 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002631 if (!VerifyOnly &&
2632 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00002633 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00002634 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002635
Douglas Gregor17bd0942009-01-28 23:36:17 +00002636 // Repeatedly perform subobject initializations in the range
2637 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002638
Douglas Gregor17bd0942009-01-28 23:36:17 +00002639 // Move to the next designator
2640 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2641 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002642
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002643 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00002644 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002645
Douglas Gregor17bd0942009-01-28 23:36:17 +00002646 while (DesignatedStartIndex <= DesignatedEndIndex) {
2647 // Recurse to check later designated subobjects.
2648 QualType ElementType = AT->getElementType();
2649 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002650
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002651 ElementEntity.setElementIndex(ElementIndex);
Alexey Bataev86a489e2016-01-25 05:14:03 +00002652 if (CheckDesignatedInitializer(
2653 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
2654 nullptr, Index, StructuredList, ElementIndex,
2655 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
2656 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002657 return true;
2658
2659 // Move to the next index in the array that we'll be initializing.
2660 ++DesignatedStartIndex;
2661 ElementIndex = DesignatedStartIndex.getZExtValue();
2662 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002663
2664 // If this the first designator, our caller will continue checking
2665 // the rest of this array subobject.
2666 if (IsFirstDesignator) {
2667 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002668 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002669 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002670 return false;
2671 }
Mike Stump11289f42009-09-09 15:08:12 +00002672
Douglas Gregor17bd0942009-01-28 23:36:17 +00002673 if (!FinishSubobjectInit)
2674 return false;
2675
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002676 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002677 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002678 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002679 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002680 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002681 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002682}
2683
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002684// Get the structured initializer list for a subobject of type
2685// @p CurrentObjectType.
2686InitListExpr *
2687InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2688 QualType CurrentObjectType,
2689 InitListExpr *StructuredList,
2690 unsigned StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +00002691 SourceRange InitRange,
2692 bool IsFullyOverwritten) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002693 if (VerifyOnly)
Craig Topperc3ec1492014-05-26 06:22:03 +00002694 return nullptr; // No structured list in verification-only mode.
2695 Expr *ExistingInit = nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002696 if (!StructuredList)
Benjamin Kramer6b441d62012-02-23 14:48:40 +00002697 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002698 else if (StructuredIndex < StructuredList->getNumInits())
2699 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002700
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002701 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
Yunzhong Gaocb779302015-06-10 00:27:52 +00002702 // There might have already been initializers for subobjects of the current
2703 // object, but a subsequent initializer list will overwrite the entirety
2704 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
2705 //
2706 // struct P { char x[6]; };
2707 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
2708 //
2709 // The first designated initializer is ignored, and l.x is just "f".
2710 if (!IsFullyOverwritten)
2711 return Result;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002712
2713 if (ExistingInit) {
2714 // We are creating an initializer list that initializes the
2715 // subobjects of the current object, but there was already an
2716 // initialization that completely initialized the current
2717 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002718 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002719 // struct X { int a, b; };
2720 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002721 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002722 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2723 // designated initializer re-initializes the whole
2724 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002725 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002726 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002727 << InitRange;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002728 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002729 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002730 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002731 << ExistingInit->getSourceRange();
2732 }
2733
Mike Stump11289f42009-09-09 15:08:12 +00002734 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002735 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko78852e92013-05-05 20:40:26 +00002736 InitRange.getBegin(), None,
Ted Kremenek013041e2010-02-19 01:50:18 +00002737 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002738
Eli Friedman91f5ae52012-02-23 02:25:10 +00002739 QualType ResultType = CurrentObjectType;
2740 if (!ResultType->isArrayType())
2741 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2742 Result->setType(ResultType);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002743
Douglas Gregor6d00c992009-03-20 23:58:33 +00002744 // Pre-allocate storage for the structured initializer list.
2745 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002746 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002747 bool GotNumInits = false;
2748 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002749 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002750 GotNumInits = true;
2751 } else if (Index < IList->getNumInits()) {
2752 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002753 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002754 GotNumInits = true;
2755 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002756 }
2757
Mike Stump11289f42009-09-09 15:08:12 +00002758 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002759 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2760 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2761 NumElements = CAType->getSize().getZExtValue();
2762 // Simple heuristic so that we don't allocate a very large
2763 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002764 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002765 NumElements = 0;
2766 }
John McCall9dd450b2009-09-21 23:43:11 +00002767 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002768 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002769 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002770 RecordDecl *RDecl = RType->getDecl();
2771 if (RDecl->isUnion())
2772 NumElements = 1;
2773 else
Aaron Ballman62e47c42014-03-10 13:43:55 +00002774 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002775 }
2776
Ted Kremenekac034612010-04-13 23:39:13 +00002777 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002778
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002779 // Link this new initializer list into the structured initializer
2780 // lists.
2781 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002782 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002783 else {
2784 Result->setSyntacticForm(IList);
2785 SyntacticToSemantic[IList] = Result;
2786 }
2787
2788 return Result;
2789}
2790
2791/// Update the initializer at index @p StructuredIndex within the
2792/// structured initializer list to the value @p expr.
2793void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2794 unsigned &StructuredIndex,
2795 Expr *expr) {
2796 // No structured initializer list to update
2797 if (!StructuredList)
2798 return;
2799
Ted Kremenekac034612010-04-13 23:39:13 +00002800 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2801 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002802 // This initializer overwrites a previous initializer. Warn.
Yunzhong Gaocb779302015-06-10 00:27:52 +00002803 // We need to check on source range validity because the previous
2804 // initializer does not have to be an explicit initializer.
2805 // struct P { int a, b; };
2806 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2807 // There is an overwrite taking place because the first braced initializer
2808 // list "{ .a = 2 }' already provides value for .p.b (which is zero).
2809 if (PrevInit->getSourceRange().isValid()) {
2810 SemaRef.Diag(expr->getLocStart(),
2811 diag::warn_initializer_overrides)
2812 << expr->getSourceRange();
2813
2814 SemaRef.Diag(PrevInit->getLocStart(),
2815 diag::note_previous_initializer)
2816 << /*FIXME:has side effects=*/0
2817 << PrevInit->getSourceRange();
2818 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002819 }
Mike Stump11289f42009-09-09 15:08:12 +00002820
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002821 ++StructuredIndex;
2822}
2823
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002824/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002825/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002826/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002827/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002828/// failure. Returns the index expression, possibly with an implicit cast
2829/// added, on success. If everything went okay, Value will receive the
2830/// value of the constant expression.
2831static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002832CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002833 SourceLocation Loc = Index->getLocStart();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002834
2835 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002836 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2837 if (Result.isInvalid())
2838 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002839
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002840 if (Value.isSigned() && Value.isNegative())
2841 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002842 << Value.toString(10) << Index->getSourceRange();
2843
Douglas Gregor51650d32009-01-23 21:04:18 +00002844 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002845 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002846}
2847
John McCalldadc5752010-08-24 06:29:42 +00002848ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002849 SourceLocation Loc,
2850 bool GNUSyntax,
2851 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002852 typedef DesignatedInitExpr::Designator ASTDesignator;
2853
2854 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002855 SmallVector<ASTDesignator, 32> Designators;
2856 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002857
2858 // Build designators and check array designator expressions.
2859 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2860 const Designator &D = Desig.getDesignator(Idx);
2861 switch (D.getKind()) {
2862 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002863 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002864 D.getFieldLoc()));
2865 break;
2866
2867 case Designator::ArrayDesignator: {
2868 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2869 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00002870 if (!Index->isTypeDependent() && !Index->isValueDependent())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002871 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002872 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002873 Invalid = true;
2874 else {
2875 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002876 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002877 D.getRBracketLoc()));
2878 InitExpressions.push_back(Index);
2879 }
2880 break;
2881 }
2882
2883 case Designator::ArrayRangeDesignator: {
2884 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2885 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2886 llvm::APSInt StartValue;
2887 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002888 bool StartDependent = StartIndex->isTypeDependent() ||
2889 StartIndex->isValueDependent();
2890 bool EndDependent = EndIndex->isTypeDependent() ||
2891 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00002892 if (!StartDependent)
2893 StartIndex =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002894 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002895 if (!EndDependent)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002896 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002897
2898 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002899 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002900 else {
2901 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002902 if (StartDependent || EndDependent) {
2903 // Nothing to compute.
2904 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002905 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002906 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002907 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002908
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002909 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002910 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002911 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002912 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2913 Invalid = true;
2914 } else {
2915 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002916 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002917 D.getEllipsisLoc(),
2918 D.getRBracketLoc()));
2919 InitExpressions.push_back(StartIndex);
2920 InitExpressions.push_back(EndIndex);
2921 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002922 }
2923 break;
2924 }
2925 }
2926 }
2927
2928 if (Invalid || Init.isInvalid())
2929 return ExprError();
2930
2931 // Clear out the expressions within the designation.
2932 Desig.ClearExprs(*this);
2933
2934 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002935 = DesignatedInitExpr::Create(Context,
David Majnemerf7e36092016-06-23 00:15:04 +00002936 Designators,
Benjamin Kramerc215e762012-08-24 11:54:20 +00002937 InitExpressions, Loc, GNUSyntax,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002938 Init.getAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002939
David Blaikiebbafb8a2012-03-11 07:00:24 +00002940 if (!getLangOpts().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002941 Diag(DIE->getLocStart(), diag::ext_designated_init)
2942 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002943
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002944 return DIE;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002945}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002946
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002947//===----------------------------------------------------------------------===//
2948// Initialization entity
2949//===----------------------------------------------------------------------===//
2950
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002951InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002952 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002953 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002954{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002955 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2956 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002957 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002958 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002959 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002960 Type = VT->getElementType();
2961 } else {
2962 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2963 assert(CT && "Unexpected type");
2964 Kind = EK_ComplexElement;
2965 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002966 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002967}
2968
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002969InitializedEntity
2970InitializedEntity::InitializeBase(ASTContext &Context,
2971 const CXXBaseSpecifier *Base,
Richard Smith872307e2016-03-08 22:17:41 +00002972 bool IsInheritedVirtualBase,
2973 const InitializedEntity *Parent) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002974 InitializedEntity Result;
2975 Result.Kind = EK_Base;
Richard Smith872307e2016-03-08 22:17:41 +00002976 Result.Parent = Parent;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002977 Result.Base = reinterpret_cast<uintptr_t>(Base);
2978 if (IsInheritedVirtualBase)
2979 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002980
Douglas Gregor1b303932009-12-22 15:35:07 +00002981 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002982 return Result;
2983}
2984
Douglas Gregor85dabae2009-12-16 01:38:02 +00002985DeclarationName InitializedEntity::getName() const {
2986 switch (getKind()) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002987 case EK_Parameter:
2988 case EK_Parameter_CF_Audited: {
John McCall31168b02011-06-15 23:02:42 +00002989 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2990 return (D ? D->getDeclName() : DeclarationName());
2991 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002992
2993 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002994 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00002995 case EK_Binding:
Richard Smith410306b2016-12-12 02:53:20 +00002996 return Variable.VariableOrMember->getDeclName();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002997
Douglas Gregor19666fb2012-02-15 16:57:26 +00002998 case EK_LambdaCapture:
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00002999 return DeclarationName(Capture.VarID);
Douglas Gregor19666fb2012-02-15 16:57:26 +00003000
Douglas Gregor85dabae2009-12-16 01:38:02 +00003001 case EK_Result:
3002 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003003 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00003004 case EK_Temporary:
3005 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003006 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003007 case EK_ArrayElement:
3008 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003009 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003010 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00003011 case EK_LambdaToBlockConversionBlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00003012 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003013 case EK_RelatedResult:
Douglas Gregor85dabae2009-12-16 01:38:02 +00003014 return DeclarationName();
3015 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003016
David Blaikie8a40f702012-01-17 06:56:22 +00003017 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00003018}
3019
Richard Smith7873de02016-08-11 22:25:46 +00003020ValueDecl *InitializedEntity::getDecl() const {
Douglas Gregora4b592a2009-12-19 03:01:41 +00003021 switch (getKind()) {
3022 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003023 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00003024 case EK_Binding:
Richard Smith410306b2016-12-12 02:53:20 +00003025 return Variable.VariableOrMember;
Douglas Gregora4b592a2009-12-19 03:01:41 +00003026
John McCall31168b02011-06-15 23:02:42 +00003027 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003028 case EK_Parameter_CF_Audited:
John McCall31168b02011-06-15 23:02:42 +00003029 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
3030
Douglas Gregora4b592a2009-12-19 03:01:41 +00003031 case EK_Result:
3032 case EK_Exception:
3033 case EK_New:
3034 case EK_Temporary:
3035 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003036 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003037 case EK_ArrayElement:
3038 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003039 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003040 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00003041 case EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00003042 case EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00003043 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003044 case EK_RelatedResult:
Craig Topperc3ec1492014-05-26 06:22:03 +00003045 return nullptr;
Douglas Gregora4b592a2009-12-19 03:01:41 +00003046 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003047
David Blaikie8a40f702012-01-17 06:56:22 +00003048 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00003049}
3050
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003051bool InitializedEntity::allowsNRVO() const {
3052 switch (getKind()) {
3053 case EK_Result:
3054 case EK_Exception:
3055 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003056
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003057 case EK_Variable:
3058 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003059 case EK_Parameter_CF_Audited:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003060 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00003061 case EK_Binding:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003062 case EK_New:
3063 case EK_Temporary:
Jordan Rose6c0505e2013-05-06 16:48:12 +00003064 case EK_CompoundLiteralInit:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003065 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003066 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003067 case EK_ArrayElement:
3068 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003069 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003070 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00003071 case EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00003072 case EK_LambdaCapture:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003073 case EK_RelatedResult:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003074 break;
3075 }
3076
3077 return false;
3078}
3079
Richard Smithe6c01442013-06-05 00:46:14 +00003080unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
Richard Smithe3b28bc2013-06-12 21:51:50 +00003081 assert(getParent() != this);
Richard Smithe6c01442013-06-05 00:46:14 +00003082 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3083 for (unsigned I = 0; I != Depth; ++I)
3084 OS << "`-";
3085
3086 switch (getKind()) {
3087 case EK_Variable: OS << "Variable"; break;
3088 case EK_Parameter: OS << "Parameter"; break;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003089 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3090 break;
Richard Smithe6c01442013-06-05 00:46:14 +00003091 case EK_Result: OS << "Result"; break;
3092 case EK_Exception: OS << "Exception"; break;
3093 case EK_Member: OS << "Member"; break;
Richard Smith7873de02016-08-11 22:25:46 +00003094 case EK_Binding: OS << "Binding"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00003095 case EK_New: OS << "New"; break;
3096 case EK_Temporary: OS << "Temporary"; break;
3097 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003098 case EK_RelatedResult: OS << "RelatedResult"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00003099 case EK_Base: OS << "Base"; break;
3100 case EK_Delegating: OS << "Delegating"; break;
3101 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3102 case EK_VectorElement: OS << "VectorElement " << Index; break;
3103 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3104 case EK_BlockElement: OS << "Block"; break;
Alex Lorenzb4791c72017-04-06 12:53:43 +00003105 case EK_LambdaToBlockConversionBlockElement:
3106 OS << "Block (lambda)";
3107 break;
Richard Smithe6c01442013-06-05 00:46:14 +00003108 case EK_LambdaCapture:
3109 OS << "LambdaCapture ";
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00003110 OS << DeclarationName(Capture.VarID);
Richard Smithe6c01442013-06-05 00:46:14 +00003111 break;
3112 }
3113
Richard Smith7873de02016-08-11 22:25:46 +00003114 if (auto *D = getDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00003115 OS << " ";
Richard Smith7873de02016-08-11 22:25:46 +00003116 D->printQualifiedName(OS);
Richard Smithe6c01442013-06-05 00:46:14 +00003117 }
3118
3119 OS << " '" << getType().getAsString() << "'\n";
3120
3121 return Depth + 1;
3122}
3123
Yaron Kerencdae9412016-01-29 19:38:18 +00003124LLVM_DUMP_METHOD void InitializedEntity::dump() const {
Richard Smithe6c01442013-06-05 00:46:14 +00003125 dumpImpl(llvm::errs());
3126}
3127
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003128//===----------------------------------------------------------------------===//
3129// Initialization sequence
3130//===----------------------------------------------------------------------===//
3131
3132void InitializationSequence::Step::Destroy() {
3133 switch (Kind) {
3134 case SK_ResolveAddressOfOverloadedFunction:
3135 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003136 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003137 case SK_CastDerivedToBaseLValue:
3138 case SK_BindReference:
3139 case SK_BindReferenceToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00003140 case SK_FinalCopy:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003141 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003142 case SK_UserConversion:
3143 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003144 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003145 case SK_QualificationConversionLValue:
Richard Smith77be48a2014-07-31 06:31:19 +00003146 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00003147 case SK_LValueToRValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00003148 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00003149 case SK_UnwrapInitList:
3150 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003151 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00003152 case SK_ConstructorInitializationFromList:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003153 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00003154 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003155 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003156 case SK_ObjCObjectConversion:
Richard Smith410306b2016-12-12 02:53:20 +00003157 case SK_ArrayLoopIndex:
3158 case SK_ArrayLoopInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003159 case SK_ArrayInit:
Richard Smith378b8c82016-12-14 03:22:16 +00003160 case SK_GNUArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00003161 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00003162 case SK_PassByIndirectCopyRestore:
3163 case SK_PassByIndirectRestore:
3164 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00003165 case SK_StdInitializerList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00003166 case SK_StdInitializerListConstructorCall:
Guy Benyei61054192013-02-07 10:55:47 +00003167 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003168 case SK_OCLZeroEvent:
Egor Churaev89831422016-12-23 14:55:49 +00003169 case SK_OCLZeroQueue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003170 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003171
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003172 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00003173 case SK_ConversionSequenceNoNarrowing:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003174 delete ICS;
3175 }
3176}
3177
Douglas Gregor838fcc32010-03-26 20:14:36 +00003178bool InitializationSequence::isDirectReferenceBinding() const {
Richard Smithb8c0f552016-12-09 18:49:13 +00003179 // There can be some lvalue adjustments after the SK_BindReference step.
3180 for (auto I = Steps.rbegin(); I != Steps.rend(); ++I) {
3181 if (I->Kind == SK_BindReference)
3182 return true;
3183 if (I->Kind == SK_BindReferenceToTemporary)
3184 return false;
3185 }
3186 return false;
Douglas Gregor838fcc32010-03-26 20:14:36 +00003187}
3188
3189bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00003190 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00003191 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003192
Douglas Gregor838fcc32010-03-26 20:14:36 +00003193 switch (getFailureKind()) {
3194 case FK_TooManyInitsForReference:
Richard Smith49a6b6e2017-03-24 01:14:25 +00003195 case FK_ParenthesizedListInitForReference:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003196 case FK_ArrayNeedsInitList:
3197 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00003198 case FK_ArrayNeedsInitListOrWideStringLiteral:
3199 case FK_NarrowStringIntoWideCharArray:
3200 case FK_WideStringIntoCharArray:
3201 case FK_IncompatWideStringIntoWideChar:
Richard Smith3a8244d2018-05-01 05:02:45 +00003202 case FK_PlainStringIntoUTF8Char:
3203 case FK_UTF8StringIntoPlainChar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003204 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3205 case FK_NonConstLValueReferenceBindingToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00003206 case FK_NonConstLValueReferenceBindingToBitfield:
3207 case FK_NonConstLValueReferenceBindingToVectorElement:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003208 case FK_NonConstLValueReferenceBindingToUnrelated:
3209 case FK_RValueReferenceBindingToLValue:
3210 case FK_ReferenceInitDropsQualifiers:
3211 case FK_ReferenceInitFailed:
3212 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00003213 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003214 case FK_TooManyInitsForScalar:
Richard Smith49a6b6e2017-03-24 01:14:25 +00003215 case FK_ParenthesizedListInitForScalar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003216 case FK_ReferenceBindingToInitList:
3217 case FK_InitListBadDestinationType:
3218 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003219 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003220 case FK_ArrayTypeMismatch:
3221 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00003222 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00003223 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00003224 case FK_PlaceholderType:
Sebastian Redl048a6d72012-04-01 19:54:59 +00003225 case FK_ExplicitConstructor:
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003226 case FK_AddressOfUnaddressableFunction:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003227 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003228
Douglas Gregor838fcc32010-03-26 20:14:36 +00003229 case FK_ReferenceInitOverloadFailed:
3230 case FK_UserConversionOverloadFailed:
3231 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003232 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003233 return FailedOverloadResult == OR_Ambiguous;
3234 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003235
David Blaikie8a40f702012-01-17 06:56:22 +00003236 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00003237}
3238
Douglas Gregorb33eed02010-04-16 22:09:46 +00003239bool InitializationSequence::isConstructorInitialization() const {
3240 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3241}
3242
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003243void
3244InitializationSequence
3245::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3246 DeclAccessPair Found,
3247 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003248 Step S;
3249 S.Kind = SK_ResolveAddressOfOverloadedFunction;
3250 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003251 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003252 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00003253 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003254 Steps.push_back(S);
3255}
3256
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003257void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00003258 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003259 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00003260 switch (VK) {
3261 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
3262 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3263 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003264 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003265 S.Type = BaseType;
3266 Steps.push_back(S);
3267}
3268
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003269void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003270 bool BindingTemporary) {
3271 Step S;
3272 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3273 S.Type = T;
3274 Steps.push_back(S);
3275}
3276
Richard Smithb8c0f552016-12-09 18:49:13 +00003277void InitializationSequence::AddFinalCopy(QualType T) {
3278 Step S;
3279 S.Kind = SK_FinalCopy;
3280 S.Type = T;
3281 Steps.push_back(S);
3282}
3283
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003284void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
3285 Step S;
3286 S.Kind = SK_ExtraneousCopyToTemporary;
3287 S.Type = T;
3288 Steps.push_back(S);
3289}
3290
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003291void
3292InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
3293 DeclAccessPair FoundDecl,
3294 QualType T,
3295 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003296 Step S;
3297 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003298 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003299 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003300 S.Function.Function = Function;
3301 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003302 Steps.push_back(S);
3303}
3304
3305void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00003306 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003307 Step S;
John McCall7a1da892010-08-26 16:36:35 +00003308 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00003309 switch (VK) {
3310 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003311 S.Kind = SK_QualificationConversionRValue;
3312 break;
John McCall2536c6d2010-08-25 10:28:54 +00003313 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003314 S.Kind = SK_QualificationConversionXValue;
3315 break;
John McCall2536c6d2010-08-25 10:28:54 +00003316 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003317 S.Kind = SK_QualificationConversionLValue;
3318 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003319 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003320 S.Type = Ty;
3321 Steps.push_back(S);
3322}
3323
Richard Smith77be48a2014-07-31 06:31:19 +00003324void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
3325 Step S;
3326 S.Kind = SK_AtomicConversion;
3327 S.Type = Ty;
3328 Steps.push_back(S);
3329}
3330
Jordan Roseb1312a52013-04-11 00:58:58 +00003331void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
3332 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
3333
3334 Step S;
3335 S.Kind = SK_LValueToRValue;
3336 S.Type = Ty;
3337 Steps.push_back(S);
3338}
3339
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003340void InitializationSequence::AddConversionSequenceStep(
Richard Smithaaa0ec42013-09-21 21:19:19 +00003341 const ImplicitConversionSequence &ICS, QualType T,
3342 bool TopLevelOfInitList) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003343 Step S;
Richard Smithaaa0ec42013-09-21 21:19:19 +00003344 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3345 : SK_ConversionSequence;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003346 S.Type = T;
3347 S.ICS = new ImplicitConversionSequence(ICS);
3348 Steps.push_back(S);
3349}
3350
Douglas Gregor51e77d52009-12-10 17:56:55 +00003351void InitializationSequence::AddListInitializationStep(QualType T) {
3352 Step S;
3353 S.Kind = SK_ListInitialization;
3354 S.Type = T;
3355 Steps.push_back(S);
3356}
3357
Richard Smith55c28882016-05-12 23:45:49 +00003358void InitializationSequence::AddConstructorInitializationStep(
3359 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3360 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003361 Step S;
Richard Smithf8adcdc2014-07-17 05:12:35 +00003362 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
Richard Smith53324112014-07-16 21:33:43 +00003363 : SK_ConstructorInitializationFromList
3364 : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003365 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003366 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003367 S.Function.Function = Constructor;
Richard Smith55c28882016-05-12 23:45:49 +00003368 S.Function.FoundDecl = FoundDecl;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003369 Steps.push_back(S);
3370}
3371
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003372void InitializationSequence::AddZeroInitializationStep(QualType T) {
3373 Step S;
3374 S.Kind = SK_ZeroInitialization;
3375 S.Type = T;
3376 Steps.push_back(S);
3377}
3378
Douglas Gregore1314a62009-12-18 05:02:21 +00003379void InitializationSequence::AddCAssignmentStep(QualType T) {
3380 Step S;
3381 S.Kind = SK_CAssignment;
3382 S.Type = T;
3383 Steps.push_back(S);
3384}
3385
Eli Friedman78275202009-12-19 08:11:05 +00003386void InitializationSequence::AddStringInitStep(QualType T) {
3387 Step S;
3388 S.Kind = SK_StringInit;
3389 S.Type = T;
3390 Steps.push_back(S);
3391}
3392
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003393void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3394 Step S;
3395 S.Kind = SK_ObjCObjectConversion;
3396 S.Type = T;
3397 Steps.push_back(S);
3398}
3399
Richard Smith378b8c82016-12-14 03:22:16 +00003400void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00003401 Step S;
Richard Smith378b8c82016-12-14 03:22:16 +00003402 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
Douglas Gregore2f943b2011-02-22 18:29:51 +00003403 S.Type = T;
3404 Steps.push_back(S);
3405}
3406
Richard Smith410306b2016-12-12 02:53:20 +00003407void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
3408 Step S;
3409 S.Kind = SK_ArrayLoopIndex;
3410 S.Type = EltT;
3411 Steps.insert(Steps.begin(), S);
3412
3413 S.Kind = SK_ArrayLoopInit;
3414 S.Type = T;
3415 Steps.push_back(S);
3416}
3417
Richard Smithebeed412012-02-15 22:38:09 +00003418void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3419 Step S;
3420 S.Kind = SK_ParenthesizedArrayInit;
3421 S.Type = T;
3422 Steps.push_back(S);
3423}
3424
John McCall31168b02011-06-15 23:02:42 +00003425void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3426 bool shouldCopy) {
3427 Step s;
3428 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3429 : SK_PassByIndirectRestore);
3430 s.Type = type;
3431 Steps.push_back(s);
3432}
3433
3434void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3435 Step S;
3436 S.Kind = SK_ProduceObjCObject;
3437 S.Type = T;
3438 Steps.push_back(S);
3439}
3440
Sebastian Redlc1839b12012-01-17 22:49:42 +00003441void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3442 Step S;
3443 S.Kind = SK_StdInitializerList;
3444 S.Type = T;
3445 Steps.push_back(S);
3446}
3447
Guy Benyei61054192013-02-07 10:55:47 +00003448void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3449 Step S;
3450 S.Kind = SK_OCLSamplerInit;
3451 S.Type = T;
3452 Steps.push_back(S);
3453}
3454
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003455void InitializationSequence::AddOCLZeroEventStep(QualType T) {
3456 Step S;
3457 S.Kind = SK_OCLZeroEvent;
3458 S.Type = T;
3459 Steps.push_back(S);
3460}
3461
Egor Churaev89831422016-12-23 14:55:49 +00003462void InitializationSequence::AddOCLZeroQueueStep(QualType T) {
3463 Step S;
3464 S.Kind = SK_OCLZeroQueue;
3465 S.Type = T;
3466 Steps.push_back(S);
3467}
3468
Sebastian Redl29526f02011-11-27 16:50:07 +00003469void InitializationSequence::RewrapReferenceInitList(QualType T,
3470 InitListExpr *Syntactic) {
3471 assert(Syntactic->getNumInits() == 1 &&
3472 "Can only rewrap trivial init lists.");
3473 Step S;
3474 S.Kind = SK_UnwrapInitList;
3475 S.Type = Syntactic->getInit(0)->getType();
3476 Steps.insert(Steps.begin(), S);
3477
3478 S.Kind = SK_RewrapInitList;
3479 S.Type = T;
3480 S.WrappingSyntacticList = Syntactic;
3481 Steps.push_back(S);
3482}
3483
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003484void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003485 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00003486 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003487 this->Failure = Failure;
3488 this->FailedOverloadResult = Result;
3489}
3490
3491//===----------------------------------------------------------------------===//
3492// Attempt initialization
3493//===----------------------------------------------------------------------===//
3494
Nico Weber337d5aa2015-04-17 08:32:38 +00003495/// Tries to add a zero initializer. Returns true if that worked.
3496static bool
3497maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
3498 const InitializedEntity &Entity) {
3499 if (Entity.getKind() != InitializedEntity::EK_Variable)
3500 return false;
3501
3502 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
3503 if (VD->getInit() || VD->getLocEnd().isMacroID())
3504 return false;
3505
3506 QualType VariableTy = VD->getType().getCanonicalType();
3507 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
3508 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3509 if (!Init.empty()) {
3510 Sequence.AddZeroInitializationStep(Entity.getType());
3511 Sequence.SetZeroInitializationFixit(Init, Loc);
3512 return true;
3513 }
3514 return false;
3515}
3516
John McCall31168b02011-06-15 23:02:42 +00003517static void MaybeProduceObjCObject(Sema &S,
3518 InitializationSequence &Sequence,
3519 const InitializedEntity &Entity) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003520 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCall31168b02011-06-15 23:02:42 +00003521
3522 /// When initializing a parameter, produce the value if it's marked
3523 /// __attribute__((ns_consumed)).
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003524 if (Entity.isParameterKind()) {
John McCall31168b02011-06-15 23:02:42 +00003525 if (!Entity.isParameterConsumed())
3526 return;
3527
3528 assert(Entity.getType()->isObjCRetainableType() &&
3529 "consuming an object of unretainable type?");
3530 Sequence.AddProduceObjCObjectStep(Entity.getType());
3531
3532 /// When initializing a return value, if the return type is a
3533 /// retainable type, then returns need to immediately retain the
3534 /// object. If an autorelease is required, it will be done at the
3535 /// last instant.
3536 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
3537 if (!Entity.getType()->isObjCRetainableType())
3538 return;
3539
3540 Sequence.AddProduceObjCObjectStep(Entity.getType());
3541 }
3542}
3543
Richard Smithcc1b96d2013-06-12 22:31:48 +00003544static void TryListInitialization(Sema &S,
3545 const InitializedEntity &Entity,
3546 const InitializationKind &Kind,
3547 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00003548 InitializationSequence &Sequence,
3549 bool TreatUnavailableAsInvalid);
Richard Smithcc1b96d2013-06-12 22:31:48 +00003550
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003551/// When initializing from init list via constructor, handle
Richard Smithd86812d2012-07-05 08:39:21 +00003552/// initialization of an object of type std::initializer_list<T>.
Sebastian Redled2e5322011-12-22 14:44:04 +00003553///
Richard Smithd86812d2012-07-05 08:39:21 +00003554/// \return true if we have handled initialization of an object of type
3555/// std::initializer_list<T>, false otherwise.
3556static bool TryInitializerListConstruction(Sema &S,
3557 InitListExpr *List,
3558 QualType DestType,
Manman Ren073db022016-03-10 18:53:19 +00003559 InitializationSequence &Sequence,
3560 bool TreatUnavailableAsInvalid) {
Richard Smithd86812d2012-07-05 08:39:21 +00003561 QualType E;
3562 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1bfe0682012-02-14 21:14:13 +00003563 return false;
3564
Richard Smithdb0ac552015-12-18 22:40:25 +00003565 if (!S.isCompleteType(List->getExprLoc(), E)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00003566 Sequence.setIncompleteTypeFailure(E);
3567 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003568 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00003569
3570 // Try initializing a temporary array from the init list.
3571 QualType ArrayType = S.Context.getConstantArrayType(
3572 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3573 List->getNumInits()),
3574 clang::ArrayType::Normal, 0);
3575 InitializedEntity HiddenArray =
3576 InitializedEntity::InitializeTemporary(ArrayType);
Vedant Kumara14a1f92018-01-17 18:53:51 +00003577 InitializationKind Kind = InitializationKind::CreateDirectList(
3578 List->getExprLoc(), List->getLocStart(), List->getLocEnd());
Manman Ren073db022016-03-10 18:53:19 +00003579 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
3580 TreatUnavailableAsInvalid);
Richard Smithcc1b96d2013-06-12 22:31:48 +00003581 if (Sequence)
3582 Sequence.AddStdInitializerListConstructionStep(DestType);
Richard Smithd86812d2012-07-05 08:39:21 +00003583 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003584}
3585
Richard Smith7c2bcc92016-09-07 02:14:33 +00003586/// Determine if the constructor has the signature of a copy or move
3587/// constructor for the type T of the class in which it was found. That is,
3588/// determine if its first parameter is of type T or reference to (possibly
3589/// cv-qualified) T.
3590static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
3591 const ConstructorInfo &Info) {
3592 if (Info.Constructor->getNumParams() == 0)
3593 return false;
3594
3595 QualType ParmT =
3596 Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
3597 QualType ClassT =
3598 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
3599
3600 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
3601}
3602
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003603static OverloadingResult
3604ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003605 MultiExprArg Args,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003606 OverloadCandidateSet &CandidateSet,
Richard Smith67ef14f2017-09-26 18:37:55 +00003607 QualType DestType,
Richard Smith40c78062015-02-21 02:31:57 +00003608 DeclContext::lookup_result Ctors,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003609 OverloadCandidateSet::iterator &Best,
3610 bool CopyInitializing, bool AllowExplicit,
Richard Smith7c2bcc92016-09-07 02:14:33 +00003611 bool OnlyListConstructors, bool IsListInit,
3612 bool SecondStepOfCopyInit = false) {
Richard Smith67ef14f2017-09-26 18:37:55 +00003613 CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003614
Richard Smith40c78062015-02-21 02:31:57 +00003615 for (NamedDecl *D : Ctors) {
Richard Smithc2bebe92016-05-11 20:37:46 +00003616 auto Info = getConstructorInfo(D);
Richard Smith7c2bcc92016-09-07 02:14:33 +00003617 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
Richard Smithc2bebe92016-05-11 20:37:46 +00003618 continue;
3619
Richard Smith7c2bcc92016-09-07 02:14:33 +00003620 if (!AllowExplicit && Info.Constructor->isExplicit())
3621 continue;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003622
Richard Smith7c2bcc92016-09-07 02:14:33 +00003623 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
3624 continue;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003625
Richard Smith7c2bcc92016-09-07 02:14:33 +00003626 // C++11 [over.best.ics]p4:
3627 // ... and the constructor or user-defined conversion function is a
3628 // candidate by
3629 // - 13.3.1.3, when the argument is the temporary in the second step
3630 // of a class copy-initialization, or
3631 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
3632 // - the second phase of 13.3.1.7 when the initializer list has exactly
3633 // one element that is itself an initializer list, and the target is
3634 // the first parameter of a constructor of class X, and the conversion
3635 // is to X or reference to (possibly cv-qualified X),
3636 // user-defined conversion sequences are not considered.
3637 bool SuppressUserConversions =
3638 SecondStepOfCopyInit ||
3639 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
3640 hasCopyOrMoveCtorParam(S.Context, Info));
3641
3642 if (Info.ConstructorTmpl)
3643 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3644 /*ExplicitArgs*/ nullptr, Args,
3645 CandidateSet, SuppressUserConversions);
3646 else {
3647 // C++ [over.match.copy]p1:
3648 // - When initializing a temporary to be bound to the first parameter
3649 // of a constructor [for type T] that takes a reference to possibly
3650 // cv-qualified T as its first argument, called with a single
3651 // argument in the context of direct-initialization, explicit
3652 // conversion functions are also considered.
3653 // FIXME: What if a constructor template instantiates to such a signature?
3654 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
3655 Args.size() == 1 &&
3656 hasCopyOrMoveCtorParam(S.Context, Info);
3657 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
3658 CandidateSet, SuppressUserConversions,
3659 /*PartialOverloading=*/false,
3660 /*AllowExplicit=*/AllowExplicitConv);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003661 }
3662 }
3663
Richard Smith67ef14f2017-09-26 18:37:55 +00003664 // FIXME: Work around a bug in C++17 guaranteed copy elision.
3665 //
3666 // When initializing an object of class type T by constructor
3667 // ([over.match.ctor]) or by list-initialization ([over.match.list])
3668 // from a single expression of class type U, conversion functions of
3669 // U that convert to the non-reference type cv T are candidates.
3670 // Explicit conversion functions are only candidates during
3671 // direct-initialization.
3672 //
3673 // Note: SecondStepOfCopyInit is only ever true in this case when
3674 // evaluating whether to produce a C++98 compatibility warning.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003675 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
Richard Smith67ef14f2017-09-26 18:37:55 +00003676 !SecondStepOfCopyInit) {
3677 Expr *Initializer = Args[0];
3678 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
3679 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
3680 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
3681 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3682 NamedDecl *D = *I;
3683 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3684 D = D->getUnderlyingDecl();
3685
3686 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3687 CXXConversionDecl *Conv;
3688 if (ConvTemplate)
3689 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3690 else
3691 Conv = cast<CXXConversionDecl>(D);
3692
3693 if ((AllowExplicit && !CopyInitializing) || !Conv->isExplicit()) {
3694 if (ConvTemplate)
3695 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3696 ActingDC, Initializer, DestType,
3697 CandidateSet, AllowExplicit,
3698 /*AllowResultConversion*/false);
3699 else
3700 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
3701 DestType, CandidateSet, AllowExplicit,
3702 /*AllowResultConversion*/false);
3703 }
3704 }
3705 }
3706 }
3707
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003708 // Perform overload resolution and return the result.
3709 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3710}
3711
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003712/// Attempt initialization by constructor (C++ [dcl.init]), which
Sebastian Redled2e5322011-12-22 14:44:04 +00003713/// enumerates the constructors of the initialized entity and performs overload
3714/// resolution to select the best.
Richard Smith410306b2016-12-12 02:53:20 +00003715/// \param DestType The destination class type.
3716/// \param DestArrayType The destination type, which is either DestType or
3717/// a (possibly multidimensional) array of DestType.
NAKAMURA Takumiffcc98a2015-02-05 23:12:13 +00003718/// \param IsListInit Is this list-initialization?
Richard Smithed83ebd2015-02-05 07:02:11 +00003719/// \param IsInitListCopy Is this non-list-initialization resulting from a
3720/// list-initialization from {x} where x is the same
3721/// type as the entity?
Sebastian Redled2e5322011-12-22 14:44:04 +00003722static void TryConstructorInitialization(Sema &S,
3723 const InitializedEntity &Entity,
3724 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003725 MultiExprArg Args, QualType DestType,
Richard Smith410306b2016-12-12 02:53:20 +00003726 QualType DestArrayType,
Sebastian Redled2e5322011-12-22 14:44:04 +00003727 InitializationSequence &Sequence,
Richard Smithed83ebd2015-02-05 07:02:11 +00003728 bool IsListInit = false,
3729 bool IsInitListCopy = false) {
Richard Smith122f88d2016-12-06 23:52:28 +00003730 assert(((!IsListInit && !IsInitListCopy) ||
3731 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3732 "IsListInit/IsInitListCopy must come with a single initializer list "
3733 "argument.");
3734 InitListExpr *ILE =
3735 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
3736 MultiExprArg UnwrappedArgs =
3737 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003738
Sebastian Redled2e5322011-12-22 14:44:04 +00003739 // The type we're constructing needs to be complete.
Richard Smithdb0ac552015-12-18 22:40:25 +00003740 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003741 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003742 return;
Sebastian Redled2e5322011-12-22 14:44:04 +00003743 }
3744
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003745 // C++17 [dcl.init]p17:
Richard Smith122f88d2016-12-06 23:52:28 +00003746 // - If the initializer expression is a prvalue and the cv-unqualified
3747 // version of the source type is the same class as the class of the
3748 // destination, the initializer expression is used to initialize the
3749 // destination object.
3750 // Per DR (no number yet), this does not apply when initializing a base
3751 // class or delegating to another constructor from a mem-initializer.
Alex Lorenzb4791c72017-04-06 12:53:43 +00003752 // ObjC++: Lambda captured by the block in the lambda to block conversion
3753 // should avoid copy elision.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003754 if (S.getLangOpts().CPlusPlus17 &&
Richard Smith122f88d2016-12-06 23:52:28 +00003755 Entity.getKind() != InitializedEntity::EK_Base &&
3756 Entity.getKind() != InitializedEntity::EK_Delegating &&
Alex Lorenzb4791c72017-04-06 12:53:43 +00003757 Entity.getKind() !=
3758 InitializedEntity::EK_LambdaToBlockConversionBlockElement &&
Richard Smith122f88d2016-12-06 23:52:28 +00003759 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isRValue() &&
3760 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
3761 // Convert qualifications if necessary.
Richard Smith16d31502016-12-21 01:31:56 +00003762 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Richard Smith122f88d2016-12-06 23:52:28 +00003763 if (ILE)
3764 Sequence.RewrapReferenceInitList(DestType, ILE);
3765 return;
3766 }
3767
Sebastian Redled2e5322011-12-22 14:44:04 +00003768 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3769 assert(DestRecordType && "Constructor initialization requires record type");
3770 CXXRecordDecl *DestRecordDecl
3771 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3772
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003773 // Build the candidate set directly in the initialization sequence
3774 // structure, so that it will persist if we fail.
3775 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3776
3777 // Determine whether we are allowed to call explicit constructors or
3778 // explicit conversion operators.
Richard Smithed83ebd2015-02-05 07:02:11 +00003779 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003780 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003781
Sebastian Redled2e5322011-12-22 14:44:04 +00003782 // - Otherwise, if T is a class type, constructors are considered. The
3783 // applicable constructors are enumerated, and the best one is chosen
3784 // through overload resolution.
Richard Smith40c78062015-02-21 02:31:57 +00003785 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
Sebastian Redled2e5322011-12-22 14:44:04 +00003786
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003787 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redled2e5322011-12-22 14:44:04 +00003788 OverloadCandidateSet::iterator Best;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003789 bool AsInitializerList = false;
3790
Larisse Voufo19d08672015-01-27 18:47:05 +00003791 // C++11 [over.match.list]p1, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00003792 // When objects of non-aggregate type T are list-initialized, such that
3793 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
3794 // according to the rules in this section, overload resolution selects
3795 // the constructor in two phases:
3796 //
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003797 // - Initially, the candidate functions are the initializer-list
3798 // constructors of the class T and the argument list consists of the
3799 // initializer list as a single argument.
Richard Smithed83ebd2015-02-05 07:02:11 +00003800 if (IsListInit) {
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003801 AsInitializerList = true;
Richard Smithd86812d2012-07-05 08:39:21 +00003802
3803 // If the initializer list has no elements and T has a default constructor,
3804 // the first phase is omitted.
Richard Smith122f88d2016-12-06 23:52:28 +00003805 if (!(UnwrappedArgs.empty() && DestRecordDecl->hasDefaultConstructor()))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003806 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Richard Smith67ef14f2017-09-26 18:37:55 +00003807 CandidateSet, DestType, Ctors, Best,
Richard Smithd86812d2012-07-05 08:39:21 +00003808 CopyInitialization, AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003809 /*OnlyListConstructor=*/true,
3810 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003811 }
3812
3813 // C++11 [over.match.list]p1:
3814 // - If no viable initializer-list constructor is found, overload resolution
3815 // is performed again, where the candidate functions are all the
Richard Smithd86812d2012-07-05 08:39:21 +00003816 // constructors of the class T and the argument list consists of the
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003817 // elements of the initializer list.
3818 if (Result == OR_No_Viable_Function) {
3819 AsInitializerList = false;
Richard Smith122f88d2016-12-06 23:52:28 +00003820 Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs,
Richard Smith67ef14f2017-09-26 18:37:55 +00003821 CandidateSet, DestType, Ctors, Best,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003822 CopyInitialization, AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003823 /*OnlyListConstructors=*/false,
3824 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003825 }
3826 if (Result) {
Richard Smithed83ebd2015-02-05 07:02:11 +00003827 Sequence.SetOverloadFailure(IsListInit ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003828 InitializationSequence::FK_ListConstructorOverloadFailed :
3829 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00003830 Result);
3831 return;
3832 }
3833
Richard Smith67ef14f2017-09-26 18:37:55 +00003834 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3835
3836 // In C++17, ResolveConstructorOverload can select a conversion function
3837 // instead of a constructor.
3838 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
3839 // Add the user-defined conversion step that calls the conversion function.
3840 QualType ConvType = CD->getConversionType();
3841 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
3842 "should not have selected this conversion function");
3843 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
3844 HadMultipleCandidates);
3845 if (!S.Context.hasSameType(ConvType, DestType))
3846 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
3847 if (IsListInit)
3848 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
3849 return;
3850 }
3851
Richard Smithd86812d2012-07-05 08:39:21 +00003852 // C++11 [dcl.init]p6:
Sebastian Redled2e5322011-12-22 14:44:04 +00003853 // If a program calls for the default initialization of an object
3854 // of a const-qualified type T, T shall be a class type with a
3855 // user-provided default constructor.
Nico Weber6a6376b2016-02-19 01:52:46 +00003856 // C++ core issue 253 proposal:
3857 // If the implicit default constructor initializes all subobjects, no
3858 // initializer should be required.
3859 // The 253 proposal is for example needed to process libstdc++ headers in 5.x.
3860 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redled2e5322011-12-22 14:44:04 +00003861 if (Kind.getKind() == InitializationKind::IK_Default &&
Nico Weber6a6376b2016-02-19 01:52:46 +00003862 Entity.getType().isConstQualified()) {
3863 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
3864 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
3865 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3866 return;
3867 }
Sebastian Redled2e5322011-12-22 14:44:04 +00003868 }
3869
Sebastian Redl048a6d72012-04-01 19:54:59 +00003870 // C++11 [over.match.list]p1:
3871 // In copy-list-initialization, if an explicit constructor is chosen, the
3872 // initializer is ill-formed.
Richard Smithed83ebd2015-02-05 07:02:11 +00003873 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
Sebastian Redl048a6d72012-04-01 19:54:59 +00003874 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3875 return;
3876 }
3877
Sebastian Redled2e5322011-12-22 14:44:04 +00003878 // Add the constructor initialization step. Any cv-qualification conversion is
3879 // subsumed by the initialization.
Richard Smithed83ebd2015-02-05 07:02:11 +00003880 Sequence.AddConstructorInitializationStep(
Richard Smith410306b2016-12-12 02:53:20 +00003881 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
Richard Smithed83ebd2015-02-05 07:02:11 +00003882 IsListInit | IsInitListCopy, AsInitializerList);
Sebastian Redled2e5322011-12-22 14:44:04 +00003883}
3884
Sebastian Redl29526f02011-11-27 16:50:07 +00003885static bool
3886ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3887 Expr *Initializer,
3888 QualType &SourceType,
3889 QualType &UnqualifiedSourceType,
3890 QualType UnqualifiedTargetType,
3891 InitializationSequence &Sequence) {
3892 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3893 S.Context.OverloadTy) {
3894 DeclAccessPair Found;
3895 bool HadMultipleCandidates = false;
3896 if (FunctionDecl *Fn
3897 = S.ResolveAddressOfOverloadedFunction(Initializer,
3898 UnqualifiedTargetType,
3899 false, Found,
3900 &HadMultipleCandidates)) {
3901 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3902 HadMultipleCandidates);
3903 SourceType = Fn->getType();
3904 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3905 } else if (!UnqualifiedTargetType->isRecordType()) {
3906 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3907 return true;
3908 }
3909 }
3910 return false;
3911}
3912
3913static void TryReferenceInitializationCore(Sema &S,
3914 const InitializedEntity &Entity,
3915 const InitializationKind &Kind,
3916 Expr *Initializer,
3917 QualType cv1T1, QualType T1,
3918 Qualifiers T1Quals,
3919 QualType cv2T2, QualType T2,
3920 Qualifiers T2Quals,
3921 InitializationSequence &Sequence);
3922
Richard Smithd86812d2012-07-05 08:39:21 +00003923static void TryValueInitialization(Sema &S,
3924 const InitializedEntity &Entity,
3925 const InitializationKind &Kind,
3926 InitializationSequence &Sequence,
Craig Topperc3ec1492014-05-26 06:22:03 +00003927 InitListExpr *InitList = nullptr);
Richard Smithd86812d2012-07-05 08:39:21 +00003928
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003929/// Attempt list initialization of a reference.
Sebastian Redl29526f02011-11-27 16:50:07 +00003930static void TryReferenceListInitialization(Sema &S,
3931 const InitializedEntity &Entity,
3932 const InitializationKind &Kind,
3933 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00003934 InitializationSequence &Sequence,
3935 bool TreatUnavailableAsInvalid) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003936 // First, catch C++03 where this isn't possible.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003937 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003938 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3939 return;
3940 }
David Majnemer9370dc22015-04-26 07:35:03 +00003941 // Can't reference initialize a compound literal.
3942 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
3943 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3944 return;
3945 }
Sebastian Redl29526f02011-11-27 16:50:07 +00003946
3947 QualType DestType = Entity.getType();
3948 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3949 Qualifiers T1Quals;
3950 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3951
3952 // Reference initialization via an initializer list works thus:
3953 // If the initializer list consists of a single element that is
3954 // reference-related to the referenced type, bind directly to that element
3955 // (possibly creating temporaries).
3956 // Otherwise, initialize a temporary with the initializer list and
3957 // bind to that.
3958 if (InitList->getNumInits() == 1) {
3959 Expr *Initializer = InitList->getInit(0);
3960 QualType cv2T2 = Initializer->getType();
3961 Qualifiers T2Quals;
3962 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3963
3964 // If this fails, creating a temporary wouldn't work either.
3965 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3966 T1, Sequence))
3967 return;
3968
3969 SourceLocation DeclLoc = Initializer->getLocStart();
3970 bool dummy1, dummy2, dummy3;
3971 Sema::ReferenceCompareResult RefRelationship
3972 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3973 dummy2, dummy3);
3974 if (RefRelationship >= Sema::Ref_Related) {
3975 // Try to bind the reference here.
3976 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3977 T1Quals, cv2T2, T2, T2Quals, Sequence);
3978 if (Sequence)
3979 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3980 return;
3981 }
Richard Smith03d93932013-01-15 07:58:29 +00003982
3983 // Update the initializer if we've resolved an overloaded function.
3984 if (Sequence.step_begin() != Sequence.step_end())
3985 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl29526f02011-11-27 16:50:07 +00003986 }
3987
3988 // Not reference-related. Create a temporary and bind to that.
3989 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3990
Manman Ren073db022016-03-10 18:53:19 +00003991 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
3992 TreatUnavailableAsInvalid);
Sebastian Redl29526f02011-11-27 16:50:07 +00003993 if (Sequence) {
3994 if (DestType->isRValueReferenceType() ||
3995 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3996 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3997 else
3998 Sequence.SetFailed(
3999 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4000 }
4001}
4002
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004003/// Attempt list initialization (C++0x [dcl.init.list])
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004004static void TryListInitialization(Sema &S,
4005 const InitializedEntity &Entity,
4006 const InitializationKind &Kind,
4007 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00004008 InitializationSequence &Sequence,
4009 bool TreatUnavailableAsInvalid) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004010 QualType DestType = Entity.getType();
4011
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004012 // C++ doesn't allow scalar initialization with more than one argument.
4013 // But C99 complex numbers are scalars and it makes sense there.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004014 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004015 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4016 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
4017 return;
4018 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004019 if (DestType->isReferenceType()) {
Manman Ren073db022016-03-10 18:53:19 +00004020 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4021 TreatUnavailableAsInvalid);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004022 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004023 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00004024
Larisse Voufod2010992015-01-24 23:09:54 +00004025 if (DestType->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004026 !S.isCompleteType(InitList->getLocStart(), DestType)) {
Larisse Voufod2010992015-01-24 23:09:54 +00004027 Sequence.setIncompleteTypeFailure(DestType);
4028 return;
4029 }
Richard Smithd86812d2012-07-05 08:39:21 +00004030
Larisse Voufo19d08672015-01-27 18:47:05 +00004031 // C++11 [dcl.init.list]p3, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00004032 // - If T is a class type and the initializer list has a single element of
4033 // type cv U, where U is T or a class derived from T, the object is
4034 // initialized from that element (by copy-initialization for
4035 // copy-list-initialization, or by direct-initialization for
4036 // direct-list-initialization).
4037 // - Otherwise, if T is a character array and the initializer list has a
4038 // single element that is an appropriately-typed string literal
4039 // (8.5.2 [dcl.init.string]), initialization is performed as described
4040 // in that section.
Larisse Voufo19d08672015-01-27 18:47:05 +00004041 // - Otherwise, if T is an aggregate, [...] (continue below).
4042 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
Larisse Voufod2010992015-01-24 23:09:54 +00004043 if (DestType->isRecordType()) {
4044 QualType InitType = InitList->getInit(0)->getType();
4045 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004046 S.IsDerivedFrom(InitList->getLocStart(), InitType, DestType)) {
Richard Smith122f88d2016-12-06 23:52:28 +00004047 Expr *InitListAsExpr = InitList;
4048 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smith410306b2016-12-12 02:53:20 +00004049 DestType, Sequence,
4050 /*InitListSyntax*/false,
4051 /*IsInitListCopy*/true);
Larisse Voufod2010992015-01-24 23:09:54 +00004052 return;
4053 }
4054 }
4055 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4056 Expr *SubInit[1] = {InitList->getInit(0)};
4057 if (!isa<VariableArrayType>(DestAT) &&
4058 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4059 InitializationKind SubKind =
4060 Kind.getKind() == InitializationKind::IK_DirectList
4061 ? InitializationKind::CreateDirect(Kind.getLocation(),
4062 InitList->getLBraceLoc(),
4063 InitList->getRBraceLoc())
4064 : Kind;
4065 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
Manman Ren073db022016-03-10 18:53:19 +00004066 /*TopLevelOfInitList*/ true,
4067 TreatUnavailableAsInvalid);
Larisse Voufod2010992015-01-24 23:09:54 +00004068
4069 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4070 // the element is not an appropriately-typed string literal, in which
4071 // case we should proceed as in C++11 (below).
4072 if (Sequence) {
4073 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4074 return;
4075 }
4076 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00004077 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004078 }
Larisse Voufod2010992015-01-24 23:09:54 +00004079
4080 // C++11 [dcl.init.list]p3:
4081 // - If T is an aggregate, aggregate initialization is performed.
Faisal Vali30622bb2015-12-07 02:37:44 +00004082 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4083 (S.getLangOpts().CPlusPlus11 &&
4084 S.isStdInitializerList(DestType, nullptr))) {
Larisse Voufod2010992015-01-24 23:09:54 +00004085 if (S.getLangOpts().CPlusPlus11) {
4086 // - Otherwise, if the initializer list has no elements and T is a
4087 // class type with a default constructor, the object is
4088 // value-initialized.
4089 if (InitList->getNumInits() == 0) {
4090 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4091 if (RD->hasDefaultConstructor()) {
4092 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4093 return;
4094 }
4095 }
4096
4097 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4098 // an initializer_list object constructed [...]
Manman Ren073db022016-03-10 18:53:19 +00004099 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4100 TreatUnavailableAsInvalid))
Larisse Voufod2010992015-01-24 23:09:54 +00004101 return;
4102
4103 // - Otherwise, if T is a class type, constructors are considered.
4104 Expr *InitListAsExpr = InitList;
4105 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smith410306b2016-12-12 02:53:20 +00004106 DestType, Sequence, /*InitListSyntax*/true);
Larisse Voufod2010992015-01-24 23:09:54 +00004107 } else
4108 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
4109 return;
4110 }
4111
Richard Smith089c3162013-09-21 21:55:46 +00004112 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
Richard Smithed638862016-03-28 06:08:37 +00004113 InitList->getNumInits() == 1) {
4114 Expr *E = InitList->getInit(0);
4115
4116 // - Otherwise, if T is an enumeration with a fixed underlying type,
4117 // the initializer-list has a single element v, and the initialization
4118 // is direct-list-initialization, the object is initialized with the
4119 // value T(v); if a narrowing conversion is required to convert v to
4120 // the underlying type of T, the program is ill-formed.
4121 auto *ET = DestType->getAs<EnumType>();
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004122 if (S.getLangOpts().CPlusPlus17 &&
Richard Smithed638862016-03-28 06:08:37 +00004123 Kind.getKind() == InitializationKind::IK_DirectList &&
4124 ET && ET->getDecl()->isFixed() &&
4125 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4126 (E->getType()->isIntegralOrEnumerationType() ||
4127 E->getType()->isFloatingType())) {
4128 // There are two ways that T(v) can work when T is an enumeration type.
4129 // If there is either an implicit conversion sequence from v to T or
4130 // a conversion function that can convert from v to T, then we use that.
4131 // Otherwise, if v is of integral, enumeration, or floating-point type,
4132 // it is converted to the enumeration type via its underlying type.
4133 // There is no overlap possible between these two cases (except when the
4134 // source value is already of the destination type), and the first
4135 // case is handled by the general case for single-element lists below.
4136 ImplicitConversionSequence ICS;
4137 ICS.setStandard();
4138 ICS.Standard.setAsIdentityConversion();
Vedant Kumarf4217f82017-02-16 01:20:00 +00004139 if (!E->isRValue())
4140 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
Richard Smithed638862016-03-28 06:08:37 +00004141 // If E is of a floating-point type, then the conversion is ill-formed
4142 // due to narrowing, but go through the motions in order to produce the
4143 // right diagnostic.
4144 ICS.Standard.Second = E->getType()->isFloatingType()
4145 ? ICK_Floating_Integral
4146 : ICK_Integral_Conversion;
4147 ICS.Standard.setFromType(E->getType());
4148 ICS.Standard.setToType(0, E->getType());
4149 ICS.Standard.setToType(1, DestType);
4150 ICS.Standard.setToType(2, DestType);
4151 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4152 /*TopLevelOfInitList*/true);
4153 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4154 return;
4155 }
4156
Richard Smith089c3162013-09-21 21:55:46 +00004157 // - Otherwise, if the initializer list has a single element of type E
4158 // [...references are handled above...], the object or reference is
Larisse Voufod2010992015-01-24 23:09:54 +00004159 // initialized from that element (by copy-initialization for
4160 // copy-list-initialization, or by direct-initialization for
4161 // direct-list-initialization); if a narrowing conversion is required
4162 // to convert the element to T, the program is ill-formed.
4163 //
Richard Smith089c3162013-09-21 21:55:46 +00004164 // Per core-24034, this is direct-initialization if we were performing
4165 // direct-list-initialization and copy-initialization otherwise.
4166 // We can't use InitListChecker for this, because it always performs
4167 // copy-initialization. This only matters if we might use an 'explicit'
4168 // conversion operator, so we only need to handle the cases where the source
4169 // is of record type.
Richard Smithed638862016-03-28 06:08:37 +00004170 if (InitList->getInit(0)->getType()->isRecordType()) {
4171 InitializationKind SubKind =
4172 Kind.getKind() == InitializationKind::IK_DirectList
4173 ? InitializationKind::CreateDirect(Kind.getLocation(),
4174 InitList->getLBraceLoc(),
4175 InitList->getRBraceLoc())
4176 : Kind;
4177 Expr *SubInit[1] = { InitList->getInit(0) };
4178 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4179 /*TopLevelOfInitList*/true,
4180 TreatUnavailableAsInvalid);
4181 if (Sequence)
4182 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4183 return;
4184 }
Richard Smith089c3162013-09-21 21:55:46 +00004185 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004186
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004187 InitListChecker CheckInitList(S, Entity, InitList,
Manman Ren073db022016-03-10 18:53:19 +00004188 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004189 if (CheckInitList.HadError()) {
4190 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
4191 return;
4192 }
4193
4194 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004195 Sequence.AddListInitializationStep(DestType);
4196}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004197
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004198/// Try a reference initialization that involves calling a conversion
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004199/// function.
Richard Smithb8c0f552016-12-09 18:49:13 +00004200static OverloadingResult TryRefInitWithConversionFunction(
4201 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4202 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4203 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004204 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004205 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4206 QualType T1 = cv1T1.getUnqualifiedType();
4207 QualType cv2T2 = Initializer->getType();
4208 QualType T2 = cv2T2.getUnqualifiedType();
4209
4210 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004211 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00004212 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004213 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004214 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004215 ObjCConversion,
4216 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004217 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00004218 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004219 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00004220 (void)ObjCLifetimeConversion;
4221
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004222 // Build the candidate set directly in the initialization sequence
4223 // structure, so that it will persist if we fail.
4224 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
Richard Smith67ef14f2017-09-26 18:37:55 +00004225 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004226
Richard Smithb368ea82018-07-02 23:25:22 +00004227 // Determine whether we are allowed to call explicit conversion operators.
4228 // Note that none of [over.match.copy], [over.match.conv], nor
4229 // [over.match.ref] permit an explicit constructor to be chosen when
4230 // initializing a reference, not even for direct-initialization.
4231 bool AllowExplicitCtors = false;
Richard Smith6c6ddab2013-09-21 21:23:47 +00004232 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4233
Craig Topperc3ec1492014-05-26 06:22:03 +00004234 const RecordType *T1RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00004235 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004236 S.isCompleteType(Kind.getLocation(), T1)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004237 // The type we're converting to is a class type. Enumerate its constructors
4238 // to see if there is a suitable conversion.
4239 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00004240
Richard Smith40c78062015-02-21 02:31:57 +00004241 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
Richard Smithc2bebe92016-05-11 20:37:46 +00004242 auto Info = getConstructorInfo(D);
4243 if (!Info.Constructor)
4244 continue;
John McCalla0296f72010-03-19 07:35:19 +00004245
Richard Smithc2bebe92016-05-11 20:37:46 +00004246 if (!Info.Constructor->isInvalidDecl() &&
Richard Smithb368ea82018-07-02 23:25:22 +00004247 Info.Constructor->isConvertingConstructor(AllowExplicitCtors)) {
Richard Smithc2bebe92016-05-11 20:37:46 +00004248 if (Info.ConstructorTmpl)
4249 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004250 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004251 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00004252 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004253 else
Richard Smithc2bebe92016-05-11 20:37:46 +00004254 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004255 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00004256 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004257 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004258 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004259 }
John McCall3696dcb2010-08-17 07:23:57 +00004260 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4261 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004262
Craig Topperc3ec1492014-05-26 06:22:03 +00004263 const RecordType *T2RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00004264 if ((T2RecordType = T2->getAs<RecordType>()) &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004265 S.isCompleteType(Kind.getLocation(), T2)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004266 // The type we're converting from is a class type, enumerate its conversion
4267 // functions.
4268 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4269
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004270 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4271 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004272 NamedDecl *D = *I;
4273 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4274 if (isa<UsingShadowDecl>(D))
4275 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004276
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004277 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4278 CXXConversionDecl *Conv;
4279 if (ConvTemplate)
4280 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4281 else
Sebastian Redld92badf2010-06-30 18:13:39 +00004282 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004283
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004284 // If the conversion function doesn't return a reference type,
4285 // it can't be considered for this conversion unless we're allowed to
4286 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004287 // FIXME: Do we need to make sure that we only consider conversion
4288 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004289 // break recursion.
Douglas Gregor6073dca2012-02-24 23:56:31 +00004290 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004291 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
4292 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004293 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004294 ActingDC, Initializer,
Douglas Gregor68782142013-12-18 21:46:16 +00004295 DestType, CandidateSet,
4296 /*AllowObjCConversionOnExplicit=*/
4297 false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004298 else
John McCalla0296f72010-03-19 07:35:19 +00004299 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004300 Initializer, DestType, CandidateSet,
4301 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004302 }
4303 }
4304 }
John McCall3696dcb2010-08-17 07:23:57 +00004305 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4306 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004307
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004308 SourceLocation DeclLoc = Initializer->getLocStart();
4309
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004310 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004311 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004312 if (OverloadingResult Result
Richard Smith67ef14f2017-09-26 18:37:55 +00004313 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004314 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004315
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004316 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004317 // This is the overload that will be used for this initialization step if we
4318 // use this initialization. Mark it as referenced.
4319 Function->setReferenced();
Chandler Carruth30141632011-02-25 19:41:05 +00004320
Richard Smithb8c0f552016-12-09 18:49:13 +00004321 // Compute the returned type and value kind of the conversion.
4322 QualType cv3T3;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004323 if (isa<CXXConversionDecl>(Function))
Richard Smithb8c0f552016-12-09 18:49:13 +00004324 cv3T3 = Function->getReturnType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004325 else
Richard Smithb8c0f552016-12-09 18:49:13 +00004326 cv3T3 = T1;
4327
4328 ExprValueKind VK = VK_RValue;
4329 if (cv3T3->isLValueReferenceType())
4330 VK = VK_LValue;
4331 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4332 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4333 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004334
4335 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004336 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Richard Smithb8c0f552016-12-09 18:49:13 +00004337 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004338 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004339
Richard Smithb8c0f552016-12-09 18:49:13 +00004340 // Determine whether we'll need to perform derived-to-base adjustments or
4341 // other conversions.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004342 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004343 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004344 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004345 Sema::ReferenceCompareResult NewRefRelationship
Richard Smithb8c0f552016-12-09 18:49:13 +00004346 = S.CompareReferenceRelationship(DeclLoc, T1, cv3T3,
John McCall31168b02011-06-15 23:02:42 +00004347 NewDerivedToBase, NewObjCConversion,
4348 NewObjCLifetimeConversion);
Richard Smithb8c0f552016-12-09 18:49:13 +00004349
4350 // Add the final conversion sequence, if necessary.
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00004351 if (NewRefRelationship == Sema::Ref_Incompatible) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004352 assert(!isa<CXXConstructorDecl>(Function) &&
4353 "should not have conversion after constructor");
4354
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00004355 ImplicitConversionSequence ICS;
4356 ICS.setStandard();
4357 ICS.Standard = Best->FinalConversion;
Richard Smithb8c0f552016-12-09 18:49:13 +00004358 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4359
4360 // Every implicit conversion results in a prvalue, except for a glvalue
4361 // derived-to-base conversion, which we handle below.
4362 cv3T3 = ICS.Standard.getToType(2);
4363 VK = VK_RValue;
4364 }
4365
4366 // If the converted initializer is a prvalue, its type T4 is adjusted to
4367 // type "cv1 T4" and the temporary materialization conversion is applied.
4368 //
4369 // We adjust the cv-qualifications to match the reference regardless of
4370 // whether we have a prvalue so that the AST records the change. In this
4371 // case, T4 is "cv3 T3".
4372 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4373 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4374 Sequence.AddQualificationConversionStep(cv1T4, VK);
4375 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue);
4376 VK = IsLValueRef ? VK_LValue : VK_XValue;
4377
4378 if (NewDerivedToBase)
4379 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004380 else if (NewObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004381 Sequence.AddObjCObjectConversionStep(cv1T1);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004382
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004383 return OR_Success;
4384}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004385
Richard Smithc620f552011-10-19 16:55:56 +00004386static void CheckCXX98CompatAccessibleCopy(Sema &S,
4387 const InitializedEntity &Entity,
4388 Expr *CurInitExpr);
4389
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004390/// Attempt reference initialization (C++0x [dcl.init.ref])
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004391static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004392 const InitializedEntity &Entity,
4393 const InitializationKind &Kind,
4394 Expr *Initializer,
4395 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004396 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004397 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00004398 Qualifiers T1Quals;
4399 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004400 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00004401 Qualifiers T2Quals;
4402 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00004403
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004404 // If the initializer is the address of an overloaded function, try
4405 // to resolve the overloaded function. If all goes well, T2 is the
4406 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00004407 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4408 T1, Sequence))
4409 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00004410
Sebastian Redl29526f02011-11-27 16:50:07 +00004411 // Delegate everything else to a subfunction.
4412 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4413 T1Quals, cv2T2, T2, T2Quals, Sequence);
4414}
4415
Richard Smithb8c0f552016-12-09 18:49:13 +00004416/// Determine whether an expression is a non-referenceable glvalue (one to
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004417/// which a reference can never bind). Attempting to bind a reference to
Richard Smithb8c0f552016-12-09 18:49:13 +00004418/// such a glvalue will always create a temporary.
4419static bool isNonReferenceableGLValue(Expr *E) {
4420 return E->refersToBitField() || E->refersToVectorElement();
Jordan Roseb1312a52013-04-11 00:58:58 +00004421}
4422
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004423/// Reference initialization without resolving overloaded functions.
Sebastian Redl29526f02011-11-27 16:50:07 +00004424static void TryReferenceInitializationCore(Sema &S,
4425 const InitializedEntity &Entity,
4426 const InitializationKind &Kind,
4427 Expr *Initializer,
4428 QualType cv1T1, QualType T1,
4429 Qualifiers T1Quals,
4430 QualType cv2T2, QualType T2,
4431 Qualifiers T2Quals,
4432 InitializationSequence &Sequence) {
4433 QualType DestType = Entity.getType();
4434 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004435 // Compute some basic properties of the types and the initializer.
4436 bool isLValueRef = DestType->isLValueReferenceType();
4437 bool isRValueRef = !isLValueRef;
4438 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004439 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004440 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004441 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004442 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004443 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004444 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00004445
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004446 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004447 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004448 // "cv2 T2" as follows:
4449 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004450 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004451 // expression
Richard Smith6c6ddab2013-09-21 21:23:47 +00004452 // Note the analogous bullet points for rvalue refs to functions. Because
Sebastian Redld92badf2010-06-30 18:13:39 +00004453 // there are no function rvalues in C++, rvalue refs to functions are treated
4454 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004455 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00004456 bool T1Function = T1->isFunctionType();
4457 if (isLValueRef || T1Function) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004458 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
Richard Smithce766292016-10-21 23:01:55 +00004459 (RefRelationship == Sema::Ref_Compatible ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004460 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004461 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004462 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004463 // reference-compatible with "cv2 T2," or
Richard Smithb8c0f552016-12-09 18:49:13 +00004464 if (T1Quals != T2Quals)
4465 // Convert to cv1 T2. This should only add qualifiers unless this is a
4466 // c-style cast. The removal of qualifiers in that case notionally
4467 // happens after the reference binding, but that doesn't matter.
4468 Sequence.AddQualificationConversionStep(
4469 S.Context.getQualifiedType(T2, T1Quals),
4470 Initializer->getValueKind());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004471 if (DerivedToBase)
Richard Smithb8c0f552016-12-09 18:49:13 +00004472 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004473 else if (ObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004474 Sequence.AddObjCObjectConversionStep(cv1T1);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004475
Richard Smithb8c0f552016-12-09 18:49:13 +00004476 // We only create a temporary here when binding a reference to a
4477 // bit-field or vector element. Those cases are't supposed to be
4478 // handled by this bullet, but the outcome is the same either way.
4479 Sequence.AddReferenceBindingStep(cv1T1, false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004480 return;
4481 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004482
4483 // - has a class type (i.e., T2 is a class type), where T1 is not
4484 // reference-related to T2, and can be implicitly converted to an
4485 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
4486 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004487 // applicable conversion functions (13.3.1.6) and choosing the best
4488 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00004489 // If we have an rvalue ref to function type here, the rhs must be
Richard Smith6c6ddab2013-09-21 21:23:47 +00004490 // an rvalue. DR1287 removed the "implicitly" here.
Sebastian Redld92badf2010-06-30 18:13:39 +00004491 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
4492 (isLValueRef || InitCategory.isRValue())) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00004493 ConvOvlResult = TryRefInitWithConversionFunction(
Richard Smithb8c0f552016-12-09 18:49:13 +00004494 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
4495 /*IsLValueRef*/ isLValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004496 if (ConvOvlResult == OR_Success)
4497 return;
Richard Smith6c6ddab2013-09-21 21:23:47 +00004498 if (ConvOvlResult != OR_No_Viable_Function)
John McCall0d1da222010-01-12 00:44:57 +00004499 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00004500 InitializationSequence::FK_ReferenceInitOverloadFailed,
4501 ConvOvlResult);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004502 }
4503 }
Sebastian Redld92badf2010-06-30 18:13:39 +00004504
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004505 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004506 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00004507 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004508 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00004509 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4510 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4511 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004512 Sequence.SetOverloadFailure(
4513 InitializationSequence::FK_ReferenceInitOverloadFailed,
4514 ConvOvlResult);
Richard Smithb8c0f552016-12-09 18:49:13 +00004515 else if (!InitCategory.isLValue())
4516 Sequence.SetFailed(
4517 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4518 else {
4519 InitializationSequence::FailureKind FK;
4520 switch (RefRelationship) {
4521 case Sema::Ref_Compatible:
4522 if (Initializer->refersToBitField())
4523 FK = InitializationSequence::
4524 FK_NonConstLValueReferenceBindingToBitfield;
4525 else if (Initializer->refersToVectorElement())
4526 FK = InitializationSequence::
4527 FK_NonConstLValueReferenceBindingToVectorElement;
4528 else
4529 llvm_unreachable("unexpected kind of compatible initializer");
4530 break;
4531 case Sema::Ref_Related:
4532 FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
4533 break;
4534 case Sema::Ref_Incompatible:
4535 FK = InitializationSequence::
4536 FK_NonConstLValueReferenceBindingToUnrelated;
4537 break;
4538 }
4539 Sequence.SetFailed(FK);
4540 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004541 return;
4542 }
Sebastian Redld92badf2010-06-30 18:13:39 +00004543
Douglas Gregor92e460e2011-01-20 16:44:54 +00004544 // - If the initializer expression
Richard Smithb8c0f552016-12-09 18:49:13 +00004545 // - is an
4546 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
4547 // [1z] rvalue (but not a bit-field) or
4548 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
4549 //
4550 // Note: functions are handled above and below rather than here...
Douglas Gregor92e460e2011-01-20 16:44:54 +00004551 if (!T1Function &&
Richard Smithce766292016-10-21 23:01:55 +00004552 (RefRelationship == Sema::Ref_Compatible ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004553 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004554 RefRelationship == Sema::Ref_Related)) &&
Richard Smithb8c0f552016-12-09 18:49:13 +00004555 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
Richard Smith122f88d2016-12-06 23:52:28 +00004556 (InitCategory.isPRValue() &&
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004557 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
Richard Smith122f88d2016-12-06 23:52:28 +00004558 T2->isArrayType())))) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004559 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_RValue;
Douglas Gregor92e460e2011-01-20 16:44:54 +00004560 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004561 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
4562 // compiler the freedom to perform a copy here or bind to the
4563 // object, while C++0x requires that we bind directly to the
4564 // object. Hence, we always bind to the object without making an
4565 // extra copy. However, in C++03 requires that we check for the
4566 // presence of a suitable copy constructor:
4567 //
4568 // The constructor that would be used to make the copy shall
4569 // be callable whether or not the copy is actually done.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004570 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004571 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004572 else if (S.getLangOpts().CPlusPlus11)
Richard Smithc620f552011-10-19 16:55:56 +00004573 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004574 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004575
Richard Smithb8c0f552016-12-09 18:49:13 +00004576 // C++1z [dcl.init.ref]/5.2.1.2:
4577 // If the converted initializer is a prvalue, its type T4 is adjusted
4578 // to type "cv1 T4" and the temporary materialization conversion is
4579 // applied.
4580 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1Quals);
4581 if (T1Quals != T2Quals)
4582 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
4583 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue);
4584 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
4585
4586 // In any case, the reference is bound to the resulting glvalue (or to
4587 // an appropriate base class subobject).
Douglas Gregor92e460e2011-01-20 16:44:54 +00004588 if (DerivedToBase)
Richard Smithb8c0f552016-12-09 18:49:13 +00004589 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
Douglas Gregor92e460e2011-01-20 16:44:54 +00004590 else if (ObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004591 Sequence.AddObjCObjectConversionStep(cv1T1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004592 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00004593 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004594
4595 // - has a class type (i.e., T2 is a class type), where T1 is not
4596 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00004597 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
4598 // where "cv1 T1" is reference-compatible with "cv3 T3",
Richard Smith6c6ddab2013-09-21 21:23:47 +00004599 //
4600 // DR1287 removes the "implicitly" here.
Douglas Gregor92e460e2011-01-20 16:44:54 +00004601 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004602 if (RefRelationship == Sema::Ref_Incompatible) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00004603 ConvOvlResult = TryRefInitWithConversionFunction(
Richard Smithb8c0f552016-12-09 18:49:13 +00004604 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
4605 /*IsLValueRef*/ isLValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004606 if (ConvOvlResult)
4607 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00004608 InitializationSequence::FK_ReferenceInitOverloadFailed,
4609 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004610
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004611 return;
4612 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004613
Richard Smithce766292016-10-21 23:01:55 +00004614 if (RefRelationship == Sema::Ref_Compatible &&
Douglas Gregor6fa6ab02013-03-26 23:59:23 +00004615 isRValueRef && InitCategory.isLValue()) {
4616 Sequence.SetFailed(
4617 InitializationSequence::FK_RValueReferenceBindingToLValue);
4618 return;
4619 }
4620
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004621 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4622 return;
4623 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004624
4625 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004626 // from the initializer expression using the rules for a non-reference
Richard Smith2eabf782013-06-13 00:57:57 +00004627 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004628 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00004629
John McCallec6f4e92010-06-04 02:29:22 +00004630 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4631
Richard Smith2eabf782013-06-13 00:57:57 +00004632 // FIXME: Why do we use an implicit conversion here rather than trying
4633 // copy-initialization?
John McCall31168b02011-06-15 23:02:42 +00004634 ImplicitConversionSequence ICS
4635 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith2eabf782013-06-13 00:57:57 +00004636 /*SuppressUserConversions=*/false,
4637 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004638 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004639 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4640 /*AllowObjCWritebackConversion=*/false);
4641
4642 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004643 // FIXME: Use the conversion function set stored in ICS to turn
4644 // this into an overloading ambiguity diagnostic. However, we need
4645 // to keep that set as an OverloadCandidateSet rather than as some
4646 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00004647 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4648 Sequence.SetOverloadFailure(
4649 InitializationSequence::FK_ReferenceInitOverloadFailed,
4650 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00004651 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4652 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00004653 else
4654 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004655 return;
John McCall31168b02011-06-15 23:02:42 +00004656 } else {
4657 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004658 }
4659
4660 // [...] If T1 is reference-related to T2, cv1 must be the
4661 // same cv-qualification as, or greater cv-qualification
4662 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00004663 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4664 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004665 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00004666 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004667 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4668 return;
4669 }
4670
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004671 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004672 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004673 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004674 InitCategory.isLValue()) {
4675 Sequence.SetFailed(
4676 InitializationSequence::FK_RValueReferenceBindingToLValue);
4677 return;
4678 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004679
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004680 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004681}
4682
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004683/// Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004684/// (C++ [dcl.init.string], C99 6.7.8).
4685static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004686 const InitializedEntity &Entity,
4687 const InitializationKind &Kind,
4688 Expr *Initializer,
4689 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004690 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004691}
4692
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004693/// Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004694static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004695 const InitializedEntity &Entity,
4696 const InitializationKind &Kind,
Richard Smithd86812d2012-07-05 08:39:21 +00004697 InitializationSequence &Sequence,
4698 InitListExpr *InitList) {
4699 assert((!InitList || InitList->getNumInits() == 0) &&
4700 "Shouldn't use value-init for non-empty init lists");
4701
Richard Smith1bfe0682012-02-14 21:14:13 +00004702 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004703 //
4704 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00004705 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004706
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004707 // -- if T is an array type, then each element is value-initialized;
Richard Smith1bfe0682012-02-14 21:14:13 +00004708 T = S.Context.getBaseElementType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004709
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004710 if (const RecordType *RT = T->getAs<RecordType>()) {
4711 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithd86812d2012-07-05 08:39:21 +00004712 bool NeedZeroInitialization = true;
Richard Smith505ef812016-12-21 01:57:02 +00004713 // C++98:
4714 // -- if T is a class type (clause 9) with a user-declared constructor
4715 // (12.1), then the default constructor for T is called (and the
4716 // initialization is ill-formed if T has no accessible default
4717 // constructor);
4718 // C++11:
4719 // -- if T is a class type (clause 9) with either no default constructor
4720 // (12.1 [class.ctor]) or a default constructor that is user-provided
4721 // or deleted, then the object is default-initialized;
4722 //
4723 // Note that the C++11 rule is the same as the C++98 rule if there are no
4724 // defaulted or deleted constructors, so we just use it unconditionally.
4725 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4726 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
4727 NeedZeroInitialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004728
Richard Smith1bfe0682012-02-14 21:14:13 +00004729 // -- if T is a (possibly cv-qualified) non-union class type without a
4730 // user-provided or deleted default constructor, then the object is
4731 // zero-initialized and, if T has a non-trivial default constructor,
4732 // default-initialized;
Richard Smithfb266522012-10-18 00:44:17 +00004733 // The 'non-union' here was removed by DR1502. The 'non-trivial default
4734 // constructor' part was removed by DR1507.
Richard Smithd86812d2012-07-05 08:39:21 +00004735 if (NeedZeroInitialization)
4736 Sequence.AddZeroInitializationStep(Entity.getType());
4737
Richard Smith593f9932012-12-08 02:01:17 +00004738 // C++03:
4739 // -- if T is a non-union class type without a user-declared constructor,
4740 // then every non-static data member and base class component of T is
4741 // value-initialized;
4742 // [...] A program that calls for [...] value-initialization of an
4743 // entity of reference type is ill-formed.
4744 //
4745 // C++11 doesn't need this handling, because value-initialization does not
4746 // occur recursively there, and the implicit default constructor is
4747 // defined as deleted in the problematic cases.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004748 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smith593f9932012-12-08 02:01:17 +00004749 ClassDecl->hasUninitializedReferenceMember()) {
4750 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4751 return;
4752 }
4753
Richard Smithd86812d2012-07-05 08:39:21 +00004754 // If this is list-value-initialization, pass the empty init list on when
4755 // building the constructor call. This affects the semantics of a few
4756 // things (such as whether an explicit default constructor can be called).
4757 Expr *InitListAsExpr = InitList;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004758 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithd86812d2012-07-05 08:39:21 +00004759 bool InitListSyntax = InitList;
4760
Richard Smith81f5ade2016-12-15 02:28:18 +00004761 // FIXME: Instead of creating a CXXConstructExpr of array type here,
Richard Smith410306b2016-12-12 02:53:20 +00004762 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
4763 return TryConstructorInitialization(
4764 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004765 }
4766 }
4767
Douglas Gregor1b303932009-12-22 15:35:07 +00004768 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004769}
4770
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004771/// Attempt default initialization (C++ [dcl.init]p6).
Douglas Gregor85dabae2009-12-16 01:38:02 +00004772static void TryDefaultInitialization(Sema &S,
4773 const InitializedEntity &Entity,
4774 const InitializationKind &Kind,
4775 InitializationSequence &Sequence) {
4776 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004777
Douglas Gregor85dabae2009-12-16 01:38:02 +00004778 // C++ [dcl.init]p6:
4779 // To default-initialize an object of type T means:
4780 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00004781 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4782
Douglas Gregor85dabae2009-12-16 01:38:02 +00004783 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4784 // constructor for T is called (and the initialization is ill-formed if
4785 // T has no accessible default constructor);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004786 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Richard Smith410306b2016-12-12 02:53:20 +00004787 TryConstructorInitialization(S, Entity, Kind, None, DestType,
4788 Entity.getType(), Sequence);
Chandler Carruthc9262402010-08-23 07:55:51 +00004789 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004790 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004791
Douglas Gregor85dabae2009-12-16 01:38:02 +00004792 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004793
Douglas Gregor85dabae2009-12-16 01:38:02 +00004794 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004795 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00004796 // default constructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004797 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Nico Weber337d5aa2015-04-17 08:32:38 +00004798 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4799 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00004800 return;
4801 }
4802
4803 // If the destination type has a lifetime property, zero-initialize it.
4804 if (DestType.getQualifiers().hasObjCLifetime()) {
4805 Sequence.AddZeroInitializationStep(Entity.getType());
4806 return;
4807 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004808}
4809
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004810/// Attempt a user-defined conversion between two types (C++ [dcl.init]),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004811/// which enumerates all conversion functions and performs overload resolution
4812/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004813static void TryUserDefinedConversion(Sema &S,
Richard Smith77be48a2014-07-31 06:31:19 +00004814 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004815 const InitializationKind &Kind,
4816 Expr *Initializer,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004817 InitializationSequence &Sequence,
4818 bool TopLevelOfInitList) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004819 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4820 QualType SourceType = Initializer->getType();
4821 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4822 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004823
Douglas Gregor540c3b02009-12-14 17:27:33 +00004824 // Build the candidate set directly in the initialization sequence
4825 // structure, so that it will persist if we fail.
4826 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
Richard Smith67ef14f2017-09-26 18:37:55 +00004827 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004828
Douglas Gregor540c3b02009-12-14 17:27:33 +00004829 // Determine whether we are allowed to call explicit constructors or
4830 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00004831 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004832
Douglas Gregor540c3b02009-12-14 17:27:33 +00004833 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4834 // The type we're converting to is a class type. Enumerate its constructors
4835 // to see if there is a suitable conversion.
4836 CXXRecordDecl *DestRecordDecl
4837 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004838
Douglas Gregord9848152010-04-26 14:36:57 +00004839 // Try to complete the type we're converting to.
Richard Smithdb0ac552015-12-18 22:40:25 +00004840 if (S.isCompleteType(Kind.getLocation(), DestType)) {
Richard Smith776e9c32017-02-01 03:28:59 +00004841 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
Richard Smithc2bebe92016-05-11 20:37:46 +00004842 auto Info = getConstructorInfo(D);
4843 if (!Info.Constructor)
4844 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004845
Richard Smithc2bebe92016-05-11 20:37:46 +00004846 if (!Info.Constructor->isInvalidDecl() &&
4847 Info.Constructor->isConvertingConstructor(AllowExplicit)) {
4848 if (Info.ConstructorTmpl)
4849 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004850 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004851 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004852 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004853 else
Richard Smithc2bebe92016-05-11 20:37:46 +00004854 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004855 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004856 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004857 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004858 }
Douglas Gregord9848152010-04-26 14:36:57 +00004859 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004860 }
Eli Friedman78275202009-12-19 08:11:05 +00004861
4862 SourceLocation DeclLoc = Initializer->getLocStart();
4863
Douglas Gregor540c3b02009-12-14 17:27:33 +00004864 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4865 // The type we're converting from is a class type, enumerate its conversion
4866 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00004867
Eli Friedman4afe9a32009-12-20 22:12:03 +00004868 // We can only enumerate the conversion functions for a complete type; if
4869 // the type isn't complete, simply skip this step.
Richard Smithdb0ac552015-12-18 22:40:25 +00004870 if (S.isCompleteType(DeclLoc, SourceType)) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004871 CXXRecordDecl *SourceRecordDecl
4872 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004873
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004874 const auto &Conversions =
4875 SourceRecordDecl->getVisibleConversionFunctions();
4876 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004877 NamedDecl *D = *I;
4878 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4879 if (isa<UsingShadowDecl>(D))
4880 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004881
Eli Friedman4afe9a32009-12-20 22:12:03 +00004882 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4883 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00004884 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00004885 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00004886 else
John McCallda4458e2010-03-31 01:36:47 +00004887 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004888
Eli Friedman4afe9a32009-12-20 22:12:03 +00004889 if (AllowExplicit || !Conv->isExplicit()) {
4890 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004891 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004892 ActingDC, Initializer, DestType,
Douglas Gregor68782142013-12-18 21:46:16 +00004893 CandidateSet, AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004894 else
John McCalla0296f72010-03-19 07:35:19 +00004895 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004896 Initializer, DestType, CandidateSet,
4897 AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004898 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004899 }
4900 }
4901 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004902
4903 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004904 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00004905 if (OverloadingResult Result
Richard Smith67ef14f2017-09-26 18:37:55 +00004906 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004907 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004908 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00004909 Result);
4910 return;
4911 }
John McCall0d1da222010-01-12 00:44:57 +00004912
Douglas Gregor540c3b02009-12-14 17:27:33 +00004913 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004914 Function->setReferenced();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004915 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004916
Douglas Gregor540c3b02009-12-14 17:27:33 +00004917 if (isa<CXXConstructorDecl>(Function)) {
4918 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithb24f0672012-02-11 19:22:50 +00004919 // subsumed by the initialization. Per DR5, the created temporary is of the
4920 // cv-unqualified type of the destination.
4921 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4922 DestType.getUnqualifiedType(),
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004923 HadMultipleCandidates);
Richard Smithb8c0f552016-12-09 18:49:13 +00004924
4925 // C++14 and before:
4926 // - if the function is a constructor, the call initializes a temporary
4927 // of the cv-unqualified version of the destination type. The [...]
4928 // temporary [...] is then used to direct-initialize, according to the
4929 // rules above, the object that is the destination of the
4930 // copy-initialization.
4931 // Note that this just performs a simple object copy from the temporary.
4932 //
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004933 // C++17:
Richard Smithb8c0f552016-12-09 18:49:13 +00004934 // - if the function is a constructor, the call is a prvalue of the
4935 // cv-unqualified version of the destination type whose return object
4936 // is initialized by the constructor. The call is used to
4937 // direct-initialize, according to the rules above, the object that
4938 // is the destination of the copy-initialization.
4939 // Therefore we need to do nothing further.
4940 //
4941 // FIXME: Mark this copy as extraneous.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004942 if (!S.getLangOpts().CPlusPlus17)
Richard Smithb8c0f552016-12-09 18:49:13 +00004943 Sequence.AddFinalCopy(DestType);
Richard Smith16d31502016-12-21 01:31:56 +00004944 else if (DestType.hasQualifiers())
4945 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004946 return;
4947 }
4948
4949 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004950 QualType ConvType = Function->getCallResultType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004951 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4952 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004953
Richard Smithb8c0f552016-12-09 18:49:13 +00004954 if (ConvType->getAs<RecordType>()) {
4955 // The call is used to direct-initialize [...] the object that is the
4956 // destination of the copy-initialization.
4957 //
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004958 // In C++17, this does not call a constructor if we enter /17.6.1:
Richard Smithb8c0f552016-12-09 18:49:13 +00004959 // - If the initializer expression is a prvalue and the cv-unqualified
4960 // version of the source type is the same as the class of the
4961 // destination [... do not make an extra copy]
4962 //
4963 // FIXME: Mark this copy as extraneous.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004964 if (!S.getLangOpts().CPlusPlus17 ||
Richard Smithb8c0f552016-12-09 18:49:13 +00004965 Function->getReturnType()->isReferenceType() ||
4966 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
4967 Sequence.AddFinalCopy(DestType);
Richard Smith16d31502016-12-21 01:31:56 +00004968 else if (!S.Context.hasSameType(ConvType, DestType))
4969 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Richard Smithb8c0f552016-12-09 18:49:13 +00004970 return;
4971 }
4972
Douglas Gregor5ab11652010-04-17 22:01:05 +00004973 // If the conversion following the call to the conversion function
4974 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004975 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4976 Best->FinalConversion.Third) {
4977 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00004978 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00004979 ICS.Standard = Best->FinalConversion;
Richard Smithaaa0ec42013-09-21 21:19:19 +00004980 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004981 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004982}
4983
Richard Smithf032001b2013-06-20 02:18:31 +00004984/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4985/// a function with a pointer return type contains a 'return false;' statement.
4986/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4987/// code using that header.
4988///
4989/// Work around this by treating 'return false;' as zero-initializing the result
4990/// if it's used in a pointer-returning function in a system header.
4991static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4992 const InitializedEntity &Entity,
4993 const Expr *Init) {
4994 return S.getLangOpts().CPlusPlus11 &&
4995 Entity.getKind() == InitializedEntity::EK_Result &&
4996 Entity.getType()->isPointerType() &&
4997 isa<CXXBoolLiteralExpr>(Init) &&
4998 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4999 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
5000}
5001
John McCall31168b02011-06-15 23:02:42 +00005002/// The non-zero enum values here are indexes into diagnostic alternatives.
5003enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
5004
5005/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00005006static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005007 bool isAddressOf, bool &isWeakAccess) {
John McCall31168b02011-06-15 23:02:42 +00005008 // Skip parens.
5009 e = e->IgnoreParens();
5010
5011 // Skip address-of nodes.
5012 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
5013 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005014 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
5015 isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00005016
5017 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00005018 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
5019 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00005020 case CK_Dependent:
5021 case CK_BitCast:
5022 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00005023 case CK_NoOp:
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005024 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00005025
5026 case CK_ArrayToPointerDecay:
5027 return IIK_nonscalar;
5028
5029 case CK_NullToPointer:
5030 return IIK_okay;
5031
5032 default:
5033 break;
5034 }
5035
5036 // If we have a declaration reference, it had better be a local variable.
John McCall113bee02012-03-10 09:33:50 +00005037 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005038 // set isWeakAccess to true, to mean that there will be an implicit
5039 // load which requires a cleanup.
5040 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
5041 isWeakAccess = true;
5042
John McCall63f84442011-06-27 23:59:58 +00005043 if (!isAddressOf) return IIK_nonlocal;
5044
John McCall113bee02012-03-10 09:33:50 +00005045 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
5046 if (!var) return IIK_nonlocal;
John McCall63f84442011-06-27 23:59:58 +00005047
5048 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00005049
5050 // If we have a conditional operator, check both sides.
5051 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005052 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
5053 isWeakAccess))
John McCall31168b02011-06-15 23:02:42 +00005054 return iik;
5055
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005056 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00005057
5058 // These are never scalar.
5059 } else if (isa<ArraySubscriptExpr>(e)) {
5060 return IIK_nonscalar;
5061
5062 // Otherwise, it needs to be a null pointer constant.
5063 } else {
5064 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
5065 ? IIK_okay : IIK_nonlocal);
5066 }
5067
5068 return IIK_nonlocal;
5069}
5070
5071/// Check whether the given expression is a valid operand for an
5072/// indirect copy/restore.
5073static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
5074 assert(src->isRValue());
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005075 bool isWeakAccess = false;
5076 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
5077 // If isWeakAccess to true, there will be an implicit
5078 // load which requires a cleanup.
5079 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
Tim Shen4a05bb82016-06-21 20:29:17 +00005080 S.Cleanup.setExprNeedsCleanups(true);
5081
John McCall31168b02011-06-15 23:02:42 +00005082 if (iik == IIK_okay) return;
5083
5084 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
5085 << ((unsigned) iik - 1) // shift index into diagnostic explanations
5086 << src->getSourceRange();
5087}
5088
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005089/// Determine whether we have compatible array types for the
Douglas Gregore2f943b2011-02-22 18:29:51 +00005090/// purposes of GNU by-copy array initialization.
Larisse Voufod2010992015-01-24 23:09:54 +00005091static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
Douglas Gregore2f943b2011-02-22 18:29:51 +00005092 const ArrayType *Source) {
5093 // If the source and destination array types are equivalent, we're
5094 // done.
5095 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
5096 return true;
5097
5098 // Make sure that the element types are the same.
5099 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
5100 return false;
5101
5102 // The only mismatch we allow is when the destination is an
5103 // incomplete array type and the source is a constant array type.
5104 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
5105}
5106
John McCall31168b02011-06-15 23:02:42 +00005107static bool tryObjCWritebackConversion(Sema &S,
5108 InitializationSequence &Sequence,
5109 const InitializedEntity &Entity,
5110 Expr *Initializer) {
5111 bool ArrayDecay = false;
5112 QualType ArgType = Initializer->getType();
5113 QualType ArgPointee;
5114 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
5115 ArrayDecay = true;
5116 ArgPointee = ArgArrayType->getElementType();
5117 ArgType = S.Context.getPointerType(ArgPointee);
5118 }
5119
5120 // Handle write-back conversion.
5121 QualType ConvertedArgType;
5122 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
5123 ConvertedArgType))
5124 return false;
5125
5126 // We should copy unless we're passing to an argument explicitly
5127 // marked 'out'.
5128 bool ShouldCopy = true;
5129 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5130 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5131
5132 // Do we need an lvalue conversion?
5133 if (ArrayDecay || Initializer->isGLValue()) {
5134 ImplicitConversionSequence ICS;
5135 ICS.setStandard();
5136 ICS.Standard.setAsIdentityConversion();
5137
5138 QualType ResultType;
5139 if (ArrayDecay) {
5140 ICS.Standard.First = ICK_Array_To_Pointer;
5141 ResultType = S.Context.getPointerType(ArgPointee);
5142 } else {
5143 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
5144 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
5145 }
5146
5147 Sequence.AddConversionSequenceStep(ICS, ResultType);
5148 }
5149
5150 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
5151 return true;
5152}
5153
Guy Benyei61054192013-02-07 10:55:47 +00005154static bool TryOCLSamplerInitialization(Sema &S,
5155 InitializationSequence &Sequence,
5156 QualType DestType,
5157 Expr *Initializer) {
5158 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00005159 (!Initializer->isIntegerConstantExpr(S.Context) &&
5160 !Initializer->getType()->isSamplerT()))
Guy Benyei61054192013-02-07 10:55:47 +00005161 return false;
5162
5163 Sequence.AddOCLSamplerInitStep(DestType);
5164 return true;
5165}
5166
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005167//
5168// OpenCL 1.2 spec, s6.12.10
5169//
5170// The event argument can also be used to associate the
5171// async_work_group_copy with a previous async copy allowing
5172// an event to be shared by multiple async copies; otherwise
5173// event should be zero.
5174//
5175static bool TryOCLZeroEventInitialization(Sema &S,
5176 InitializationSequence &Sequence,
5177 QualType DestType,
5178 Expr *Initializer) {
5179 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
5180 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
5181 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
5182 return false;
5183
5184 Sequence.AddOCLZeroEventStep(DestType);
5185 return true;
5186}
5187
Egor Churaev89831422016-12-23 14:55:49 +00005188static bool TryOCLZeroQueueInitialization(Sema &S,
5189 InitializationSequence &Sequence,
5190 QualType DestType,
5191 Expr *Initializer) {
5192 if (!S.getLangOpts().OpenCL || S.getLangOpts().OpenCLVersion < 200 ||
5193 !DestType->isQueueT() ||
5194 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
5195 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
5196 return false;
5197
5198 Sequence.AddOCLZeroQueueStep(DestType);
5199 return true;
5200}
5201
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005202InitializationSequence::InitializationSequence(Sema &S,
5203 const InitializedEntity &Entity,
5204 const InitializationKind &Kind,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005205 MultiExprArg Args,
Manman Ren073db022016-03-10 18:53:19 +00005206 bool TopLevelOfInitList,
5207 bool TreatUnavailableAsInvalid)
Richard Smith100b24a2014-04-17 01:52:14 +00005208 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
Manman Ren073db022016-03-10 18:53:19 +00005209 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
5210 TreatUnavailableAsInvalid);
Richard Smith089c3162013-09-21 21:55:46 +00005211}
5212
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005213/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
5214/// address of that function, this returns true. Otherwise, it returns false.
5215static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
5216 auto *DRE = dyn_cast<DeclRefExpr>(E);
5217 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
5218 return false;
5219
5220 return !S.checkAddressOfFunctionIsAvailable(
5221 cast<FunctionDecl>(DRE->getDecl()));
5222}
5223
Richard Smith410306b2016-12-12 02:53:20 +00005224/// Determine whether we can perform an elementwise array copy for this kind
5225/// of entity.
5226static bool canPerformArrayCopy(const InitializedEntity &Entity) {
5227 switch (Entity.getKind()) {
5228 case InitializedEntity::EK_LambdaCapture:
5229 // C++ [expr.prim.lambda]p24:
5230 // For array members, the array elements are direct-initialized in
5231 // increasing subscript order.
5232 return true;
5233
5234 case InitializedEntity::EK_Variable:
5235 // C++ [dcl.decomp]p1:
5236 // [...] each element is copy-initialized or direct-initialized from the
5237 // corresponding element of the assignment-expression [...]
5238 return isa<DecompositionDecl>(Entity.getDecl());
5239
5240 case InitializedEntity::EK_Member:
5241 // C++ [class.copy.ctor]p14:
5242 // - if the member is an array, each element is direct-initialized with
5243 // the corresponding subobject of x
5244 return Entity.isImplicitMemberInitializer();
5245
5246 case InitializedEntity::EK_ArrayElement:
5247 // All the above cases are intended to apply recursively, even though none
5248 // of them actually say that.
5249 if (auto *E = Entity.getParent())
5250 return canPerformArrayCopy(*E);
5251 break;
5252
5253 default:
5254 break;
5255 }
5256
5257 return false;
5258}
5259
Richard Smith089c3162013-09-21 21:55:46 +00005260void InitializationSequence::InitializeFrom(Sema &S,
5261 const InitializedEntity &Entity,
5262 const InitializationKind &Kind,
5263 MultiExprArg Args,
Manman Ren073db022016-03-10 18:53:19 +00005264 bool TopLevelOfInitList,
5265 bool TreatUnavailableAsInvalid) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005266 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005267
John McCall5e77d762013-04-16 07:28:30 +00005268 // Eliminate non-overload placeholder types in the arguments. We
5269 // need to do this before checking whether types are dependent
5270 // because lowering a pseudo-object expression might well give us
5271 // something of dependent type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005272 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall5e77d762013-04-16 07:28:30 +00005273 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
5274 // FIXME: should we be doing this here?
5275 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
5276 if (result.isInvalid()) {
5277 SetFailed(FK_PlaceholderType);
5278 return;
5279 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005280 Args[I] = result.get();
John McCall5e77d762013-04-16 07:28:30 +00005281 }
5282
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005283 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005284 // The semantics of initializers are as follows. The destination type is
5285 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005286 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005287 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005288 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005289 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005290
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005291 if (DestType->isDependentType() ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005292 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005293 SequenceKind = DependentSequence;
5294 return;
5295 }
5296
Sebastian Redld201edf2011-06-05 13:59:11 +00005297 // Almost everything is a normal sequence.
5298 setSequenceKind(NormalSequence);
5299
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005300 QualType SourceType;
Craig Topperc3ec1492014-05-26 06:22:03 +00005301 Expr *Initializer = nullptr;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005302 if (Args.size() == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005303 Initializer = Args[0];
Fariborz Jahanian283bf892013-12-18 21:04:43 +00005304 if (S.getLangOpts().ObjC1) {
5305 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
5306 DestType, Initializer->getType(),
5307 Initializer) ||
5308 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
5309 Args[0] = Initializer;
Fariborz Jahanian283bf892013-12-18 21:04:43 +00005310 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005311 if (!isa<InitListExpr>(Initializer))
5312 SourceType = Initializer->getType();
5313 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005314
Sebastian Redl0501c632012-02-12 16:37:36 +00005315 // - If the initializer is a (non-parenthesized) braced-init-list, the
5316 // object is list-initialized (8.5.4).
5317 if (Kind.getKind() != InitializationKind::IK_Direct) {
5318 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Manman Ren073db022016-03-10 18:53:19 +00005319 TryListInitialization(S, Entity, Kind, InitList, *this,
5320 TreatUnavailableAsInvalid);
Sebastian Redl0501c632012-02-12 16:37:36 +00005321 return;
5322 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005323 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005324
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005325 // - If the destination type is a reference type, see 8.5.3.
5326 if (DestType->isReferenceType()) {
5327 // C++0x [dcl.init.ref]p1:
5328 // A variable declared to be a T& or T&&, that is, "reference to type T"
5329 // (8.3.2), shall be initialized by an object, or function, of type T or
5330 // by an object that can be converted into a T.
5331 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005332 if (Args.size() != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005333 SetFailed(FK_TooManyInitsForReference);
Richard Smith49a6b6e2017-03-24 01:14:25 +00005334 // C++17 [dcl.init.ref]p5:
5335 // A reference [...] is initialized by an expression [...] as follows:
5336 // If the initializer is not an expression, presumably we should reject,
5337 // but the standard fails to actually say so.
5338 else if (isa<InitListExpr>(Args[0]))
5339 SetFailed(FK_ParenthesizedListInitForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005340 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005341 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005342 return;
5343 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005344
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005345 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00005346 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005347 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005348 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005349 return;
5350 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005351
Douglas Gregor85dabae2009-12-16 01:38:02 +00005352 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00005353 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005354 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005355 return;
5356 }
Douglas Gregore1314a62009-12-18 05:02:21 +00005357
John McCall66884dd2011-02-21 07:22:22 +00005358 // - If the destination type is an array of characters, an array of
5359 // char16_t, an array of char32_t, or an array of wchar_t, and the
5360 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005361 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005362 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00005363 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00005364 if (Initializer && isa<VariableArrayType>(DestAT)) {
5365 SetFailed(FK_VariableLengthArrayHasInitializer);
5366 return;
5367 }
5368
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005369 if (Initializer) {
5370 switch (IsStringInit(Initializer, DestAT, Context)) {
5371 case SIF_None:
5372 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
5373 return;
5374 case SIF_NarrowStringIntoWideChar:
5375 SetFailed(FK_NarrowStringIntoWideCharArray);
5376 return;
5377 case SIF_WideStringIntoChar:
5378 SetFailed(FK_WideStringIntoCharArray);
5379 return;
5380 case SIF_IncompatWideStringIntoWideChar:
5381 SetFailed(FK_IncompatWideStringIntoWideChar);
5382 return;
Richard Smith3a8244d2018-05-01 05:02:45 +00005383 case SIF_PlainStringIntoUTF8Char:
5384 SetFailed(FK_PlainStringIntoUTF8Char);
5385 return;
5386 case SIF_UTF8StringIntoPlainChar:
5387 SetFailed(FK_UTF8StringIntoPlainChar);
5388 return;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005389 case SIF_Other:
5390 break;
5391 }
John McCall66884dd2011-02-21 07:22:22 +00005392 }
5393
Richard Smith410306b2016-12-12 02:53:20 +00005394 // Some kinds of initialization permit an array to be initialized from
5395 // another array of the same type, and perform elementwise initialization.
5396 if (Initializer && isa<ConstantArrayType>(DestAT) &&
5397 S.Context.hasSameUnqualifiedType(Initializer->getType(),
5398 Entity.getType()) &&
5399 canPerformArrayCopy(Entity)) {
5400 // If source is a prvalue, use it directly.
5401 if (Initializer->getValueKind() == VK_RValue) {
Richard Smith378b8c82016-12-14 03:22:16 +00005402 AddArrayInitStep(DestType, /*IsGNUExtension*/false);
Richard Smith410306b2016-12-12 02:53:20 +00005403 return;
5404 }
5405
5406 // Emit element-at-a-time copy loop.
5407 InitializedEntity Element =
5408 InitializedEntity::InitializeElement(S.Context, 0, Entity);
5409 QualType InitEltT =
5410 Context.getAsArrayType(Initializer->getType())->getElementType();
Richard Smith30e304e2016-12-14 00:03:17 +00005411 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
5412 Initializer->getValueKind(),
5413 Initializer->getObjectKind());
Richard Smith410306b2016-12-12 02:53:20 +00005414 Expr *OVEAsExpr = &OVE;
5415 InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
5416 TreatUnavailableAsInvalid);
5417 if (!Failed())
5418 AddArrayInitLoopStep(Entity.getType(), InitEltT);
5419 return;
5420 }
5421
Douglas Gregore2f943b2011-02-22 18:29:51 +00005422 // Note: as an GNU C extension, we allow initialization of an
5423 // array from a compound literal that creates an array of the same
5424 // type, so long as the initializer has no side effects.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005425 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregore2f943b2011-02-22 18:29:51 +00005426 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
5427 Initializer->getType()->isArrayType()) {
5428 const ArrayType *SourceAT
5429 = Context.getAsArrayType(Initializer->getType());
5430 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005431 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005432 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005433 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005434 else {
Richard Smith378b8c82016-12-14 03:22:16 +00005435 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005436 }
Richard Smithebeed412012-02-15 22:38:09 +00005437 }
Richard Smithd86812d2012-07-05 08:39:21 +00005438 // Note: as a GNU C++ extension, we allow list-initialization of a
5439 // class member of array type from a parenthesized initializer list.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005440 else if (S.getLangOpts().CPlusPlus &&
Richard Smithebeed412012-02-15 22:38:09 +00005441 Entity.getKind() == InitializedEntity::EK_Member &&
5442 Initializer && isa<InitListExpr>(Initializer)) {
5443 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
Manman Ren073db022016-03-10 18:53:19 +00005444 *this, TreatUnavailableAsInvalid);
Richard Smithebeed412012-02-15 22:38:09 +00005445 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005446 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005447 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005448 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
5449 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005450 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005451 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005452
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005453 return;
5454 }
Eli Friedman78275202009-12-19 08:11:05 +00005455
Larisse Voufod2010992015-01-24 23:09:54 +00005456 // Determine whether we should consider writeback conversions for
John McCall31168b02011-06-15 23:02:42 +00005457 // Objective-C ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005458 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005459 Entity.isParameterKind();
John McCall31168b02011-06-15 23:02:42 +00005460
5461 // We're at the end of the line for C: it's either a write-back conversion
5462 // or it's a C assignment. There's no need to check anything else.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005463 if (!S.getLangOpts().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00005464 // If allowed, check whether this is an Objective-C writeback conversion.
5465 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005466 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00005467 return;
5468 }
Guy Benyei61054192013-02-07 10:55:47 +00005469
5470 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
5471 return;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005472
5473 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
5474 return;
5475
Egor Churaev89831422016-12-23 14:55:49 +00005476 if (TryOCLZeroQueueInitialization(S, *this, DestType, Initializer))
5477 return;
5478
John McCall31168b02011-06-15 23:02:42 +00005479 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005480 AddCAssignmentStep(DestType);
5481 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00005482 return;
5483 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005484
David Blaikiebbafb8a2012-03-11 07:00:24 +00005485 assert(S.getLangOpts().CPlusPlus);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005486
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005487 // - If the destination type is a (possibly cv-qualified) class type:
5488 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005489 // - If the initialization is direct-initialization, or if it is
5490 // copy-initialization where the cv-unqualified version of the
5491 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005492 // class of the destination, constructors are considered. [...]
5493 if (Kind.getKind() == InitializationKind::IK_Direct ||
5494 (Kind.getKind() == InitializationKind::IK_Copy &&
5495 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005496 S.IsDerivedFrom(Initializer->getLocStart(), SourceType, DestType))))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005497 TryConstructorInitialization(S, Entity, Kind, Args,
Richard Smith410306b2016-12-12 02:53:20 +00005498 DestType, DestType, *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005499 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005500 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005501 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005502 // used) to a derived class thereof are enumerated as described in
5503 // 13.3.1.4, and the best one is chosen through overload resolution
5504 // (13.3).
5505 else
Richard Smith77be48a2014-07-31 06:31:19 +00005506 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005507 TopLevelOfInitList);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005508 return;
5509 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005510
Richard Smith49a6b6e2017-03-24 01:14:25 +00005511 assert(Args.size() >= 1 && "Zero-argument case handled above");
5512
5513 // The remaining cases all need a source type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005514 if (Args.size() > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005515 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005516 return;
Richard Smith49a6b6e2017-03-24 01:14:25 +00005517 } else if (isa<InitListExpr>(Args[0])) {
5518 SetFailed(FK_ParenthesizedListInitForScalar);
5519 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00005520 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005521
5522 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005523 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00005524 if (!SourceType.isNull() && SourceType->isRecordType()) {
Richard Smith77be48a2014-07-31 06:31:19 +00005525 // For a conversion to _Atomic(T) from either T or a class type derived
5526 // from T, initialize the T object then convert to _Atomic type.
5527 bool NeedAtomicConversion = false;
5528 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
5529 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005530 S.IsDerivedFrom(Initializer->getLocStart(), SourceType,
5531 Atomic->getValueType())) {
Richard Smith77be48a2014-07-31 06:31:19 +00005532 DestType = Atomic->getValueType();
5533 NeedAtomicConversion = true;
5534 }
5535 }
5536
5537 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005538 TopLevelOfInitList);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005539 MaybeProduceObjCObject(S, *this, Entity);
Richard Smith77be48a2014-07-31 06:31:19 +00005540 if (!Failed() && NeedAtomicConversion)
5541 AddAtomicConversionStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005542 return;
5543 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005544
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005545 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00005546 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005547 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005548 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005549 // destination type; no user-defined conversions are considered.
Richard Smith77be48a2014-07-31 06:31:19 +00005550
John McCall31168b02011-06-15 23:02:42 +00005551 ImplicitConversionSequence ICS
Richard Smith77be48a2014-07-31 06:31:19 +00005552 = S.TryImplicitConversion(Initializer, DestType,
John McCall31168b02011-06-15 23:02:42 +00005553 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00005554 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00005555 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00005556 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5557 allowObjCWritebackConversion);
Richard Smith77be48a2014-07-31 06:31:19 +00005558
5559 if (ICS.isStandard() &&
John McCall31168b02011-06-15 23:02:42 +00005560 ICS.Standard.Second == ICK_Writeback_Conversion) {
5561 // Objective-C ARC writeback conversion.
5562
5563 // We should copy unless we're passing to an argument explicitly
5564 // marked 'out'.
5565 bool ShouldCopy = true;
5566 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5567 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5568
5569 // If there was an lvalue adjustment, add it as a separate conversion.
5570 if (ICS.Standard.First == ICK_Array_To_Pointer ||
5571 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5572 ImplicitConversionSequence LvalueICS;
5573 LvalueICS.setStandard();
5574 LvalueICS.Standard.setAsIdentityConversion();
5575 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
5576 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005577 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00005578 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005579
Richard Smith77be48a2014-07-31 06:31:19 +00005580 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00005581 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00005582 DeclAccessPair dap;
Richard Smithf032001b2013-06-20 02:18:31 +00005583 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
5584 AddZeroInitializationStep(Entity.getType());
5585 } else if (Initializer->getType() == Context.OverloadTy &&
5586 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
5587 false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005588 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005589 else if (Initializer->getType()->isFunctionType() &&
5590 isExprAnUnaddressableFunction(S, Initializer))
5591 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
Douglas Gregore81f58e2010-11-08 03:40:48 +00005592 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005593 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00005594 } else {
Richard Smith77be48a2014-07-31 06:31:19 +00005595 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
John McCallfa272342011-06-16 23:24:51 +00005596
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005597 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00005598 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005599}
5600
5601InitializationSequence::~InitializationSequence() {
Davide Italiano67bb9f72015-07-01 21:51:58 +00005602 for (auto &S : Steps)
5603 S.Destroy();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005604}
5605
5606//===----------------------------------------------------------------------===//
5607// Perform initialization
5608//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005609static Sema::AssignmentAction
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005610getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005611 switch(Entity.getKind()) {
5612 case InitializedEntity::EK_Variable:
5613 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00005614 case InitializedEntity::EK_Exception:
5615 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005616 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00005617 return Sema::AA_Initializing;
5618
5619 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005620 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00005621 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5622 return Sema::AA_Sending;
5623
Douglas Gregore1314a62009-12-18 05:02:21 +00005624 return Sema::AA_Passing;
5625
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005626 case InitializedEntity::EK_Parameter_CF_Audited:
5627 if (Entity.getDecl() &&
5628 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5629 return Sema::AA_Sending;
5630
5631 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
5632
Douglas Gregore1314a62009-12-18 05:02:21 +00005633 case InitializedEntity::EK_Result:
5634 return Sema::AA_Returning;
5635
Douglas Gregore1314a62009-12-18 05:02:21 +00005636 case InitializedEntity::EK_Temporary:
Fariborz Jahanian14e95412013-07-11 19:13:34 +00005637 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00005638 // FIXME: Can we tell apart casting vs. converting?
5639 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005640
Douglas Gregore1314a62009-12-18 05:02:21 +00005641 case InitializedEntity::EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00005642 case InitializedEntity::EK_Binding:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00005643 case InitializedEntity::EK_ArrayElement:
5644 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005645 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005646 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005647 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005648 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005649 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00005650 return Sema::AA_Initializing;
5651 }
5652
David Blaikie8a40f702012-01-17 06:56:22 +00005653 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00005654}
5655
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005656/// Whether we should bind a created object as a temporary when
Douglas Gregor95562572010-04-24 23:45:46 +00005657/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005658static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005659 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00005660 case InitializedEntity::EK_ArrayElement:
5661 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005662 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00005663 case InitializedEntity::EK_New:
5664 case InitializedEntity::EK_Variable:
5665 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005666 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00005667 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005668 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00005669 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005670 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005671 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005672 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005673 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00005674 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005675
Douglas Gregore1314a62009-12-18 05:02:21 +00005676 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005677 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregore1314a62009-12-18 05:02:21 +00005678 case InitializedEntity::EK_Temporary:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005679 case InitializedEntity::EK_RelatedResult:
Richard Smith7873de02016-08-11 22:25:46 +00005680 case InitializedEntity::EK_Binding:
Douglas Gregore1314a62009-12-18 05:02:21 +00005681 return true;
5682 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005683
Douglas Gregore1314a62009-12-18 05:02:21 +00005684 llvm_unreachable("missed an InitializedEntity kind?");
5685}
5686
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005687/// Whether the given entity, when initialized with an object
Douglas Gregor95562572010-04-24 23:45:46 +00005688/// created for that initialization, requires destruction.
Richard Smithb8c0f552016-12-09 18:49:13 +00005689static bool shouldDestroyEntity(const InitializedEntity &Entity) {
Douglas Gregor95562572010-04-24 23:45:46 +00005690 switch (Entity.getKind()) {
Douglas Gregor95562572010-04-24 23:45:46 +00005691 case InitializedEntity::EK_Result:
5692 case InitializedEntity::EK_New:
5693 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005694 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00005695 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005696 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005697 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005698 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005699 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor95562572010-04-24 23:45:46 +00005700 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005701
Richard Smith27874d62013-01-08 00:08:23 +00005702 case InitializedEntity::EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00005703 case InitializedEntity::EK_Binding:
Douglas Gregor95562572010-04-24 23:45:46 +00005704 case InitializedEntity::EK_Variable:
5705 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005706 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor95562572010-04-24 23:45:46 +00005707 case InitializedEntity::EK_Temporary:
5708 case InitializedEntity::EK_ArrayElement:
5709 case InitializedEntity::EK_Exception:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005710 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005711 case InitializedEntity::EK_RelatedResult:
Douglas Gregor95562572010-04-24 23:45:46 +00005712 return true;
5713 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005714
5715 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00005716}
5717
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005718/// Get the location at which initialization diagnostics should appear.
Richard Smithc620f552011-10-19 16:55:56 +00005719static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
5720 Expr *Initializer) {
5721 switch (Entity.getKind()) {
5722 case InitializedEntity::EK_Result:
5723 return Entity.getReturnLoc();
5724
5725 case InitializedEntity::EK_Exception:
5726 return Entity.getThrowLoc();
5727
5728 case InitializedEntity::EK_Variable:
Richard Smith7873de02016-08-11 22:25:46 +00005729 case InitializedEntity::EK_Binding:
Richard Smithc620f552011-10-19 16:55:56 +00005730 return Entity.getDecl()->getLocation();
5731
Douglas Gregor19666fb2012-02-15 16:57:26 +00005732 case InitializedEntity::EK_LambdaCapture:
5733 return Entity.getCaptureLoc();
5734
Richard Smithc620f552011-10-19 16:55:56 +00005735 case InitializedEntity::EK_ArrayElement:
5736 case InitializedEntity::EK_Member:
5737 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005738 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithc620f552011-10-19 16:55:56 +00005739 case InitializedEntity::EK_Temporary:
5740 case InitializedEntity::EK_New:
5741 case InitializedEntity::EK_Base:
5742 case InitializedEntity::EK_Delegating:
5743 case InitializedEntity::EK_VectorElement:
5744 case InitializedEntity::EK_ComplexElement:
5745 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005746 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005747 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005748 case InitializedEntity::EK_RelatedResult:
Richard Smithc620f552011-10-19 16:55:56 +00005749 return Initializer->getLocStart();
5750 }
5751 llvm_unreachable("missed an InitializedEntity kind?");
5752}
5753
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005754/// Make a (potentially elidable) temporary copy of the object
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005755/// provided by the given initializer by calling the appropriate copy
5756/// constructor.
5757///
5758/// \param S The Sema object used for type-checking.
5759///
Abramo Bagnara92141d22011-01-27 19:55:10 +00005760/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005761/// the type of the initializer expression or a superclass thereof.
5762///
James Dennett634962f2012-06-14 21:40:34 +00005763/// \param Entity The entity being initialized.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005764///
5765/// \param CurInit The initializer expression.
5766///
5767/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5768/// is permitted in C++03 (but not C++0x) when binding a reference to
5769/// an rvalue.
5770///
5771/// \returns An expression that copies the initializer expression into
5772/// a temporary object, or an error expression if a copy could not be
5773/// created.
John McCalldadc5752010-08-24 06:29:42 +00005774static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005775 QualType T,
5776 const InitializedEntity &Entity,
5777 ExprResult CurInit,
5778 bool IsExtraneousCopy) {
Fariborz Jahanian36f7f132015-01-28 22:08:10 +00005779 if (CurInit.isInvalid())
5780 return CurInit;
Douglas Gregor5ab11652010-04-17 22:01:05 +00005781 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00005782 Expr *CurInitExpr = (Expr *)CurInit.get();
Craig Topperc3ec1492014-05-26 06:22:03 +00005783 CXXRecordDecl *Class = nullptr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005784 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005785 Class = cast<CXXRecordDecl>(Record->getDecl());
5786 if (!Class)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005787 return CurInit;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005788
Richard Smithc620f552011-10-19 16:55:56 +00005789 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00005790
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005791 // Make sure that the type we are copying is complete.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005792 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005793 return CurInit;
Douglas Gregord5c231e2010-04-24 21:09:25 +00005794
Richard Smith7c2bcc92016-09-07 02:14:33 +00005795 // Perform overload resolution using the class's constructors. Per
5796 // C++11 [dcl.init]p16, second bullet for class types, this initialization
Richard Smithc620f552011-10-19 16:55:56 +00005797 // is direct-initialization.
Richard Smith100b24a2014-04-17 01:52:14 +00005798 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smith7c2bcc92016-09-07 02:14:33 +00005799 DeclContext::lookup_result Ctors = S.LookupConstructors(Class);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005800
Douglas Gregore1314a62009-12-18 05:02:21 +00005801 OverloadCandidateSet::iterator Best;
Richard Smith7c2bcc92016-09-07 02:14:33 +00005802 switch (ResolveConstructorOverload(
Richard Smith67ef14f2017-09-26 18:37:55 +00005803 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
Richard Smith7c2bcc92016-09-07 02:14:33 +00005804 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
5805 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
5806 /*SecondStepOfCopyInit=*/true)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005807 case OR_Success:
5808 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005809
Douglas Gregore1314a62009-12-18 05:02:21 +00005810 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005811 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
5812 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
5813 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005814 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005815 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005816 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005817 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00005818 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005819 return CurInit;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005820
Douglas Gregore1314a62009-12-18 05:02:21 +00005821 case OR_Ambiguous:
5822 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005823 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005824 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005825 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallfaf5fb42010-08-26 23:41:50 +00005826 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005827
Douglas Gregore1314a62009-12-18 05:02:21 +00005828 case OR_Deleted:
5829 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005830 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005831 << CurInitExpr->getSourceRange();
Richard Smith852265f2012-03-30 20:53:28 +00005832 S.NoteDeletedFunction(Best->Function);
John McCallfaf5fb42010-08-26 23:41:50 +00005833 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005834 }
5835
Richard Smith7c2bcc92016-09-07 02:14:33 +00005836 bool HadMultipleCandidates = CandidateSet.size() > 1;
5837
Douglas Gregor5ab11652010-04-17 22:01:05 +00005838 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramerf0623432012-08-23 22:51:59 +00005839 SmallVector<Expr*, 8> ConstructorArgs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005840 CurInit.get(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005841
Richard Smith5179eb72016-06-28 19:03:57 +00005842 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
5843 IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005844
5845 if (IsExtraneousCopy) {
5846 // If this is a totally extraneous copy for C++03 reference
5847 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00005848 // expression. We don't generate an (elided) copy operation here
5849 // because doing so would require us to pass down a flag to avoid
5850 // infinite recursion, where each step adds another extraneous,
5851 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005852
Douglas Gregor30b52772010-04-18 07:57:34 +00005853 // Instantiate the default arguments of any extra parameters in
5854 // the selected copy constructor, as if we were going to create a
5855 // proper call to the copy constructor.
5856 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5857 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5858 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005859 diag::err_call_incomplete_argument))
Douglas Gregor30b52772010-04-18 07:57:34 +00005860 break;
5861
5862 // Build the default argument expression; we don't actually care
5863 // if this succeeds or not, because this routine will complain
5864 // if there was a problem.
5865 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5866 }
5867
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005868 return CurInitExpr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005869 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005870
Douglas Gregor5ab11652010-04-17 22:01:05 +00005871 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005872 // constructor call (we might have derived-to-base conversions, or
5873 // the copy constructor may have default arguments).
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005874 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005875 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005876
Richard Smith7c2bcc92016-09-07 02:14:33 +00005877 // C++0x [class.copy]p32:
5878 // When certain criteria are met, an implementation is allowed to
5879 // omit the copy/move construction of a class object, even if the
5880 // copy/move constructor and/or destructor for the object have
5881 // side effects. [...]
5882 // - when a temporary class object that has not been bound to a
5883 // reference (12.2) would be copied/moved to a class object
5884 // with the same cv-unqualified type, the copy/move operation
5885 // can be omitted by constructing the temporary object
5886 // directly into the target of the omitted copy/move
5887 //
5888 // Note that the other three bullets are handled elsewhere. Copy
5889 // elision for return statements and throw expressions are handled as part
5890 // of constructor initialization, while copy elision for exception handlers
5891 // is handled by the run-time.
5892 //
5893 // FIXME: If the function parameter is not the same type as the temporary, we
5894 // should still be able to elide the copy, but we don't have a way to
5895 // represent in the AST how much should be elided in this case.
5896 bool Elidable =
5897 CurInitExpr->isTemporaryObject(S.Context, Class) &&
5898 S.Context.hasSameUnqualifiedType(
5899 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
5900 CurInitExpr->getType());
5901
Douglas Gregord0ace022010-04-25 00:55:24 +00005902 // Actually perform the constructor call.
Richard Smithc2bebe92016-05-11 20:37:46 +00005903 CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor,
5904 Elidable,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005905 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005906 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005907 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005908 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005909 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005910 CXXConstructExpr::CK_Complete,
5911 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005912
Douglas Gregord0ace022010-04-25 00:55:24 +00005913 // If we're supposed to bind temporaries, do so.
5914 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005915 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005916 return CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00005917}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005918
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005919/// Check whether elidable copy construction for binding a reference to
Richard Smithc620f552011-10-19 16:55:56 +00005920/// a temporary would have succeeded if we were building in C++98 mode, for
5921/// -Wc++98-compat.
5922static void CheckCXX98CompatAccessibleCopy(Sema &S,
5923 const InitializedEntity &Entity,
5924 Expr *CurInitExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005925 assert(S.getLangOpts().CPlusPlus11);
Richard Smithc620f552011-10-19 16:55:56 +00005926
5927 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5928 if (!Record)
5929 return;
5930
5931 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005932 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
Richard Smithc620f552011-10-19 16:55:56 +00005933 return;
5934
5935 // Find constructors which would have been considered.
Richard Smith100b24a2014-04-17 01:52:14 +00005936 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smith7c2bcc92016-09-07 02:14:33 +00005937 DeclContext::lookup_result Ctors =
5938 S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
Richard Smithc620f552011-10-19 16:55:56 +00005939
5940 // Perform overload resolution.
5941 OverloadCandidateSet::iterator Best;
Richard Smith7c2bcc92016-09-07 02:14:33 +00005942 OverloadingResult OR = ResolveConstructorOverload(
Richard Smith67ef14f2017-09-26 18:37:55 +00005943 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
Richard Smith7c2bcc92016-09-07 02:14:33 +00005944 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
5945 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
5946 /*SecondStepOfCopyInit=*/true);
Richard Smithc620f552011-10-19 16:55:56 +00005947
5948 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5949 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5950 << CurInitExpr->getSourceRange();
5951
5952 switch (OR) {
5953 case OR_Success:
5954 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
Richard Smith5179eb72016-06-28 19:03:57 +00005955 Best->FoundDecl, Entity, Diag);
Richard Smithc620f552011-10-19 16:55:56 +00005956 // FIXME: Check default arguments as far as that's possible.
5957 break;
5958
5959 case OR_No_Viable_Function:
5960 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005961 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005962 break;
5963
5964 case OR_Ambiguous:
5965 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005966 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005967 break;
5968
5969 case OR_Deleted:
5970 S.Diag(Loc, Diag);
Richard Smith852265f2012-03-30 20:53:28 +00005971 S.NoteDeletedFunction(Best->Function);
Richard Smithc620f552011-10-19 16:55:56 +00005972 break;
5973 }
5974}
5975
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005976void InitializationSequence::PrintInitLocationNote(Sema &S,
5977 const InitializedEntity &Entity) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005978 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005979 if (Entity.getDecl()->getLocation().isInvalid())
5980 return;
5981
5982 if (Entity.getDecl()->getDeclName())
5983 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5984 << Entity.getDecl()->getDeclName();
5985 else
5986 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5987 }
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005988 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5989 Entity.getMethodDecl())
5990 S.Diag(Entity.getMethodDecl()->getLocation(),
5991 diag::note_method_return_type_change)
5992 << Entity.getMethodDecl()->getDeclName();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005993}
5994
Jordan Rose6c0505e2013-05-06 16:48:12 +00005995/// Returns true if the parameters describe a constructor initialization of
5996/// an explicit temporary object, e.g. "Point(x, y)".
5997static bool isExplicitTemporary(const InitializedEntity &Entity,
5998 const InitializationKind &Kind,
5999 unsigned NumArgs) {
6000 switch (Entity.getKind()) {
6001 case InitializedEntity::EK_Temporary:
6002 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00006003 case InitializedEntity::EK_RelatedResult:
Jordan Rose6c0505e2013-05-06 16:48:12 +00006004 break;
6005 default:
6006 return false;
6007 }
6008
6009 switch (Kind.getKind()) {
6010 case InitializationKind::IK_DirectList:
6011 return true;
6012 // FIXME: Hack to work around cast weirdness.
6013 case InitializationKind::IK_Direct:
6014 case InitializationKind::IK_Value:
6015 return NumArgs != 1;
6016 default:
6017 return false;
6018 }
6019}
6020
Sebastian Redled2e5322011-12-22 14:44:04 +00006021static ExprResult
6022PerformConstructorInitialization(Sema &S,
6023 const InitializedEntity &Entity,
6024 const InitializationKind &Kind,
6025 MultiExprArg Args,
6026 const InitializationSequence::Step& Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006027 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006028 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006029 bool IsStdInitListInitialization,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006030 SourceLocation LBraceLoc,
6031 SourceLocation RBraceLoc) {
Sebastian Redled2e5322011-12-22 14:44:04 +00006032 unsigned NumArgs = Args.size();
6033 CXXConstructorDecl *Constructor
6034 = cast<CXXConstructorDecl>(Step.Function.Function);
6035 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
6036
6037 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00006038 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redled2e5322011-12-22 14:44:04 +00006039 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
6040 ? Kind.getEqualLoc()
6041 : Kind.getLocation();
6042
6043 if (Kind.getKind() == InitializationKind::IK_Default) {
6044 // Force even a trivial, implicit default constructor to be
6045 // semantically checked. We do this explicitly because we don't build
6046 // the definition for completely trivial constructors.
Matt Beaumont-Gay47ff1222012-02-24 08:37:56 +00006047 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redled2e5322011-12-22 14:44:04 +00006048 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregorf704ade2012-02-24 07:48:37 +00006049 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redled2e5322011-12-22 14:44:04 +00006050 S.DefineImplicitDefaultConstructor(Loc, Constructor);
6051 }
6052
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006053 ExprResult CurInit((Expr *)nullptr);
Sebastian Redled2e5322011-12-22 14:44:04 +00006054
Douglas Gregor6073dca2012-02-24 23:56:31 +00006055 // C++ [over.match.copy]p1:
6056 // - When initializing a temporary to be bound to the first parameter
6057 // of a constructor that takes a reference to possibly cv-qualified
6058 // T as its first argument, called with a single argument in the
6059 // context of direct-initialization, explicit conversion functions
6060 // are also considered.
Richard Smith7c2bcc92016-09-07 02:14:33 +00006061 bool AllowExplicitConv =
6062 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
6063 hasCopyOrMoveCtorParam(S.Context,
6064 getConstructorInfo(Step.Function.FoundDecl));
Douglas Gregor6073dca2012-02-24 23:56:31 +00006065
Sebastian Redled2e5322011-12-22 14:44:04 +00006066 // Determine the arguments required to actually perform the constructor
6067 // call.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006068 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregor6073dca2012-02-24 23:56:31 +00006069 Loc, ConstructorArgs,
Richard Smith6b216962013-02-05 05:52:24 +00006070 AllowExplicitConv,
6071 IsListInitialization))
Sebastian Redled2e5322011-12-22 14:44:04 +00006072 return ExprError();
6073
6074
Jordan Rose6c0505e2013-05-06 16:48:12 +00006075 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redled2e5322011-12-22 14:44:04 +00006076 // An explicitly-constructed temporary, e.g., X(1, 2).
Richard Smith22262ab2013-05-04 06:44:46 +00006077 if (S.DiagnoseUseOfDecl(Constructor, Loc))
6078 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00006079
6080 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6081 if (!TSInfo)
6082 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Vedant Kumara14a1f92018-01-17 18:53:51 +00006083 SourceRange ParenOrBraceRange = Kind.getParenOrBraceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006084
Richard Smith5179eb72016-06-28 19:03:57 +00006085 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
Richard Smith80a47022016-06-29 01:10:27 +00006086 Step.Function.FoundDecl.getDecl())) {
Richard Smith5179eb72016-06-28 19:03:57 +00006087 Constructor = S.findInheritingConstructor(Loc, Constructor, Shadow);
Richard Smith80a47022016-06-29 01:10:27 +00006088 if (S.DiagnoseUseOfDecl(Constructor, Loc))
6089 return ExprError();
6090 }
Richard Smith5179eb72016-06-28 19:03:57 +00006091 S.MarkFunctionReferenced(Loc, Constructor);
6092
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006093 CurInit = new (S.Context) CXXTemporaryObjectExpr(
Richard Smith60437622017-02-09 19:17:44 +00006094 S.Context, Constructor,
6095 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
Richard Smithc2bebe92016-05-11 20:37:46 +00006096 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
6097 IsListInitialization, IsStdInitListInitialization,
6098 ConstructorInitRequiresZeroInit);
Sebastian Redled2e5322011-12-22 14:44:04 +00006099 } else {
6100 CXXConstructExpr::ConstructionKind ConstructKind =
6101 CXXConstructExpr::CK_Complete;
6102
6103 if (Entity.getKind() == InitializedEntity::EK_Base) {
6104 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
6105 CXXConstructExpr::CK_VirtualBase :
6106 CXXConstructExpr::CK_NonVirtualBase;
6107 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
6108 ConstructKind = CXXConstructExpr::CK_Delegating;
6109 }
6110
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006111 // Only get the parenthesis or brace range if it is a list initialization or
6112 // direct construction.
6113 SourceRange ParenOrBraceRange;
6114 if (IsListInitialization)
6115 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
6116 else if (Kind.getKind() == InitializationKind::IK_Direct)
Vedant Kumara14a1f92018-01-17 18:53:51 +00006117 ParenOrBraceRange = Kind.getParenOrBraceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006118
6119 // If the entity allows NRVO, mark the construction as elidable
6120 // unconditionally.
6121 if (Entity.allowsNRVO())
Richard Smith410306b2016-12-12 02:53:20 +00006122 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
Richard Smithc2bebe92016-05-11 20:37:46 +00006123 Step.Function.FoundDecl,
Sebastian Redled2e5322011-12-22 14:44:04 +00006124 Constructor, /*Elidable=*/true,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006125 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00006126 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006127 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006128 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00006129 ConstructorInitRequiresZeroInit,
6130 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006131 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00006132 else
Richard Smith410306b2016-12-12 02:53:20 +00006133 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
Richard Smithc2bebe92016-05-11 20:37:46 +00006134 Step.Function.FoundDecl,
Sebastian Redled2e5322011-12-22 14:44:04 +00006135 Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006136 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00006137 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006138 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006139 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00006140 ConstructorInitRequiresZeroInit,
6141 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006142 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00006143 }
6144 if (CurInit.isInvalid())
6145 return ExprError();
6146
6147 // Only check access if all of that succeeded.
Richard Smith5179eb72016-06-28 19:03:57 +00006148 S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
Richard Smith22262ab2013-05-04 06:44:46 +00006149 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
6150 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00006151
6152 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006153 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redled2e5322011-12-22 14:44:04 +00006154
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006155 return CurInit;
Sebastian Redled2e5322011-12-22 14:44:04 +00006156}
6157
Richard Smitheb3cad52012-06-04 22:27:30 +00006158/// Determine whether the specified InitializedEntity definitely has a lifetime
6159/// longer than the current full-expression. Conservatively returns false if
6160/// it's unclear.
6161static bool
6162InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
6163 const InitializedEntity *Top = &Entity;
6164 while (Top->getParent())
6165 Top = Top->getParent();
6166
6167 switch (Top->getKind()) {
6168 case InitializedEntity::EK_Variable:
6169 case InitializedEntity::EK_Result:
6170 case InitializedEntity::EK_Exception:
6171 case InitializedEntity::EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00006172 case InitializedEntity::EK_Binding:
Richard Smitheb3cad52012-06-04 22:27:30 +00006173 case InitializedEntity::EK_New:
6174 case InitializedEntity::EK_Base:
6175 case InitializedEntity::EK_Delegating:
6176 return true;
6177
6178 case InitializedEntity::EK_ArrayElement:
6179 case InitializedEntity::EK_VectorElement:
6180 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00006181 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Richard Smitheb3cad52012-06-04 22:27:30 +00006182 case InitializedEntity::EK_ComplexElement:
6183 // Could not determine what the full initialization is. Assume it might not
6184 // outlive the full-expression.
6185 return false;
6186
6187 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006188 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smitheb3cad52012-06-04 22:27:30 +00006189 case InitializedEntity::EK_Temporary:
6190 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00006191 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00006192 case InitializedEntity::EK_RelatedResult:
Richard Smitheb3cad52012-06-04 22:27:30 +00006193 // The entity being initialized might not outlive the full-expression.
6194 return false;
6195 }
6196
6197 llvm_unreachable("unknown entity kind");
6198}
6199
Richard Smithe6c01442013-06-05 00:46:14 +00006200/// Determine the declaration which an initialized entity ultimately refers to,
6201/// for the purpose of lifetime-extending a temporary bound to a reference in
6202/// the initialization of \p Entity.
Florian Hahn0aa117d2018-07-17 09:23:31 +00006203static const InitializedEntity *getEntityForTemporaryLifetimeExtension(
David Majnemerdaff3702014-05-01 17:50:17 +00006204 const InitializedEntity *Entity,
Florian Hahn0aa117d2018-07-17 09:23:31 +00006205 const InitializedEntity *FallbackDecl = nullptr) {
Richard Smithe6c01442013-06-05 00:46:14 +00006206 // C++11 [class.temporary]p5:
David Majnemerdaff3702014-05-01 17:50:17 +00006207 switch (Entity->getKind()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006208 case InitializedEntity::EK_Variable:
6209 // The temporary [...] persists for the lifetime of the reference
Florian Hahn0aa117d2018-07-17 09:23:31 +00006210 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00006211
6212 case InitializedEntity::EK_Member:
6213 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00006214 if (Entity->getParent())
6215 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
6216 Entity);
Richard Smithe6c01442013-06-05 00:46:14 +00006217
6218 // except:
Florian Hahn0aa117d2018-07-17 09:23:31 +00006219 // -- A temporary bound to a reference member in a constructor's
6220 // ctor-initializer persists until the constructor exits.
6221 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00006222
Richard Smith7873de02016-08-11 22:25:46 +00006223 case InitializedEntity::EK_Binding:
Richard Smith3997b1b2016-08-12 01:55:21 +00006224 // Per [dcl.decomp]p3, the binding is treated as a variable of reference
6225 // type.
Florian Hahn0aa117d2018-07-17 09:23:31 +00006226 return Entity;
Richard Smith7873de02016-08-11 22:25:46 +00006227
Richard Smithe6c01442013-06-05 00:46:14 +00006228 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006229 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithe6c01442013-06-05 00:46:14 +00006230 // -- A temporary bound to a reference parameter in a function call
6231 // persists until the completion of the full-expression containing
6232 // the call.
6233 case InitializedEntity::EK_Result:
6234 // -- The lifetime of a temporary bound to the returned value in a
6235 // function return statement is not extended; the temporary is
6236 // destroyed at the end of the full-expression in the return statement.
6237 case InitializedEntity::EK_New:
6238 // -- A temporary bound to a reference in a new-initializer persists
6239 // until the completion of the full-expression containing the
6240 // new-initializer.
Florian Hahn0aa117d2018-07-17 09:23:31 +00006241 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00006242
6243 case InitializedEntity::EK_Temporary:
6244 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00006245 case InitializedEntity::EK_RelatedResult:
Richard Smithe6c01442013-06-05 00:46:14 +00006246 // We don't yet know the storage duration of the surrounding temporary.
6247 // Assume it's got full-expression duration for now, it will patch up our
6248 // storage duration if that's not correct.
Florian Hahn0aa117d2018-07-17 09:23:31 +00006249 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00006250
6251 case InitializedEntity::EK_ArrayElement:
6252 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00006253 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
Florian Hahn0aa117d2018-07-17 09:23:31 +00006254 FallbackDecl);
Richard Smithe6c01442013-06-05 00:46:14 +00006255
6256 case InitializedEntity::EK_Base:
Richard Smith872307e2016-03-08 22:17:41 +00006257 // For subobjects, we look at the complete object.
6258 if (Entity->getParent())
6259 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
Florian Hahn0aa117d2018-07-17 09:23:31 +00006260 Entity);
6261 LLVM_FALLTHROUGH;
Richard Smithe6c01442013-06-05 00:46:14 +00006262 case InitializedEntity::EK_Delegating:
6263 // We can reach this case for aggregate initialization in a constructor:
6264 // struct A { int &&r; };
6265 // struct B : A { B() : A{0} {} };
Florian Hahn0aa117d2018-07-17 09:23:31 +00006266 // In this case, use the innermost field decl as the context.
6267 return FallbackDecl;
Richard Smithe6c01442013-06-05 00:46:14 +00006268
6269 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00006270 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Richard Smithe6c01442013-06-05 00:46:14 +00006271 case InitializedEntity::EK_LambdaCapture:
6272 case InitializedEntity::EK_Exception:
6273 case InitializedEntity::EK_VectorElement:
6274 case InitializedEntity::EK_ComplexElement:
Florian Hahn0aa117d2018-07-17 09:23:31 +00006275 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00006276 }
Benjamin Kramercabc8822013-06-05 15:37:50 +00006277 llvm_unreachable("unknown entity kind");
Richard Smithe6c01442013-06-05 00:46:14 +00006278}
6279
Florian Hahn0aa117d2018-07-17 09:23:31 +00006280static void performLifetimeExtension(Expr *Init,
6281 const InitializedEntity *ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00006282
Florian Hahn0aa117d2018-07-17 09:23:31 +00006283/// Update a glvalue expression that is used as the initializer of a reference
6284/// to note that its lifetime is extended.
6285/// \return \c true if any temporary had its lifetime extended.
6286static bool
6287performReferenceExtension(Expr *Init,
6288 const InitializedEntity *ExtendingEntity) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006289 // Walk past any constructs which we can lifetime-extend across.
6290 Expr *Old;
6291 do {
6292 Old = Init;
6293
Richard Smithdbc82492015-01-10 01:28:13 +00006294 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Florian Hahn0aa117d2018-07-17 09:23:31 +00006295 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
6296 // This is just redundant braces around an initializer. Step over it.
Richard Smithdbc82492015-01-10 01:28:13 +00006297 Init = ILE->getInit(0);
Florian Hahn0aa117d2018-07-17 09:23:31 +00006298 }
Richard Smithdbc82492015-01-10 01:28:13 +00006299 }
6300
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006301 // Step over any subobject adjustments; we may have a materialized
6302 // temporary inside them.
Richard Smith4baaa5a2016-12-03 01:14:32 +00006303 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006304
6305 // Per current approach for DR1376, look through casts to reference type
6306 // when performing lifetime extension.
6307 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
6308 if (CE->getSubExpr()->isGLValue())
6309 Init = CE->getSubExpr();
6310
Richard Smithb3189a12016-12-05 07:49:14 +00006311 // Per the current approach for DR1299, look through array element access
6312 // when performing lifetime extension.
6313 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init))
6314 Init = ASE->getBase();
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006315 } while (Init != Old);
6316
Florian Hahn0aa117d2018-07-17 09:23:31 +00006317 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
6318 // Update the storage duration of the materialized temporary.
6319 // FIXME: Rebuild the expression instead of mutating it.
6320 ME->setExtendingDecl(ExtendingEntity->getDecl(),
6321 ExtendingEntity->allocateManglingNumber());
6322 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity);
6323 return true;
Richard Smithe6c01442013-06-05 00:46:14 +00006324 }
Florian Hahn0aa117d2018-07-17 09:23:31 +00006325
6326 return false;
Richard Smithe6c01442013-06-05 00:46:14 +00006327}
6328
Florian Hahn0aa117d2018-07-17 09:23:31 +00006329/// Update a prvalue expression that is going to be materialized as a
6330/// lifetime-extended temporary.
6331static void performLifetimeExtension(Expr *Init,
6332 const InitializedEntity *ExtendingEntity) {
Richard Smithe6c01442013-06-05 00:46:14 +00006333 // Dig out the expression which constructs the extended temporary.
Richard Smith4baaa5a2016-12-03 01:14:32 +00006334 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
Richard Smithe6c01442013-06-05 00:46:14 +00006335
Richard Smith736a9472013-06-12 20:42:33 +00006336 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
6337 Init = BTE->getSubExpr();
6338
Florian Hahn0aa117d2018-07-17 09:23:31 +00006339 if (CXXStdInitializerListExpr *ILE =
6340 dyn_cast<CXXStdInitializerListExpr>(Init)) {
6341 performReferenceExtension(ILE->getSubExpr(), ExtendingEntity);
6342 return;
6343 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00006344
Richard Smithe6c01442013-06-05 00:46:14 +00006345 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00006346 if (ILE->getType()->isArrayType()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006347 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
Florian Hahn0aa117d2018-07-17 09:23:31 +00006348 performLifetimeExtension(ILE->getInit(I), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00006349 return;
6350 }
6351
Richard Smithcc1b96d2013-06-12 22:31:48 +00006352 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006353 assert(RD->isAggregate() && "aggregate init on non-aggregate");
6354
6355 // If we lifetime-extend a braced initializer which is initializing an
6356 // aggregate, and that aggregate contains reference members which are
6357 // bound to temporaries, those temporaries are also lifetime-extended.
6358 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
6359 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
Florian Hahn0aa117d2018-07-17 09:23:31 +00006360 performReferenceExtension(ILE->getInit(0), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00006361 else {
6362 unsigned Index = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006363 for (const auto *I : RD->fields()) {
Richard Smith0bca59d2013-07-01 06:08:20 +00006364 if (Index >= ILE->getNumInits())
6365 break;
Richard Smithe6c01442013-06-05 00:46:14 +00006366 if (I->isUnnamedBitfield())
6367 continue;
Richard Smith8d7f11d2013-06-27 22:54:33 +00006368 Expr *SubInit = ILE->getInit(Index);
Richard Smithe6c01442013-06-05 00:46:14 +00006369 if (I->getType()->isReferenceType())
Florian Hahn0aa117d2018-07-17 09:23:31 +00006370 performReferenceExtension(SubInit, ExtendingEntity);
6371 else if (isa<InitListExpr>(SubInit) ||
6372 isa<CXXStdInitializerListExpr>(SubInit))
6373 // This may be either aggregate-initialization of a member or
6374 // initialization of a std::initializer_list object. Either way,
Richard Smithe6c01442013-06-05 00:46:14 +00006375 // we should recursively lifetime-extend that initializer.
Florian Hahn0aa117d2018-07-17 09:23:31 +00006376 performLifetimeExtension(SubInit, ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00006377 ++Index;
6378 }
6379 }
6380 }
6381 }
6382}
6383
Florian Hahn0aa117d2018-07-17 09:23:31 +00006384static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
6385 const Expr *Init, bool IsInitializerList,
6386 const ValueDecl *ExtendingDecl) {
6387 // Warn if a field lifetime-extends a temporary.
6388 if (isa<FieldDecl>(ExtendingDecl)) {
6389 if (IsInitializerList) {
6390 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
6391 << /*at end of constructor*/true;
6392 return;
6393 }
6394
6395 bool IsSubobjectMember = false;
6396 for (const InitializedEntity *Ent = Entity.getParent(); Ent;
6397 Ent = Ent->getParent()) {
6398 if (Ent->getKind() != InitializedEntity::EK_Base) {
6399 IsSubobjectMember = true;
6400 break;
6401 }
6402 }
6403 S.Diag(Init->getExprLoc(),
6404 diag::warn_bind_ref_member_to_temporary)
6405 << ExtendingDecl << Init->getSourceRange()
6406 << IsSubobjectMember << IsInitializerList;
6407 if (IsSubobjectMember)
6408 S.Diag(ExtendingDecl->getLocation(),
6409 diag::note_ref_subobject_of_member_declared_here);
6410 else
6411 S.Diag(ExtendingDecl->getLocation(),
6412 diag::note_ref_or_ptr_member_declared_here)
6413 << /*is pointer*/false;
Richard Smith0a9969b2018-07-17 00:11:41 +00006414 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00006415}
6416
Richard Smithaaa0ec42013-09-21 21:19:19 +00006417static void DiagnoseNarrowingInInitList(Sema &S,
6418 const ImplicitConversionSequence &ICS,
6419 QualType PreNarrowingType,
6420 QualType EntityType,
6421 const Expr *PostInit);
6422
Richard Trieuac3eca52015-04-29 01:52:17 +00006423/// Provide warnings when std::move is used on construction.
6424static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
6425 bool IsReturnStmt) {
6426 if (!InitExpr)
6427 return;
6428
Richard Smith51ec0cf2017-02-21 01:17:38 +00006429 if (S.inTemplateInstantiation())
Richard Trieu6093d142015-07-29 17:03:34 +00006430 return;
6431
Richard Trieuac3eca52015-04-29 01:52:17 +00006432 QualType DestType = InitExpr->getType();
6433 if (!DestType->isRecordType())
6434 return;
6435
6436 unsigned DiagID = 0;
6437 if (IsReturnStmt) {
6438 const CXXConstructExpr *CCE =
6439 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
6440 if (!CCE || CCE->getNumArgs() != 1)
6441 return;
6442
6443 if (!CCE->getConstructor()->isCopyOrMoveConstructor())
6444 return;
6445
6446 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
Richard Trieuac3eca52015-04-29 01:52:17 +00006447 }
6448
6449 // Find the std::move call and get the argument.
6450 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
Nico Weber192184c2018-06-20 15:57:38 +00006451 if (!CE || !CE->isCallToStdMove())
Richard Trieuac3eca52015-04-29 01:52:17 +00006452 return;
6453
6454 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
6455
6456 if (IsReturnStmt) {
6457 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
6458 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
6459 return;
6460
6461 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
6462 if (!VD || !VD->hasLocalStorage())
6463 return;
6464
Alex Lorenzbbe51d82017-11-07 21:40:11 +00006465 // __block variables are not moved implicitly.
6466 if (VD->hasAttr<BlocksAttr>())
6467 return;
6468
Richard Trieu8d4006a2015-07-28 19:06:16 +00006469 QualType SourceType = VD->getType();
6470 if (!SourceType->isRecordType())
Richard Trieu1d4911bc2015-05-18 19:54:08 +00006471 return;
6472
Richard Trieu8d4006a2015-07-28 19:06:16 +00006473 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
Richard Trieu1993dc82015-07-29 23:47:19 +00006474 return;
Richard Trieu8d4006a2015-07-28 19:06:16 +00006475 }
6476
Davide Italiano7842c3f2015-07-18 01:15:19 +00006477 // If we're returning a function parameter, copy elision
6478 // is not possible.
6479 if (isa<ParmVarDecl>(VD))
6480 DiagID = diag::warn_redundant_move_on_return;
Richard Trieu1993dc82015-07-29 23:47:19 +00006481 else
6482 DiagID = diag::warn_pessimizing_move_on_return;
Richard Trieuac3eca52015-04-29 01:52:17 +00006483 } else {
6484 DiagID = diag::warn_pessimizing_move_on_initialization;
6485 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
6486 if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType())
6487 return;
6488 }
6489
6490 S.Diag(CE->getLocStart(), DiagID);
6491
6492 // Get all the locations for a fix-it. Don't emit the fix-it if any location
6493 // is within a macro.
6494 SourceLocation CallBegin = CE->getCallee()->getLocStart();
6495 if (CallBegin.isMacroID())
6496 return;
6497 SourceLocation RParen = CE->getRParenLoc();
6498 if (RParen.isMacroID())
6499 return;
6500 SourceLocation LParen;
6501 SourceLocation ArgLoc = Arg->getLocStart();
6502
6503 // Special testing for the argument location. Since the fix-it needs the
6504 // location right before the argument, the argument location can be in a
6505 // macro only if it is at the beginning of the macro.
6506 while (ArgLoc.isMacroID() &&
6507 S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
Richard Smithb5f81712018-04-30 05:25:48 +00006508 ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).getBegin();
Richard Trieuac3eca52015-04-29 01:52:17 +00006509 }
6510
6511 if (LParen.isMacroID())
6512 return;
6513
6514 LParen = ArgLoc.getLocWithOffset(-1);
6515
6516 S.Diag(CE->getLocStart(), diag::note_remove_move)
6517 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
6518 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
6519}
6520
Nick Lewycky2eeddfb2016-05-14 17:44:14 +00006521static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
6522 // Check to see if we are dereferencing a null pointer. If so, this is
6523 // undefined behavior, so warn about it. This only handles the pattern
6524 // "*null", which is a very syntactic check.
6525 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
6526 if (UO->getOpcode() == UO_Deref &&
6527 UO->getSubExpr()->IgnoreParenCasts()->
6528 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
6529 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
6530 S.PDiag(diag::warn_binding_null_to_reference)
6531 << UO->getSubExpr()->getSourceRange());
6532 }
6533}
6534
Tim Shen4a05bb82016-06-21 20:29:17 +00006535MaterializeTemporaryExpr *
6536Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
6537 bool BoundToLvalueReference) {
6538 auto MTE = new (Context)
6539 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
6540
6541 // Order an ExprWithCleanups for lifetime marks.
6542 //
6543 // TODO: It'll be good to have a single place to check the access of the
6544 // destructor and generate ExprWithCleanups for various uses. Currently these
6545 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
6546 // but there may be a chance to merge them.
6547 Cleanup.setExprNeedsCleanups(false);
6548 return MTE;
6549}
6550
Richard Smith4baaa5a2016-12-03 01:14:32 +00006551ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {
6552 // In C++98, we don't want to implicitly create an xvalue.
6553 // FIXME: This means that AST consumers need to deal with "prvalues" that
6554 // denote materialized temporaries. Maybe we should add another ValueKind
6555 // for "xvalue pretending to be a prvalue" for C++98 support.
6556 if (!E->isRValue() || !getLangOpts().CPlusPlus11)
6557 return E;
6558
6559 // C++1z [conv.rval]/1: T shall be a complete type.
Richard Smith81f5ade2016-12-15 02:28:18 +00006560 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
6561 // If so, we should check for a non-abstract class type here too.
Richard Smith4baaa5a2016-12-03 01:14:32 +00006562 QualType T = E->getType();
6563 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
6564 return ExprError();
6565
6566 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
6567}
6568
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006569ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006570InitializationSequence::Perform(Sema &S,
6571 const InitializedEntity &Entity,
6572 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00006573 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00006574 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00006575 if (Failed()) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006576 Diagnose(S, Entity, Kind, Args);
John McCallfaf5fb42010-08-26 23:41:50 +00006577 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006578 }
Nico Weber337d5aa2015-04-17 08:32:38 +00006579 if (!ZeroInitializationFixit.empty()) {
6580 unsigned DiagID = diag::err_default_init_const;
6581 if (Decl *D = Entity.getDecl())
6582 if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>())
6583 DiagID = diag::ext_default_init_const;
6584
6585 // The initialization would have succeeded with this fixit. Since the fixit
6586 // is on the error, we need to build a valid AST in this case, so this isn't
6587 // handled in the Failed() branch above.
6588 QualType DestType = Entity.getType();
6589 S.Diag(Kind.getLocation(), DiagID)
6590 << DestType << (bool)DestType->getAs<RecordType>()
6591 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
6592 ZeroInitializationFixit);
6593 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006594
Sebastian Redld201edf2011-06-05 13:59:11 +00006595 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00006596 // If the declaration is a non-dependent, incomplete array type
6597 // that has an initializer, then its type will be completed once
6598 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00006599 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00006600 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00006601 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00006602 if (const IncompleteArrayType *ArrayT
6603 = S.Context.getAsIncompleteArrayType(DeclType)) {
6604 // FIXME: We don't currently have the ability to accurately
6605 // compute the length of an initializer list without
6606 // performing full type-checking of the initializer list
6607 // (since we have to determine where braces are implicitly
6608 // introduced and such). So, we fall back to making the array
6609 // type a dependently-sized array type with no specified
6610 // bound.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006611 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00006612 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00006613
Douglas Gregor51e77d52009-12-10 17:56:55 +00006614 // Scavange the location of the brackets from the entity, if we can.
Richard Smith7873de02016-08-11 22:25:46 +00006615 if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
Douglas Gregor1b303932009-12-22 15:35:07 +00006616 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
6617 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00006618 if (IncompleteArrayTypeLoc ArrayLoc =
6619 TL.getAs<IncompleteArrayTypeLoc>())
6620 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregor1b303932009-12-22 15:35:07 +00006621 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00006622 }
6623
6624 *ResultType
6625 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006626 /*NumElts=*/nullptr,
Douglas Gregor51e77d52009-12-10 17:56:55 +00006627 ArrayT->getSizeModifier(),
6628 ArrayT->getIndexTypeCVRQualifiers(),
6629 Brackets);
6630 }
6631
6632 }
6633 }
Sebastian Redla9351792012-02-11 23:51:47 +00006634 if (Kind.getKind() == InitializationKind::IK_Direct &&
6635 !Kind.isExplicitCast()) {
6636 // Rebuild the ParenListExpr.
Vedant Kumara14a1f92018-01-17 18:53:51 +00006637 SourceRange ParenRange = Kind.getParenOrBraceRange();
Sebastian Redla9351792012-02-11 23:51:47 +00006638 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006639 Args);
Sebastian Redla9351792012-02-11 23:51:47 +00006640 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00006641 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregorbf138952012-04-04 04:06:51 +00006642 Kind.isExplicitCast() ||
6643 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006644 return ExprResult(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006645 }
6646
Sebastian Redld201edf2011-06-05 13:59:11 +00006647 // No steps means no initialization.
6648 if (Steps.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006649 return ExprResult((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006650
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006651 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006652 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006653 !Entity.isParameterKind()) {
Richard Smith2b349ae2012-04-19 06:58:00 +00006654 // Produce a C++98 compatibility warning if we are initializing a reference
6655 // from an initializer list. For parameters, we produce a better warning
6656 // elsewhere.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006657 Expr *Init = Args[0];
Richard Smith2b349ae2012-04-19 06:58:00 +00006658 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
6659 << Init->getSourceRange();
6660 }
6661
Egor Churaev3bccec52017-04-05 12:47:10 +00006662 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
6663 QualType ETy = Entity.getType();
6664 Qualifiers TyQualifiers = ETy.getQualifiers();
6665 bool HasGlobalAS = TyQualifiers.hasAddressSpace() &&
6666 TyQualifiers.getAddressSpace() == LangAS::opencl_global;
6667
6668 if (S.getLangOpts().OpenCLVersion >= 200 &&
6669 ETy->isAtomicType() && !HasGlobalAS &&
6670 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
6671 S.Diag(Args[0]->getLocStart(), diag::err_opencl_atomic_init) << 1 <<
6672 SourceRange(Entity.getDecl()->getLocStart(), Args[0]->getLocEnd());
6673 return ExprError();
6674 }
6675
Richard Smitheb3cad52012-06-04 22:27:30 +00006676 // Diagnose cases where we initialize a pointer to an array temporary, and the
6677 // pointer obviously outlives the temporary.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006678 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smitheb3cad52012-06-04 22:27:30 +00006679 Entity.getType()->isPointerType() &&
6680 InitializedEntityOutlivesFullExpression(Entity)) {
Richard Smith4baaa5a2016-12-03 01:14:32 +00006681 const Expr *Init = Args[0]->skipRValueSubobjectAdjustments();
6682 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
6683 Init = MTE->GetTemporaryExpr();
Richard Smitheb3cad52012-06-04 22:27:30 +00006684 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
6685 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
6686 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
6687 << Init->getSourceRange();
6688 }
6689
Douglas Gregor1b303932009-12-22 15:35:07 +00006690 QualType DestType = Entity.getType().getNonReferenceType();
6691 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00006692 // the same as Entity.getDecl()->getType() in cases involving type merging,
6693 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00006694 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00006695 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00006696 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006697
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006698 ExprResult CurInit((Expr *)nullptr);
Richard Smith410306b2016-12-12 02:53:20 +00006699 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006700
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006701 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00006702 // grab the only argument out the Args and place it into the "current"
6703 // initializer.
6704 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00006705 case SK_ResolveAddressOfOverloadedFunction:
6706 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006707 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00006708 case SK_CastDerivedToBaseLValue:
6709 case SK_BindReference:
6710 case SK_BindReferenceToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00006711 case SK_FinalCopy:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006712 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00006713 case SK_UserConversion:
6714 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006715 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00006716 case SK_QualificationConversionRValue:
Richard Smith77be48a2014-07-31 06:31:19 +00006717 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00006718 case SK_LValueToRValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00006719 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00006720 case SK_ConversionSequenceNoNarrowing:
Douglas Gregore1314a62009-12-18 05:02:21 +00006721 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00006722 case SK_UnwrapInitList:
6723 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00006724 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00006725 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00006726 case SK_ObjCObjectConversion:
Richard Smith410306b2016-12-12 02:53:20 +00006727 case SK_ArrayLoopIndex:
6728 case SK_ArrayLoopInit:
John McCall31168b02011-06-15 23:02:42 +00006729 case SK_ArrayInit:
Richard Smith378b8c82016-12-14 03:22:16 +00006730 case SK_GNUArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00006731 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00006732 case SK_PassByIndirectCopyRestore:
6733 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00006734 case SK_ProduceObjCObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006735 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00006736 case SK_OCLSamplerInit:
Egor Churaev89831422016-12-23 14:55:49 +00006737 case SK_OCLZeroEvent:
6738 case SK_OCLZeroQueue: {
Douglas Gregore1314a62009-12-18 05:02:21 +00006739 assert(Args.size() == 1);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006740 CurInit = Args[0];
John Wiegley01296292011-04-08 18:41:53 +00006741 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00006742 break;
John McCall34376a62010-12-04 03:47:34 +00006743 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006744
Douglas Gregore1314a62009-12-18 05:02:21 +00006745 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00006746 case SK_ConstructorInitializationFromList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00006747 case SK_StdInitializerListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00006748 case SK_ZeroInitialization:
6749 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006750 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006751
Richard Smithd6a15082017-01-07 00:48:55 +00006752 // Promote from an unevaluated context to an unevaluated list context in
6753 // C++11 list-initialization; we need to instantiate entities usable in
6754 // constant expressions here in order to perform narrowing checks =(
6755 EnterExpressionEvaluationContext Evaluated(
6756 S, EnterExpressionEvaluationContext::InitList,
6757 CurInit.get() && isa<InitListExpr>(CurInit.get()));
6758
Richard Smith81f5ade2016-12-15 02:28:18 +00006759 // C++ [class.abstract]p2:
6760 // no objects of an abstract class can be created except as subobjects
6761 // of a class derived from it
6762 auto checkAbstractType = [&](QualType T) -> bool {
6763 if (Entity.getKind() == InitializedEntity::EK_Base ||
6764 Entity.getKind() == InitializedEntity::EK_Delegating)
6765 return false;
6766 return S.RequireNonAbstractType(Kind.getLocation(), T,
6767 diag::err_allocation_of_abstract_type);
6768 };
6769
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006770 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006771 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006772 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006773 for (step_iterator Step = step_begin(), StepEnd = step_end();
6774 Step != StepEnd; ++Step) {
6775 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006776 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006777
John Wiegley01296292011-04-08 18:41:53 +00006778 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006779
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006780 switch (Step->Kind) {
6781 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006782 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006783 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00006784 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +00006785 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
6786 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006787 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall16df1e52010-03-30 21:47:33 +00006788 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00006789 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006790 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006791
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006792 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006793 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006794 case SK_CastDerivedToBaseLValue: {
6795 // We have a derived-to-base cast that produces either an rvalue or an
6796 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006797
John McCallcf142162010-08-07 06:22:56 +00006798 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00006799
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006800 // Casts to inaccessible base classes are allowed with C-style casts.
6801 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
6802 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00006803 CurInit.get()->getLocStart(),
6804 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00006805 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00006806 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006807
John McCall2536c6d2010-08-25 10:28:54 +00006808 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006809 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006810 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006811 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006812 VK_XValue :
6813 VK_RValue);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006814 CurInit =
6815 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
6816 CurInit.get(), &BasePath, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006817 break;
6818 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006819
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006820 case SK_BindReference:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006821 // Reference binding does not have any corresponding ASTs.
6822
6823 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00006824 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00006825 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00006826
George Burgess IVcfd48d92017-04-13 23:47:08 +00006827 // We don't check for e.g. function pointers here, since address
6828 // availability checks should only occur when the function first decays
6829 // into a pointer or reference.
6830 if (CurInit.get()->getType()->isFunctionProtoType()) {
6831 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
6832 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
6833 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
6834 DRE->getLocStart()))
6835 return ExprError();
6836 }
6837 }
6838 }
6839
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006840 // Even though we didn't materialize a temporary, the binding may still
Florian Hahn0aa117d2018-07-17 09:23:31 +00006841 // extend the lifetime of a temporary. This happens if we bind a reference
6842 // to the result of a cast to reference type.
6843 if (const InitializedEntity *ExtendingEntity =
6844 getEntityForTemporaryLifetimeExtension(&Entity))
6845 if (performReferenceExtension(CurInit.get(), ExtendingEntity))
6846 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6847 /*IsInitializerList=*/false,
6848 ExtendingEntity->getDecl());
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006849
Nick Lewycky2eeddfb2016-05-14 17:44:14 +00006850 CheckForNullPointerDereference(S, CurInit.get());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006851 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00006852
Richard Smithe6c01442013-06-05 00:46:14 +00006853 case SK_BindReferenceToTemporary: {
Jordan Roseb1312a52013-04-11 00:58:58 +00006854 // Make sure the "temporary" is actually an rvalue.
6855 assert(CurInit.get()->isRValue() && "not a temporary");
6856
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006857 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00006858 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00006859 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006860
Douglas Gregorfe314812011-06-21 17:03:29 +00006861 // Materialize the temporary into memory.
Tim Shen4a05bb82016-06-21 20:29:17 +00006862 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
Richard Smithb8c0f552016-12-09 18:49:13 +00006863 Step->Type, CurInit.get(), Entity.getType()->isLValueReferenceType());
David Majnemerdaff3702014-05-01 17:50:17 +00006864
6865 // Maybe lifetime-extend the temporary's subobjects to match the
6866 // entity's lifetime.
Florian Hahn0aa117d2018-07-17 09:23:31 +00006867 if (const InitializedEntity *ExtendingEntity =
6868 getEntityForTemporaryLifetimeExtension(&Entity))
6869 if (performReferenceExtension(MTE, ExtendingEntity))
6870 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6871 /*IsInitializerList=*/false,
6872 ExtendingEntity->getDecl());
Douglas Gregor58df5092011-06-22 16:12:01 +00006873
Brian Kelley762f9282017-03-29 18:16:38 +00006874 // If we're extending this temporary to automatic storage duration -- we
6875 // need to register its cleanup during the full-expression's cleanups.
6876 if (MTE->getStorageDuration() == SD_Automatic &&
6877 MTE->getType().isDestructedType())
Tim Shen4a05bb82016-06-21 20:29:17 +00006878 S.Cleanup.setExprNeedsCleanups(true);
Florian Hahn0aa117d2018-07-17 09:23:31 +00006879
6880 CurInit = MTE;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006881 break;
Richard Smithe6c01442013-06-05 00:46:14 +00006882 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006883
Richard Smithb8c0f552016-12-09 18:49:13 +00006884 case SK_FinalCopy:
Richard Smith81f5ade2016-12-15 02:28:18 +00006885 if (checkAbstractType(Step->Type))
6886 return ExprError();
6887
Richard Smithb8c0f552016-12-09 18:49:13 +00006888 // If the overall initialization is initializing a temporary, we already
6889 // bound our argument if it was necessary to do so. If not (if we're
6890 // ultimately initializing a non-temporary), our argument needs to be
6891 // bound since it's initializing a function parameter.
6892 // FIXME: This is a mess. Rationalize temporary destruction.
6893 if (!shouldBindAsTemporary(Entity))
6894 CurInit = S.MaybeBindToTemporary(CurInit.get());
6895 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
6896 /*IsExtraneousCopy=*/false);
6897 break;
6898
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006899 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006900 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006901 /*IsExtraneousCopy=*/true);
6902 break;
6903
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006904 case SK_UserConversion: {
6905 // We have a user-defined conversion that invokes either a constructor
6906 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00006907 CastKind CastKind;
John McCalla0296f72010-03-19 07:35:19 +00006908 FunctionDecl *Fn = Step->Function.Function;
6909 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006910 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00006911 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00006912 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006913 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00006914 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley01296292011-04-08 18:41:53 +00006915 SourceLocation Loc = CurInit.get()->getLocStart();
John McCall760af172010-02-01 03:16:54 +00006916
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006917 // Determine the arguments required to actually perform the constructor
6918 // call.
John Wiegley01296292011-04-08 18:41:53 +00006919 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006920 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00006921 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006922 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00006923 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006924
Richard Smithb24f0672012-02-11 19:22:50 +00006925 // Build an expression that constructs a temporary.
Richard Smithc2bebe92016-05-11 20:37:46 +00006926 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type,
6927 FoundFn, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006928 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006929 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006930 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006931 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00006932 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00006933 CXXConstructExpr::CK_Complete,
6934 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006935 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006936 return ExprError();
John McCall760af172010-02-01 03:16:54 +00006937
Richard Smith5179eb72016-06-28 19:03:57 +00006938 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
6939 Entity);
Richard Smith22262ab2013-05-04 06:44:46 +00006940 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6941 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006942
John McCalle3027922010-08-25 11:45:40 +00006943 CastKind = CK_ConstructorConversion;
Douglas Gregor95562572010-04-24 23:45:46 +00006944 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006945 } else {
6946 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00006947 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Craig Topperc3ec1492014-05-26 06:22:03 +00006948 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
John McCalla0296f72010-03-19 07:35:19 +00006949 FoundFn);
Richard Smith22262ab2013-05-04 06:44:46 +00006950 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6951 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006952
6953 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006954 // derived-to-base conversion? I believe the answer is "no", because
6955 // we don't want to turn off access control here for c-style casts.
Richard Smithb8c0f552016-12-09 18:49:13 +00006956 CurInit = S.PerformObjectArgumentInitialization(CurInit.get(),
6957 /*Qualifier=*/nullptr,
6958 FoundFn, Conversion);
6959 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006960 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006961
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006962 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006963 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
6964 HadMultipleCandidates);
Richard Smithb8c0f552016-12-09 18:49:13 +00006965 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006966 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006967
John McCalle3027922010-08-25 11:45:40 +00006968 CastKind = CK_UserDefinedConversion;
Alp Toker314cc812014-01-25 16:55:45 +00006969 CreatedObject = Conversion->getReturnType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006970 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006971
Richard Smith81f5ade2016-12-15 02:28:18 +00006972 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
6973 return ExprError();
6974
Richard Smithb8c0f552016-12-09 18:49:13 +00006975 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
6976 CastKind, CurInit.get(), nullptr,
6977 CurInit.get()->getValueKind());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00006978
Richard Smithb8c0f552016-12-09 18:49:13 +00006979 if (shouldBindAsTemporary(Entity))
6980 // The overall entity is temporary, so this expression should be
6981 // destroyed at the end of its full-expression.
6982 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
6983 else if (CreatedObject && shouldDestroyEntity(Entity)) {
6984 // The object outlasts the full-expression, but we need to prepare for
6985 // a destructor being run on it.
6986 // FIXME: It makes no sense to do this here. This should happen
6987 // regardless of how we initialized the entity.
John Wiegley01296292011-04-08 18:41:53 +00006988 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00006989 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006990 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00006991 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00006992 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00006993 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00006994 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith22262ab2013-05-04 06:44:46 +00006995 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
6996 return ExprError();
Douglas Gregor95562572010-04-24 23:45:46 +00006997 }
6998 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006999 break;
7000 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007001
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007002 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007003 case SK_QualificationConversionXValue:
7004 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007005 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00007006 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007007 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00007008 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007009 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00007010 VK_XValue :
7011 VK_RValue);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007012 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007013 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007014 }
7015
Richard Smith77be48a2014-07-31 06:31:19 +00007016 case SK_AtomicConversion: {
7017 assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
7018 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7019 CK_NonAtomicToAtomic, VK_RValue);
7020 break;
7021 }
7022
Jordan Roseb1312a52013-04-11 00:58:58 +00007023 case SK_LValueToRValue: {
7024 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007025 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
7026 CK_LValueToRValue, CurInit.get(),
7027 /*BasePath=*/nullptr, VK_RValue);
Jordan Roseb1312a52013-04-11 00:58:58 +00007028 break;
7029 }
7030
Richard Smithaaa0ec42013-09-21 21:19:19 +00007031 case SK_ConversionSequence:
7032 case SK_ConversionSequenceNoNarrowing: {
7033 Sema::CheckedConversionKind CCK
John McCall31168b02011-06-15 23:02:42 +00007034 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
7035 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00007036 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00007037 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00007038 ExprResult CurInitExprRes =
7039 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00007040 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00007041 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007042 return ExprError();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00007043
7044 S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get());
7045
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007046 CurInit = CurInitExprRes;
Richard Smithaaa0ec42013-09-21 21:19:19 +00007047
7048 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
Richard Smith52e624f2016-12-21 21:42:57 +00007049 S.getLangOpts().CPlusPlus)
Richard Smithaaa0ec42013-09-21 21:19:19 +00007050 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
7051 CurInit.get());
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00007052
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007053 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00007054 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007055
Douglas Gregor51e77d52009-12-10 17:56:55 +00007056 case SK_ListInitialization: {
Richard Smith81f5ade2016-12-15 02:28:18 +00007057 if (checkAbstractType(Step->Type))
7058 return ExprError();
7059
John Wiegley01296292011-04-08 18:41:53 +00007060 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smithcc1b96d2013-06-12 22:31:48 +00007061 // If we're not initializing the top-level entity, we need to create an
7062 // InitializeTemporary entity for our target type.
7063 QualType Ty = Step->Type;
7064 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl29526f02011-11-27 16:50:07 +00007065 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smithd712d0d2013-02-02 01:13:06 +00007066 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
7067 InitListChecker PerformInitList(S, InitEntity,
Manman Ren073db022016-03-10 18:53:19 +00007068 InitList, Ty, /*VerifyOnly=*/false,
7069 /*TreatUnavailableAsInvalid=*/false);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007070 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00007071 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00007072
Richard Smithcc1b96d2013-06-12 22:31:48 +00007073 // Hack: We must update *ResultType if available in order to set the
7074 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
7075 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
7076 if (ResultType &&
7077 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00007078 if ((*ResultType)->isRValueReferenceType())
7079 Ty = S.Context.getRValueReferenceType(Ty);
7080 else if ((*ResultType)->isLValueReferenceType())
7081 Ty = S.Context.getLValueReferenceType(Ty,
7082 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
7083 *ResultType = Ty;
7084 }
7085
7086 InitListExpr *StructuredInitList =
7087 PerformInitList.getFullyStructuredList();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007088 CurInit.get();
Richard Smithd712d0d2013-02-02 01:13:06 +00007089 CurInit = shouldBindAsTemporary(InitEntity)
7090 ? S.MaybeBindToTemporary(StructuredInitList)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007091 : StructuredInitList;
Douglas Gregor51e77d52009-12-10 17:56:55 +00007092 break;
7093 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007094
Richard Smith53324112014-07-16 21:33:43 +00007095 case SK_ConstructorInitializationFromList: {
Richard Smith81f5ade2016-12-15 02:28:18 +00007096 if (checkAbstractType(Step->Type))
7097 return ExprError();
7098
Sebastian Redl5a41f682012-02-12 16:37:24 +00007099 // When an initializer list is passed for a parameter of type "reference
7100 // to object", we don't get an EK_Temporary entity, but instead an
7101 // EK_Parameter entity with reference type.
Sebastian Redl99f66162012-02-19 12:27:56 +00007102 // FIXME: This is a hack. What we really should do is create a user
7103 // conversion step for this case, but this makes it considerably more
7104 // complicated. For now, this will do.
Sebastian Redl5a41f682012-02-12 16:37:24 +00007105 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
7106 Entity.getType().getNonReferenceType());
7107 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithd86812d2012-07-05 08:39:21 +00007108 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007109 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith2b349ae2012-04-19 06:58:00 +00007110 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
7111 << InitList->getSourceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00007112 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl5a41f682012-02-12 16:37:24 +00007113 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
7114 Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007115 Kind, Arg, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00007116 ConstructorInitRequiresZeroInit,
Richard Smith53324112014-07-16 21:33:43 +00007117 /*IsListInitialization*/true,
Richard Smithf8adcdc2014-07-17 05:12:35 +00007118 /*IsStdInitListInit*/false,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00007119 InitList->getLBraceLoc(),
7120 InitList->getRBraceLoc());
Sebastian Redled2e5322011-12-22 14:44:04 +00007121 break;
7122 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007123
Sebastian Redl29526f02011-11-27 16:50:07 +00007124 case SK_UnwrapInitList:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007125 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
Sebastian Redl29526f02011-11-27 16:50:07 +00007126 break;
7127
7128 case SK_RewrapInitList: {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007129 Expr *E = CurInit.get();
Sebastian Redl29526f02011-11-27 16:50:07 +00007130 InitListExpr *Syntactic = Step->WrappingSyntacticList;
7131 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramerc215e762012-08-24 11:54:20 +00007132 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl29526f02011-11-27 16:50:07 +00007133 ILE->setSyntacticForm(Syntactic);
7134 ILE->setType(E->getType());
7135 ILE->setValueKind(E->getValueKind());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007136 CurInit = ILE;
Sebastian Redl29526f02011-11-27 16:50:07 +00007137 break;
7138 }
7139
Richard Smith53324112014-07-16 21:33:43 +00007140 case SK_ConstructorInitialization:
Richard Smithf8adcdc2014-07-17 05:12:35 +00007141 case SK_StdInitializerListConstructorCall: {
Richard Smith81f5ade2016-12-15 02:28:18 +00007142 if (checkAbstractType(Step->Type))
7143 return ExprError();
7144
Sebastian Redl99f66162012-02-19 12:27:56 +00007145 // When an initializer list is passed for a parameter of type "reference
7146 // to object", we don't get an EK_Temporary entity, but instead an
7147 // EK_Parameter entity with reference type.
7148 // FIXME: This is a hack. What we really should do is create a user
7149 // conversion step for this case, but this makes it considerably more
7150 // complicated. For now, this will do.
7151 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
7152 Entity.getType().getNonReferenceType());
7153 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf8adcdc2014-07-17 05:12:35 +00007154 bool IsStdInitListInit =
7155 Step->Kind == SK_StdInitializerListConstructorCall;
Richard Smith410306b2016-12-12 02:53:20 +00007156 Expr *Source = CurInit.get();
Vedant Kumara14a1f92018-01-17 18:53:51 +00007157 SourceRange Range = Kind.hasParenOrBraceRange()
7158 ? Kind.getParenOrBraceRange()
7159 : SourceRange();
Richard Smith53324112014-07-16 21:33:43 +00007160 CurInit = PerformConstructorInitialization(
Richard Smith410306b2016-12-12 02:53:20 +00007161 S, UseTemporary ? TempEntity : Entity, Kind,
7162 Source ? MultiExprArg(Source) : Args, *Step,
Richard Smith53324112014-07-16 21:33:43 +00007163 ConstructorInitRequiresZeroInit,
Richard Smith410306b2016-12-12 02:53:20 +00007164 /*IsListInitialization*/ IsStdInitListInit,
7165 /*IsStdInitListInitialization*/ IsStdInitListInit,
Vedant Kumara14a1f92018-01-17 18:53:51 +00007166 /*LBraceLoc*/ Range.getBegin(),
7167 /*RBraceLoc*/ Range.getEnd());
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007168 break;
Sebastian Redl99f66162012-02-19 12:27:56 +00007169 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007170
Douglas Gregor7dc42e52009-12-15 00:01:57 +00007171 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007172 step_iterator NextStep = Step;
7173 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007174 if (NextStep != StepEnd &&
Richard Smithd86812d2012-07-05 08:39:21 +00007175 (NextStep->Kind == SK_ConstructorInitialization ||
Richard Smith53324112014-07-16 21:33:43 +00007176 NextStep->Kind == SK_ConstructorInitializationFromList)) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007177 // The need for zero-initialization is recorded directly into
7178 // the call to the object's constructor within the next step.
7179 ConstructorInitRequiresZeroInit = true;
7180 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007181 S.getLangOpts().CPlusPlus &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007182 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00007183 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7184 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007185 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00007186 Kind.getRange().getBegin());
7187
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007188 CurInit = new (S.Context) CXXScalarValueInitExpr(
Richard Smith60437622017-02-09 19:17:44 +00007189 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007190 Kind.getRange().getEnd());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007191 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007192 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007193 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00007194 break;
7195 }
Douglas Gregore1314a62009-12-18 05:02:21 +00007196
7197 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00007198 QualType SourceType = CurInit.get()->getType();
George Burgess IV5f21c712015-10-12 19:57:04 +00007199 // Save off the initial CurInit in case we need to emit a diagnostic
7200 ExprResult InitialCurInit = CurInit;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007201 ExprResult Result = CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00007202 Sema::AssignConvertType ConvTy =
Fariborz Jahanian25eef192013-07-31 21:40:51 +00007203 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
7204 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley01296292011-04-08 18:41:53 +00007205 if (Result.isInvalid())
7206 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007207 CurInit = Result;
Douglas Gregor96596c92009-12-22 07:24:36 +00007208
7209 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007210 ExprResult CurInitExprRes = CurInit;
Douglas Gregor96596c92009-12-22 07:24:36 +00007211 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00007212 Entity.isParameterKind() &&
John Wiegley01296292011-04-08 18:41:53 +00007213 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00007214 == Sema::Compatible)
7215 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00007216 if (CurInitExprRes.isInvalid())
7217 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007218 CurInit = CurInitExprRes;
Douglas Gregor96596c92009-12-22 07:24:36 +00007219
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007220 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00007221 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
7222 Step->Type, SourceType,
George Burgess IV5f21c712015-10-12 19:57:04 +00007223 InitialCurInit.get(),
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00007224 getAssignmentAction(Entity, true),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007225 &Complained)) {
7226 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00007227 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007228 } else if (Complained)
7229 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00007230 break;
7231 }
Eli Friedman78275202009-12-19 08:11:05 +00007232
7233 case SK_StringInit: {
7234 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00007235 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00007236 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00007237 break;
7238 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007239
7240 case SK_ObjCObjectConversion:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007241 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00007242 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00007243 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007244 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007245
Richard Smith410306b2016-12-12 02:53:20 +00007246 case SK_ArrayLoopIndex: {
7247 Expr *Cur = CurInit.get();
7248 Expr *BaseExpr = new (S.Context)
7249 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
7250 Cur->getValueKind(), Cur->getObjectKind(), Cur);
7251 Expr *IndexExpr =
7252 new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());
7253 CurInit = S.CreateBuiltinArraySubscriptExpr(
7254 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
7255 ArrayLoopCommonExprs.push_back(BaseExpr);
7256 break;
7257 }
7258
7259 case SK_ArrayLoopInit: {
7260 assert(!ArrayLoopCommonExprs.empty() &&
7261 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
7262 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
7263 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
7264 CurInit.get());
7265 break;
7266 }
7267
Richard Smith378b8c82016-12-14 03:22:16 +00007268 case SK_GNUArrayInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00007269 // Okay: we checked everything before creating this step. Note that
7270 // this is a GNU extension.
7271 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00007272 << Step->Type << CurInit.get()->getType()
7273 << CurInit.get()->getSourceRange();
Richard Smith378b8c82016-12-14 03:22:16 +00007274 LLVM_FALLTHROUGH;
7275 case SK_ArrayInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00007276 // If the destination type is an incomplete array type, update the
7277 // type accordingly.
7278 if (ResultType) {
7279 if (const IncompleteArrayType *IncompleteDest
7280 = S.Context.getAsIncompleteArrayType(Step->Type)) {
7281 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00007282 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00007283 *ResultType = S.Context.getConstantArrayType(
7284 IncompleteDest->getElementType(),
7285 ConstantSource->getSize(),
7286 ArrayType::Normal, 0);
7287 }
7288 }
7289 }
John McCall31168b02011-06-15 23:02:42 +00007290 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007291
Richard Smithebeed412012-02-15 22:38:09 +00007292 case SK_ParenthesizedArrayInit:
7293 // Okay: we checked everything before creating this step. Note that
7294 // this is a GNU extension.
7295 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
7296 << CurInit.get()->getSourceRange();
7297 break;
7298
John McCall31168b02011-06-15 23:02:42 +00007299 case SK_PassByIndirectCopyRestore:
7300 case SK_PassByIndirectRestore:
7301 checkIndirectCopyRestoreSource(S, CurInit.get());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007302 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
7303 CurInit.get(), Step->Type,
7304 Step->Kind == SK_PassByIndirectCopyRestore);
John McCall31168b02011-06-15 23:02:42 +00007305 break;
7306
7307 case SK_ProduceObjCObject:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007308 CurInit =
7309 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
7310 CurInit.get(), nullptr, VK_RValue);
Douglas Gregore2f943b2011-02-22 18:29:51 +00007311 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00007312
7313 case SK_StdInitializerList: {
Richard Smithcc1b96d2013-06-12 22:31:48 +00007314 S.Diag(CurInit.get()->getExprLoc(),
7315 diag::warn_cxx98_compat_initializer_list_init)
7316 << CurInit.get()->getSourceRange();
Sebastian Redl249dee52012-03-05 19:35:43 +00007317
Richard Smithcc1b96d2013-06-12 22:31:48 +00007318 // Materialize the temporary into memory.
Tim Shen4a05bb82016-06-21 20:29:17 +00007319 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
7320 CurInit.get()->getType(), CurInit.get(),
7321 /*BoundToLvalueReference=*/false);
David Majnemerdaff3702014-05-01 17:50:17 +00007322
Richard Smith0a9969b2018-07-17 00:11:41 +00007323 // Maybe lifetime-extend the array temporary's subobjects to match the
7324 // entity's lifetime.
Florian Hahn0aa117d2018-07-17 09:23:31 +00007325 if (const InitializedEntity *ExtendingEntity =
7326 getEntityForTemporaryLifetimeExtension(&Entity))
7327 if (performReferenceExtension(MTE, ExtendingEntity))
7328 warnOnLifetimeExtension(S, Entity, CurInit.get(),
7329 /*IsInitializerList=*/true,
7330 ExtendingEntity->getDecl());
7331
7332 // Wrap it in a construction of a std::initializer_list<T>.
7333 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
Richard Smith0a9969b2018-07-17 00:11:41 +00007334
Richard Smithcc1b96d2013-06-12 22:31:48 +00007335 // Bind the result, in case the library has given initializer_list a
7336 // non-trivial destructor.
7337 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007338 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redlc1839b12012-01-17 22:49:42 +00007339 break;
7340 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00007341
Guy Benyei61054192013-02-07 10:55:47 +00007342 case SK_OCLSamplerInit: {
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007343 // Sampler initialzation have 5 cases:
7344 // 1. function argument passing
7345 // 1a. argument is a file-scope variable
7346 // 1b. argument is a function-scope variable
7347 // 1c. argument is one of caller function's parameters
7348 // 2. variable initialization
7349 // 2a. initializing a file-scope variable
7350 // 2b. initializing a function-scope variable
7351 //
7352 // For file-scope variables, since they cannot be initialized by function
7353 // call of __translate_sampler_initializer in LLVM IR, their references
7354 // need to be replaced by a cast from their literal initializers to
7355 // sampler type. Since sampler variables can only be used in function
7356 // calls as arguments, we only need to replace them when handling the
7357 // argument passing.
7358 assert(Step->Type->isSamplerT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00007359 "Sampler initialization on non-sampler type.");
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007360 Expr *Init = CurInit.get();
7361 QualType SourceType = Init->getType();
7362 // Case 1
Fariborz Jahanian131996b2013-07-31 18:21:45 +00007363 if (Entity.isParameterKind()) {
Egor Churaeva8d24512017-04-05 09:02:56 +00007364 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
Guy Benyei61054192013-02-07 10:55:47 +00007365 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
7366 << SourceType;
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007367 break;
7368 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
7369 auto Var = cast<VarDecl>(DRE->getDecl());
7370 // Case 1b and 1c
7371 // No cast from integer to sampler is needed.
7372 if (!Var->hasGlobalStorage()) {
7373 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
7374 CK_LValueToRValue, Init,
7375 /*BasePath=*/nullptr, VK_RValue);
7376 break;
7377 }
7378 // Case 1a
7379 // For function call with a file-scope sampler variable as argument,
7380 // get the integer literal.
7381 // Do not diagnose if the file-scope variable does not have initializer
7382 // since this has already been diagnosed when parsing the variable
7383 // declaration.
7384 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
7385 break;
7386 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
7387 Var->getInit()))->getSubExpr();
7388 SourceType = Init->getType();
7389 }
7390 } else {
7391 // Case 2
7392 // Check initializer is 32 bit integer constant.
7393 // If the initializer is taken from global variable, do not diagnose since
7394 // this has already been done when parsing the variable declaration.
7395 if (!Init->isConstantInitializer(S.Context, false))
7396 break;
7397
7398 if (!SourceType->isIntegerType() ||
7399 32 != S.Context.getIntWidth(SourceType)) {
7400 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
7401 << SourceType;
7402 break;
7403 }
7404
7405 llvm::APSInt Result;
7406 Init->EvaluateAsInt(Result, S.Context);
7407 const uint64_t SamplerValue = Result.getLimitedValue();
7408 // 32-bit value of sampler's initializer is interpreted as
7409 // bit-field with the following structure:
7410 // |unspecified|Filter|Addressing Mode| Normalized Coords|
7411 // |31 6|5 4|3 1| 0|
7412 // This structure corresponds to enum values of sampler properties
7413 // defined in SPIR spec v1.2 and also opencl-c.h
7414 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
7415 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
7416 if (FilterMode != 1 && FilterMode != 2)
7417 S.Diag(Kind.getLocation(),
7418 diag::warn_sampler_initializer_invalid_bits)
7419 << "Filter Mode";
7420 if (AddressingMode > 4)
7421 S.Diag(Kind.getLocation(),
7422 diag::warn_sampler_initializer_invalid_bits)
7423 << "Addressing Mode";
Guy Benyei61054192013-02-07 10:55:47 +00007424 }
7425
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007426 // Cases 1a, 2a and 2b
7427 // Insert cast from integer to sampler.
7428 CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy,
7429 CK_IntToOCLSampler);
Guy Benyei61054192013-02-07 10:55:47 +00007430 break;
7431 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007432 case SK_OCLZeroEvent: {
7433 assert(Step->Type->isEventT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00007434 "Event initialization on non-event type.");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007435
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007436 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007437 CK_ZeroToOCLEvent,
7438 CurInit.get()->getValueKind());
7439 break;
7440 }
Egor Churaev89831422016-12-23 14:55:49 +00007441 case SK_OCLZeroQueue: {
7442 assert(Step->Type->isQueueT() &&
7443 "Event initialization on non queue type.");
7444
7445 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7446 CK_ZeroToOCLQueue,
7447 CurInit.get()->getValueKind());
7448 break;
7449 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007450 }
7451 }
John McCall1f425642010-11-11 03:21:53 +00007452
7453 // Diagnose non-fatal problems with the completed initialization.
7454 if (Entity.getKind() == InitializedEntity::EK_Member &&
7455 cast<FieldDecl>(Entity.getDecl())->isBitField())
7456 S.CheckBitFieldInitialization(Kind.getLocation(),
7457 cast<FieldDecl>(Entity.getDecl()),
7458 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007459
Richard Trieuac3eca52015-04-29 01:52:17 +00007460 // Check for std::move on construction.
7461 if (const Expr *E = CurInit.get()) {
7462 CheckMoveOnConstruction(S, E,
7463 Entity.getKind() == InitializedEntity::EK_Result);
7464 }
7465
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007466 return CurInit;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007467}
7468
Richard Smith593f9932012-12-08 02:01:17 +00007469/// Somewhere within T there is an uninitialized reference subobject.
7470/// Dig it out and diagnose it.
Benjamin Kramer3e350262013-02-15 12:30:38 +00007471static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
7472 QualType T) {
Richard Smith593f9932012-12-08 02:01:17 +00007473 if (T->isReferenceType()) {
7474 S.Diag(Loc, diag::err_reference_without_init)
7475 << T.getNonReferenceType();
7476 return true;
7477 }
7478
7479 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7480 if (!RD || !RD->hasUninitializedReferenceMember())
7481 return false;
7482
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007483 for (const auto *FI : RD->fields()) {
Richard Smith593f9932012-12-08 02:01:17 +00007484 if (FI->isUnnamedBitfield())
7485 continue;
7486
7487 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
7488 S.Diag(Loc, diag::note_value_initialization_here) << RD;
7489 return true;
7490 }
7491 }
7492
Aaron Ballman574705e2014-03-13 15:41:46 +00007493 for (const auto &BI : RD->bases()) {
7494 if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
Richard Smith593f9932012-12-08 02:01:17 +00007495 S.Diag(Loc, diag::note_value_initialization_here) << RD;
7496 return true;
7497 }
7498 }
7499
7500 return false;
7501}
7502
7503
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007504//===----------------------------------------------------------------------===//
7505// Diagnose initialization failures
7506//===----------------------------------------------------------------------===//
John McCall5ec7e7d2013-03-19 07:04:25 +00007507
7508/// Emit notes associated with an initialization that failed due to a
7509/// "simple" conversion failure.
7510static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
7511 Expr *op) {
7512 QualType destType = entity.getType();
7513 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
7514 op->getType()->isObjCObjectPointerType()) {
7515
7516 // Emit a possible note about the conversion failing because the
7517 // operand is a message send with a related result type.
7518 S.EmitRelatedResultTypeNote(op);
7519
7520 // Emit a possible note about a return failing because we're
7521 // expecting a related result type.
7522 if (entity.getKind() == InitializedEntity::EK_Result)
7523 S.EmitRelatedResultTypeNoteForReturn(destType);
7524 }
7525}
7526
Richard Smith0449aaf2013-11-21 23:30:57 +00007527static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
7528 InitListExpr *InitList) {
7529 QualType DestType = Entity.getType();
7530
7531 QualType E;
7532 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
7533 QualType ArrayType = S.Context.getConstantArrayType(
7534 E.withConst(),
7535 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
7536 InitList->getNumInits()),
7537 clang::ArrayType::Normal, 0);
7538 InitializedEntity HiddenArray =
7539 InitializedEntity::InitializeTemporary(ArrayType);
7540 return diagnoseListInit(S, HiddenArray, InitList);
7541 }
7542
Richard Smith8d082d12014-09-04 22:13:39 +00007543 if (DestType->isReferenceType()) {
7544 // A list-initialization failure for a reference means that we tried to
7545 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
7546 // inner initialization failed.
7547 QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
7548 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
7549 SourceLocation Loc = InitList->getLocStart();
7550 if (auto *D = Entity.getDecl())
7551 Loc = D->getLocation();
7552 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
7553 return;
7554 }
7555
Richard Smith0449aaf2013-11-21 23:30:57 +00007556 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
Manman Ren073db022016-03-10 18:53:19 +00007557 /*VerifyOnly=*/false,
7558 /*TreatUnavailableAsInvalid=*/false);
Richard Smith0449aaf2013-11-21 23:30:57 +00007559 assert(DiagnoseInitList.HadError() &&
7560 "Inconsistent init list check result.");
7561}
7562
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007563bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007564 const InitializedEntity &Entity,
7565 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007566 ArrayRef<Expr *> Args) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00007567 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007568 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007569
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007570 // When we want to diagnose only one element of a braced-init-list,
7571 // we need to factor it out.
7572 Expr *OnlyArg;
7573 if (Args.size() == 1) {
7574 auto *List = dyn_cast<InitListExpr>(Args[0]);
7575 if (List && List->getNumInits() == 1)
7576 OnlyArg = List->getInit(0);
7577 else
7578 OnlyArg = Args[0];
7579 }
7580 else
7581 OnlyArg = nullptr;
7582
Douglas Gregor1b303932009-12-22 15:35:07 +00007583 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007584 switch (Failure) {
7585 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007586 // FIXME: Customize for the initialized entity?
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007587 if (Args.empty()) {
Richard Smith593f9932012-12-08 02:01:17 +00007588 // Dig out the reference subobject which is uninitialized and diagnose it.
7589 // If this is value-initialization, this could be nested some way within
7590 // the target type.
7591 assert(Kind.getKind() == InitializationKind::IK_Value ||
7592 DestType->isReferenceType());
7593 bool Diagnosed =
7594 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
7595 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
7596 (void)Diagnosed;
7597 } else // FIXME: diagnostic below could be better!
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007598 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007599 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007600 break;
Richard Smith49a6b6e2017-03-24 01:14:25 +00007601 case FK_ParenthesizedListInitForReference:
7602 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
7603 << 1 << Entity.getType() << Args[0]->getSourceRange();
7604 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007605
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007606 case FK_ArrayNeedsInitList:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00007607 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007608 break;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00007609 case FK_ArrayNeedsInitListOrStringLiteral:
7610 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
7611 break;
7612 case FK_ArrayNeedsInitListOrWideStringLiteral:
7613 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
7614 break;
7615 case FK_NarrowStringIntoWideCharArray:
7616 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
7617 break;
7618 case FK_WideStringIntoCharArray:
7619 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
7620 break;
7621 case FK_IncompatWideStringIntoWideChar:
7622 S.Diag(Kind.getLocation(),
7623 diag::err_array_init_incompat_wide_string_into_wchar);
7624 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00007625 case FK_PlainStringIntoUTF8Char:
7626 S.Diag(Kind.getLocation(),
7627 diag::err_array_init_plain_string_into_char8_t);
7628 S.Diag(Args.front()->getLocStart(),
7629 diag::note_array_init_plain_string_into_char8_t)
7630 << FixItHint::CreateInsertion(Args.front()->getLocStart(), "u8");
7631 break;
7632 case FK_UTF8StringIntoPlainChar:
7633 S.Diag(Kind.getLocation(),
7634 diag::err_array_init_utf8_string_into_char);
7635 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007636 case FK_ArrayTypeMismatch:
7637 case FK_NonConstantArrayInit:
Richard Smith0449aaf2013-11-21 23:30:57 +00007638 S.Diag(Kind.getLocation(),
Douglas Gregore2f943b2011-02-22 18:29:51 +00007639 (Failure == FK_ArrayTypeMismatch
7640 ? diag::err_array_init_different_type
7641 : diag::err_array_init_non_constant_array))
7642 << DestType.getNonReferenceType()
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007643 << OnlyArg->getType()
Douglas Gregore2f943b2011-02-22 18:29:51 +00007644 << Args[0]->getSourceRange();
7645 break;
7646
John McCalla59dc2f2012-01-05 00:13:19 +00007647 case FK_VariableLengthArrayHasInitializer:
7648 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
7649 << Args[0]->getSourceRange();
7650 break;
7651
John McCall16df1e52010-03-30 21:47:33 +00007652 case FK_AddressOfOverloadFailed: {
7653 DeclAccessPair Found;
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007654 S.ResolveAddressOfOverloadedFunction(OnlyArg,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007655 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00007656 true,
7657 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007658 break;
John McCall16df1e52010-03-30 21:47:33 +00007659 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007660
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007661 case FK_AddressOfUnaddressableFunction: {
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007662 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007663 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007664 OnlyArg->getLocStart());
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007665 break;
7666 }
7667
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007668 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00007669 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007670 switch (FailedOverloadResult) {
7671 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00007672 if (Failure == FK_UserConversionOverloadFailed)
7673 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007674 << OnlyArg->getType() << DestType
Douglas Gregore1314a62009-12-18 05:02:21 +00007675 << Args[0]->getSourceRange();
7676 else
7677 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007678 << DestType << OnlyArg->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00007679 << Args[0]->getSourceRange();
7680
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007681 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007682 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007683
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007684 case OR_No_Viable_Function:
Larisse Voufo70bb43a2013-06-27 03:36:30 +00007685 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00007686 DestType.getNonReferenceType(),
7687 diag::err_typecheck_nonviable_condition_incomplete,
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007688 OnlyArg->getType(), Args[0]->getSourceRange()))
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00007689 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00007690 << (Entity.getKind() == InitializedEntity::EK_Result)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007691 << OnlyArg->getType() << Args[0]->getSourceRange()
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00007692 << DestType.getNonReferenceType();
7693
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007694 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007695 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007696
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007697 case OR_Deleted: {
7698 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007699 << OnlyArg->getType() << DestType.getNonReferenceType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007700 << Args[0]->getSourceRange();
7701 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007702 OverloadingResult Ovl
Richard Smith67ef14f2017-09-26 18:37:55 +00007703 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007704 if (Ovl == OR_Deleted) {
Richard Smith852265f2012-03-30 20:53:28 +00007705 S.NoteDeletedFunction(Best->Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007706 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00007707 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007708 }
7709 break;
7710 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007711
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007712 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00007713 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007714 }
7715 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007716
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007717 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00007718 if (isa<InitListExpr>(Args[0])) {
7719 S.Diag(Kind.getLocation(),
7720 diag::err_lvalue_reference_bind_to_initlist)
7721 << DestType.getNonReferenceType().isVolatileQualified()
7722 << DestType.getNonReferenceType()
7723 << Args[0]->getSourceRange();
7724 break;
7725 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007726 LLVM_FALLTHROUGH;
Sebastian Redl29526f02011-11-27 16:50:07 +00007727
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007728 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007729 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007730 Failure == FK_NonConstLValueReferenceBindingToTemporary
7731 ? diag::err_lvalue_reference_bind_to_temporary
7732 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00007733 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007734 << DestType.getNonReferenceType()
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007735 << OnlyArg->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007736 << Args[0]->getSourceRange();
7737 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007738
Richard Smithb8c0f552016-12-09 18:49:13 +00007739 case FK_NonConstLValueReferenceBindingToBitfield: {
7740 // We don't necessarily have an unambiguous source bit-field.
7741 FieldDecl *BitField = Args[0]->getSourceBitField();
7742 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
7743 << DestType.isVolatileQualified()
7744 << (BitField ? BitField->getDeclName() : DeclarationName())
7745 << (BitField != nullptr)
7746 << Args[0]->getSourceRange();
7747 if (BitField)
7748 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
7749 break;
7750 }
7751
7752 case FK_NonConstLValueReferenceBindingToVectorElement:
7753 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
7754 << DestType.isVolatileQualified()
7755 << Args[0]->getSourceRange();
7756 break;
7757
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007758 case FK_RValueReferenceBindingToLValue:
7759 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007760 << DestType.getNonReferenceType() << OnlyArg->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007761 << Args[0]->getSourceRange();
7762 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007763
Richard Trieuf956a492015-05-16 01:27:03 +00007764 case FK_ReferenceInitDropsQualifiers: {
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007765 QualType SourceType = OnlyArg->getType();
Richard Trieuf956a492015-05-16 01:27:03 +00007766 QualType NonRefType = DestType.getNonReferenceType();
7767 Qualifiers DroppedQualifiers =
7768 SourceType.getQualifiers() - NonRefType.getQualifiers();
7769
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007770 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
Richard Trieuf956a492015-05-16 01:27:03 +00007771 << SourceType
7772 << NonRefType
7773 << DroppedQualifiers.getCVRQualifiers()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007774 << Args[0]->getSourceRange();
7775 break;
Richard Trieuf956a492015-05-16 01:27:03 +00007776 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007777
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007778 case FK_ReferenceInitFailed:
7779 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
7780 << DestType.getNonReferenceType()
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007781 << OnlyArg->isLValue()
7782 << OnlyArg->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007783 << Args[0]->getSourceRange();
John McCall5ec7e7d2013-03-19 07:04:25 +00007784 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007785 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007786
Douglas Gregorb491ed32011-02-19 21:32:49 +00007787 case FK_ConversionFailed: {
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007788 QualType FromType = OnlyArg->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00007789 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00007790 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007791 << DestType
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00007792 << OnlyArg->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00007793 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007794 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00007795 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
7796 S.Diag(Kind.getLocation(), PDiag);
John McCall5ec7e7d2013-03-19 07:04:25 +00007797 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00007798 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007799 }
John Wiegley01296292011-04-08 18:41:53 +00007800
7801 case FK_ConversionFromPropertyFailed:
7802 // No-op. This error has already been reported.
7803 break;
7804
Douglas Gregor51e77d52009-12-10 17:56:55 +00007805 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00007806 SourceRange R;
7807
David Majnemerbd385442015-04-10 04:52:06 +00007808 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
Benjamin Kramerc4284e32015-09-23 16:03:53 +00007809 if (InitList && InitList->getNumInits() >= 1) {
David Majnemerbd385442015-04-10 04:52:06 +00007810 R = SourceRange(InitList->getInit(0)->getLocEnd(), InitList->getLocEnd());
Benjamin Kramerc4284e32015-09-23 16:03:53 +00007811 } else {
7812 assert(Args.size() > 1 && "Expected multiple initializers!");
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007813 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Benjamin Kramerc4284e32015-09-23 16:03:53 +00007814 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00007815
Alp Tokerb6cc5922014-05-03 03:45:55 +00007816 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
Douglas Gregor8ec51732010-09-08 21:40:08 +00007817 if (Kind.isCStyleOrFunctionalCast())
7818 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
7819 << R;
7820 else
7821 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
7822 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00007823 break;
7824 }
7825
Richard Smith49a6b6e2017-03-24 01:14:25 +00007826 case FK_ParenthesizedListInitForScalar:
7827 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
7828 << 0 << Entity.getType() << Args[0]->getSourceRange();
7829 break;
7830
Douglas Gregor51e77d52009-12-10 17:56:55 +00007831 case FK_ReferenceBindingToInitList:
7832 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
7833 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
7834 break;
7835
7836 case FK_InitListBadDestinationType:
7837 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
7838 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
7839 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007840
Sebastian Redl6901c0d2011-12-22 18:58:38 +00007841 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007842 case FK_ConstructorOverloadFailed: {
7843 SourceRange ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007844 if (Args.size())
7845 ArgsRange = SourceRange(Args.front()->getLocStart(),
7846 Args.back()->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007847
Sebastian Redl6901c0d2011-12-22 18:58:38 +00007848 if (Failure == FK_ListConstructorOverloadFailed) {
Nico Weber9709ebf2014-07-08 23:54:25 +00007849 assert(Args.size() == 1 &&
7850 "List construction from other than 1 argument.");
Sebastian Redl6901c0d2011-12-22 18:58:38 +00007851 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007852 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00007853 }
7854
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007855 // FIXME: Using "DestType" for the entity we're printing is probably
7856 // bad.
7857 switch (FailedOverloadResult) {
7858 case OR_Ambiguous:
7859 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
7860 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007861 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007862 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007863
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007864 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007865 if (Kind.getKind() == InitializationKind::IK_Default &&
7866 (Entity.getKind() == InitializedEntity::EK_Base ||
7867 Entity.getKind() == InitializedEntity::EK_Member) &&
7868 isa<CXXConstructorDecl>(S.CurContext)) {
7869 // This is implicit default initialization of a member or
7870 // base within a constructor. If no viable function was
Nico Webera6916892016-06-10 18:53:04 +00007871 // found, notify the user that they need to explicitly
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007872 // initialize this base/member.
7873 CXXConstructorDecl *Constructor
7874 = cast<CXXConstructorDecl>(S.CurContext);
Richard Smith5179eb72016-06-28 19:03:57 +00007875 const CXXRecordDecl *InheritedFrom = nullptr;
7876 if (auto Inherited = Constructor->getInheritedConstructor())
7877 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007878 if (Entity.getKind() == InitializedEntity::EK_Base) {
7879 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith5179eb72016-06-28 19:03:57 +00007880 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007881 << S.Context.getTypeDeclType(Constructor->getParent())
7882 << /*base=*/0
Richard Smith5179eb72016-06-28 19:03:57 +00007883 << Entity.getType()
7884 << InheritedFrom;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007885
7886 RecordDecl *BaseDecl
7887 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
7888 ->getDecl();
7889 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
7890 << S.Context.getTagDeclType(BaseDecl);
7891 } else {
7892 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith5179eb72016-06-28 19:03:57 +00007893 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007894 << S.Context.getTypeDeclType(Constructor->getParent())
7895 << /*member=*/1
Richard Smith5179eb72016-06-28 19:03:57 +00007896 << Entity.getName()
7897 << InheritedFrom;
Alp Toker2afa8782014-05-28 12:20:14 +00007898 S.Diag(Entity.getDecl()->getLocation(),
7899 diag::note_member_declared_at);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007900
7901 if (const RecordType *Record
7902 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007903 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007904 diag::note_previous_decl)
7905 << S.Context.getTagDeclType(Record->getDecl());
7906 }
7907 break;
7908 }
7909
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007910 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
7911 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007912 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007913 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007914
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007915 case OR_Deleted: {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007916 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007917 OverloadingResult Ovl
7918 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor74f7d502012-02-15 19:33:52 +00007919 if (Ovl != OR_Deleted) {
7920 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
7921 << true << DestType << ArgsRange;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007922 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor74f7d502012-02-15 19:33:52 +00007923 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007924 }
Douglas Gregor74f7d502012-02-15 19:33:52 +00007925
7926 // If this is a defaulted or implicitly-declared function, then
7927 // it was implicitly deleted. Make it clear that the deletion was
7928 // implicit.
Richard Smith852265f2012-03-30 20:53:28 +00007929 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00007930 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith852265f2012-03-30 20:53:28 +00007931 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00007932 << DestType << ArgsRange;
Richard Smith852265f2012-03-30 20:53:28 +00007933 else
7934 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
7935 << true << DestType << ArgsRange;
7936
7937 S.NoteDeletedFunction(Best->Function);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007938 break;
7939 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007940
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007941 case OR_Success:
7942 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007943 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007944 }
David Blaikie60deeee2012-01-17 08:24:58 +00007945 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007946
Douglas Gregor85dabae2009-12-16 01:38:02 +00007947 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007948 if (Entity.getKind() == InitializedEntity::EK_Member &&
7949 isa<CXXConstructorDecl>(S.CurContext)) {
7950 // This is implicit default-initialization of a const member in
7951 // a constructor. Complain that it needs to be explicitly
7952 // initialized.
7953 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
7954 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00007955 << (Constructor->getInheritedConstructor() ? 2 :
7956 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007957 << S.Context.getTypeDeclType(Constructor->getParent())
7958 << /*const=*/1
7959 << Entity.getName();
7960 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
7961 << Entity.getName();
7962 } else {
7963 S.Diag(Kind.getLocation(), diag::err_default_init_const)
Nico Weber9386c822014-07-23 05:16:10 +00007964 << DestType << (bool)DestType->getAs<RecordType>();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007965 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00007966 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007967
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007968 case FK_Incomplete:
Douglas Gregor85f34232012-04-10 20:43:46 +00007969 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007970 diag::err_init_incomplete_type);
7971 break;
7972
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007973 case FK_ListInitializationFailed: {
7974 // Run the init list checker again to emit diagnostics.
Richard Smith0449aaf2013-11-21 23:30:57 +00007975 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
7976 diagnoseListInit(S, Entity, InitList);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007977 break;
7978 }
John McCall4124c492011-10-17 18:40:02 +00007979
7980 case FK_PlaceholderType: {
7981 // FIXME: Already diagnosed!
7982 break;
7983 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00007984
Sebastian Redl048a6d72012-04-01 19:54:59 +00007985 case FK_ExplicitConstructor: {
7986 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
7987 << Args[0]->getSourceRange();
7988 OverloadCandidateSet::iterator Best;
7989 OverloadingResult Ovl
7990 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gay5dcce092012-04-02 19:05:35 +00007991 (void)Ovl;
Sebastian Redl048a6d72012-04-01 19:54:59 +00007992 assert(Ovl == OR_Success && "Inconsistent overload resolution");
7993 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
Richard Smith60437622017-02-09 19:17:44 +00007994 S.Diag(CtorDecl->getLocation(),
7995 diag::note_explicit_ctor_deduction_guide_here) << false;
Sebastian Redl048a6d72012-04-01 19:54:59 +00007996 break;
7997 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007998 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007999
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008000 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008001 return true;
8002}
Douglas Gregore1314a62009-12-18 05:02:21 +00008003
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008004void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008005 switch (SequenceKind) {
8006 case FailedSequence: {
8007 OS << "Failed sequence: ";
8008 switch (Failure) {
8009 case FK_TooManyInitsForReference:
8010 OS << "too many initializers for reference";
8011 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008012
Richard Smith49a6b6e2017-03-24 01:14:25 +00008013 case FK_ParenthesizedListInitForReference:
8014 OS << "parenthesized list init for reference";
8015 break;
8016
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008017 case FK_ArrayNeedsInitList:
8018 OS << "array requires initializer list";
8019 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008020
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008021 case FK_AddressOfUnaddressableFunction:
8022 OS << "address of unaddressable function was taken";
8023 break;
8024
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008025 case FK_ArrayNeedsInitListOrStringLiteral:
8026 OS << "array requires initializer list or string literal";
8027 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008028
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00008029 case FK_ArrayNeedsInitListOrWideStringLiteral:
8030 OS << "array requires initializer list or wide string literal";
8031 break;
8032
8033 case FK_NarrowStringIntoWideCharArray:
8034 OS << "narrow string into wide char array";
8035 break;
8036
8037 case FK_WideStringIntoCharArray:
8038 OS << "wide string into char array";
8039 break;
8040
8041 case FK_IncompatWideStringIntoWideChar:
8042 OS << "incompatible wide string into wide char array";
8043 break;
8044
Richard Smith3a8244d2018-05-01 05:02:45 +00008045 case FK_PlainStringIntoUTF8Char:
8046 OS << "plain string literal into char8_t array";
8047 break;
8048
8049 case FK_UTF8StringIntoPlainChar:
8050 OS << "u8 string literal into char array";
8051 break;
8052
Douglas Gregore2f943b2011-02-22 18:29:51 +00008053 case FK_ArrayTypeMismatch:
8054 OS << "array type mismatch";
8055 break;
8056
8057 case FK_NonConstantArrayInit:
8058 OS << "non-constant array initializer";
8059 break;
8060
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008061 case FK_AddressOfOverloadFailed:
8062 OS << "address of overloaded function failed";
8063 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008064
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008065 case FK_ReferenceInitOverloadFailed:
8066 OS << "overload resolution for reference initialization failed";
8067 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008068
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008069 case FK_NonConstLValueReferenceBindingToTemporary:
8070 OS << "non-const lvalue reference bound to temporary";
8071 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008072
Richard Smithb8c0f552016-12-09 18:49:13 +00008073 case FK_NonConstLValueReferenceBindingToBitfield:
8074 OS << "non-const lvalue reference bound to bit-field";
8075 break;
8076
8077 case FK_NonConstLValueReferenceBindingToVectorElement:
8078 OS << "non-const lvalue reference bound to vector element";
8079 break;
8080
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008081 case FK_NonConstLValueReferenceBindingToUnrelated:
8082 OS << "non-const lvalue reference bound to unrelated type";
8083 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008084
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008085 case FK_RValueReferenceBindingToLValue:
8086 OS << "rvalue reference bound to an lvalue";
8087 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008088
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008089 case FK_ReferenceInitDropsQualifiers:
8090 OS << "reference initialization drops qualifiers";
8091 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008092
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008093 case FK_ReferenceInitFailed:
8094 OS << "reference initialization failed";
8095 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008096
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008097 case FK_ConversionFailed:
8098 OS << "conversion failed";
8099 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008100
John Wiegley01296292011-04-08 18:41:53 +00008101 case FK_ConversionFromPropertyFailed:
8102 OS << "conversion from property failed";
8103 break;
8104
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008105 case FK_TooManyInitsForScalar:
8106 OS << "too many initializers for scalar";
8107 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008108
Richard Smith49a6b6e2017-03-24 01:14:25 +00008109 case FK_ParenthesizedListInitForScalar:
8110 OS << "parenthesized list init for reference";
8111 break;
8112
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008113 case FK_ReferenceBindingToInitList:
8114 OS << "referencing binding to initializer list";
8115 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008116
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008117 case FK_InitListBadDestinationType:
8118 OS << "initializer list for non-aggregate, non-scalar type";
8119 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008120
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008121 case FK_UserConversionOverloadFailed:
8122 OS << "overloading failed for user-defined conversion";
8123 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008124
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008125 case FK_ConstructorOverloadFailed:
8126 OS << "constructor overloading failed";
8127 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008128
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008129 case FK_DefaultInitOfConst:
8130 OS << "default initialization of a const variable";
8131 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008132
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00008133 case FK_Incomplete:
8134 OS << "initialization of incomplete type";
8135 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008136
8137 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008138 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00008139 break;
8140
John McCalla59dc2f2012-01-05 00:13:19 +00008141 case FK_VariableLengthArrayHasInitializer:
8142 OS << "variable length array has an initializer";
8143 break;
8144
John McCall4124c492011-10-17 18:40:02 +00008145 case FK_PlaceholderType:
8146 OS << "initializer expression isn't contextually valid";
8147 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00008148
8149 case FK_ListConstructorOverloadFailed:
8150 OS << "list constructor overloading failed";
8151 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00008152
Sebastian Redl048a6d72012-04-01 19:54:59 +00008153 case FK_ExplicitConstructor:
8154 OS << "list copy initialization chose explicit constructor";
8155 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008156 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008157 OS << '\n';
8158 return;
8159 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008160
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008161 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00008162 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008163 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008164
Sebastian Redld201edf2011-06-05 13:59:11 +00008165 case NormalSequence:
8166 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008167 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008168 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008169
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008170 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
8171 if (S != step_begin()) {
8172 OS << " -> ";
8173 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008174
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008175 switch (S->Kind) {
8176 case SK_ResolveAddressOfOverloadedFunction:
8177 OS << "resolve address of overloaded function";
8178 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008179
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008180 case SK_CastDerivedToBaseRValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00008181 OS << "derived-to-base (rvalue)";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008182 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008183
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008184 case SK_CastDerivedToBaseXValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00008185 OS << "derived-to-base (xvalue)";
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008186 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008187
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008188 case SK_CastDerivedToBaseLValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00008189 OS << "derived-to-base (lvalue)";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008190 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008191
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008192 case SK_BindReference:
8193 OS << "bind reference to lvalue";
8194 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008195
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008196 case SK_BindReferenceToTemporary:
8197 OS << "bind reference to a temporary";
8198 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008199
Richard Smithb8c0f552016-12-09 18:49:13 +00008200 case SK_FinalCopy:
8201 OS << "final copy in class direct-initialization";
8202 break;
8203
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00008204 case SK_ExtraneousCopyToTemporary:
8205 OS << "extraneous C++03 copy to temporary";
8206 break;
8207
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008208 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00008209 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008210 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008211
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008212 case SK_QualificationConversionRValue:
8213 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00008214 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008215
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008216 case SK_QualificationConversionXValue:
8217 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00008218 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008219
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008220 case SK_QualificationConversionLValue:
8221 OS << "qualification conversion (lvalue)";
8222 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008223
Richard Smith77be48a2014-07-31 06:31:19 +00008224 case SK_AtomicConversion:
8225 OS << "non-atomic-to-atomic conversion";
8226 break;
8227
Jordan Roseb1312a52013-04-11 00:58:58 +00008228 case SK_LValueToRValue:
8229 OS << "load (lvalue to rvalue)";
8230 break;
8231
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008232 case SK_ConversionSequence:
8233 OS << "implicit conversion sequence (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00008234 S->ICS->dump(); // FIXME: use OS
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008235 OS << ")";
8236 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008237
Richard Smithaaa0ec42013-09-21 21:19:19 +00008238 case SK_ConversionSequenceNoNarrowing:
8239 OS << "implicit conversion sequence with narrowing prohibited (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00008240 S->ICS->dump(); // FIXME: use OS
Richard Smithaaa0ec42013-09-21 21:19:19 +00008241 OS << ")";
8242 break;
8243
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008244 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008245 OS << "list aggregate initialization";
8246 break;
8247
Sebastian Redl29526f02011-11-27 16:50:07 +00008248 case SK_UnwrapInitList:
8249 OS << "unwrap reference initializer list";
8250 break;
8251
8252 case SK_RewrapInitList:
8253 OS << "rewrap reference initializer list";
8254 break;
8255
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008256 case SK_ConstructorInitialization:
8257 OS << "constructor initialization";
8258 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008259
Richard Smith53324112014-07-16 21:33:43 +00008260 case SK_ConstructorInitializationFromList:
8261 OS << "list initialization via constructor";
8262 break;
8263
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008264 case SK_ZeroInitialization:
8265 OS << "zero initialization";
8266 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008267
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008268 case SK_CAssignment:
8269 OS << "C assignment";
8270 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008271
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008272 case SK_StringInit:
8273 OS << "string initialization";
8274 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008275
8276 case SK_ObjCObjectConversion:
8277 OS << "Objective-C object conversion";
8278 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00008279
Richard Smith410306b2016-12-12 02:53:20 +00008280 case SK_ArrayLoopIndex:
8281 OS << "indexing for array initialization loop";
8282 break;
8283
8284 case SK_ArrayLoopInit:
8285 OS << "array initialization loop";
8286 break;
8287
Douglas Gregore2f943b2011-02-22 18:29:51 +00008288 case SK_ArrayInit:
8289 OS << "array initialization";
8290 break;
John McCall31168b02011-06-15 23:02:42 +00008291
Richard Smith378b8c82016-12-14 03:22:16 +00008292 case SK_GNUArrayInit:
8293 OS << "array initialization (GNU extension)";
8294 break;
8295
Richard Smithebeed412012-02-15 22:38:09 +00008296 case SK_ParenthesizedArrayInit:
8297 OS << "parenthesized array initialization";
8298 break;
8299
John McCall31168b02011-06-15 23:02:42 +00008300 case SK_PassByIndirectCopyRestore:
8301 OS << "pass by indirect copy and restore";
8302 break;
8303
8304 case SK_PassByIndirectRestore:
8305 OS << "pass by indirect restore";
8306 break;
8307
8308 case SK_ProduceObjCObject:
8309 OS << "Objective-C object retension";
8310 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00008311
8312 case SK_StdInitializerList:
8313 OS << "std::initializer_list from initializer list";
8314 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008315
Richard Smithf8adcdc2014-07-17 05:12:35 +00008316 case SK_StdInitializerListConstructorCall:
8317 OS << "list initialization from std::initializer_list";
8318 break;
8319
Guy Benyei61054192013-02-07 10:55:47 +00008320 case SK_OCLSamplerInit:
8321 OS << "OpenCL sampler_t from integer constant";
8322 break;
8323
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008324 case SK_OCLZeroEvent:
8325 OS << "OpenCL event_t from zero";
8326 break;
Egor Churaev89831422016-12-23 14:55:49 +00008327
8328 case SK_OCLZeroQueue:
8329 OS << "OpenCL queue_t from zero";
8330 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008331 }
Richard Smith6b216962013-02-05 05:52:24 +00008332
8333 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008334 }
Richard Smith6b216962013-02-05 05:52:24 +00008335
8336 OS << '\n';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008337}
8338
8339void InitializationSequence::dump() const {
8340 dump(llvm::errs());
8341}
8342
Nico Weber3d7f00d2018-06-19 23:19:34 +00008343static bool NarrowingErrs(const LangOptions &L) {
8344 return L.CPlusPlus11 &&
8345 (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015));
8346}
8347
Richard Smithaaa0ec42013-09-21 21:19:19 +00008348static void DiagnoseNarrowingInInitList(Sema &S,
8349 const ImplicitConversionSequence &ICS,
8350 QualType PreNarrowingType,
Richard Smith66e05fe2012-01-18 05:21:49 +00008351 QualType EntityType,
Richard Smith66e05fe2012-01-18 05:21:49 +00008352 const Expr *PostInit) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008353 const StandardConversionSequence *SCS = nullptr;
Richard Smith66e05fe2012-01-18 05:21:49 +00008354 switch (ICS.getKind()) {
8355 case ImplicitConversionSequence::StandardConversion:
8356 SCS = &ICS.Standard;
8357 break;
8358 case ImplicitConversionSequence::UserDefinedConversion:
8359 SCS = &ICS.UserDefined.After;
8360 break;
8361 case ImplicitConversionSequence::AmbiguousConversion:
8362 case ImplicitConversionSequence::EllipsisConversion:
8363 case ImplicitConversionSequence::BadConversion:
8364 return;
8365 }
8366
Richard Smith66e05fe2012-01-18 05:21:49 +00008367 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
8368 APValue ConstantValue;
Richard Smith5614ca72012-03-23 23:55:39 +00008369 QualType ConstantType;
8370 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
8371 ConstantType)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00008372 case NK_Not_Narrowing:
Richard Smith52e624f2016-12-21 21:42:57 +00008373 case NK_Dependent_Narrowing:
Richard Smith66e05fe2012-01-18 05:21:49 +00008374 // No narrowing occurred.
8375 return;
8376
8377 case NK_Type_Narrowing:
8378 // This was a floating-to-integer conversion, which is always considered a
8379 // narrowing conversion even if the value is a constant and can be
8380 // represented exactly as an integer.
Nico Weber3d7f00d2018-06-19 23:19:34 +00008381 S.Diag(PostInit->getLocStart(), NarrowingErrs(S.getLangOpts())
8382 ? diag::ext_init_list_type_narrowing
8383 : diag::warn_init_list_type_narrowing)
8384 << PostInit->getSourceRange()
8385 << PreNarrowingType.getLocalUnqualifiedType()
8386 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00008387 break;
8388
8389 case NK_Constant_Narrowing:
8390 // A constant value was narrowed.
8391 S.Diag(PostInit->getLocStart(),
Nico Weber3d7f00d2018-06-19 23:19:34 +00008392 NarrowingErrs(S.getLangOpts())
8393 ? diag::ext_init_list_constant_narrowing
8394 : diag::warn_init_list_constant_narrowing)
8395 << PostInit->getSourceRange()
8396 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
8397 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00008398 break;
8399
8400 case NK_Variable_Narrowing:
8401 // A variable's value may have been narrowed.
8402 S.Diag(PostInit->getLocStart(),
Nico Weber3d7f00d2018-06-19 23:19:34 +00008403 NarrowingErrs(S.getLangOpts())
8404 ? diag::ext_init_list_variable_narrowing
8405 : diag::warn_init_list_variable_narrowing)
8406 << PostInit->getSourceRange()
8407 << PreNarrowingType.getLocalUnqualifiedType()
8408 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00008409 break;
8410 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008411
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008412 SmallString<128> StaticCast;
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008413 llvm::raw_svector_ostream OS(StaticCast);
8414 OS << "static_cast<";
8415 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
8416 // It's important to use the typedef's name if there is one so that the
8417 // fixit doesn't break code using types like int64_t.
8418 //
8419 // FIXME: This will break if the typedef requires qualification. But
8420 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00008421 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008422 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikiebbafb8a2012-03-11 07:00:24 +00008423 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008424 else {
8425 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
8426 // with a broken cast.
8427 return;
8428 }
8429 OS << ">(";
Alp Tokerb0869032014-05-17 01:13:18 +00008430 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence)
Alp Tokerb6cc5922014-05-03 03:45:55 +00008431 << PostInit->getSourceRange()
8432 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
8433 << FixItHint::CreateInsertion(
8434 S.getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008435}
8436
Douglas Gregore1314a62009-12-18 05:02:21 +00008437//===----------------------------------------------------------------------===//
8438// Initialization helper functions
8439//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00008440bool
8441Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
8442 ExprResult Init) {
8443 if (Init.isInvalid())
8444 return false;
8445
8446 Expr *InitE = Init.get();
8447 assert(InitE && "No initialization expression");
8448
Douglas Gregorf4cc61d2012-07-31 22:15:04 +00008449 InitializationKind Kind
8450 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008451 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00008452 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00008453}
8454
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008455ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00008456Sema::PerformCopyInitialization(const InitializedEntity &Entity,
8457 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008458 ExprResult Init,
Douglas Gregor6073dca2012-02-24 23:56:31 +00008459 bool TopLevelOfInitList,
8460 bool AllowExplicit) {
Douglas Gregore1314a62009-12-18 05:02:21 +00008461 if (Init.isInvalid())
8462 return ExprError();
8463
John McCall1f425642010-11-11 03:21:53 +00008464 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00008465 assert(InitE && "No initialization expression?");
8466
8467 if (EqualLoc.isInvalid())
8468 EqualLoc = InitE->getLocStart();
8469
8470 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00008471 EqualLoc,
8472 AllowExplicit);
Richard Smithaaa0ec42013-09-21 21:19:19 +00008473 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008474
Alex Lorenzde69ff92017-05-16 10:23:58 +00008475 // Prevent infinite recursion when performing parameter copy-initialization.
8476 const bool ShouldTrackCopy =
8477 Entity.isParameterKind() && Seq.isConstructorInitialization();
8478 if (ShouldTrackCopy) {
8479 if (llvm::find(CurrentParameterCopyTypes, Entity.getType()) !=
8480 CurrentParameterCopyTypes.end()) {
8481 Seq.SetOverloadFailure(
8482 InitializationSequence::FK_ConstructorOverloadFailed,
8483 OR_No_Viable_Function);
8484
8485 // Try to give a meaningful diagnostic note for the problematic
8486 // constructor.
8487 const auto LastStep = Seq.step_end() - 1;
8488 assert(LastStep->Kind ==
8489 InitializationSequence::SK_ConstructorInitialization);
8490 const FunctionDecl *Function = LastStep->Function.Function;
8491 auto Candidate =
8492 llvm::find_if(Seq.getFailedCandidateSet(),
8493 [Function](const OverloadCandidate &Candidate) -> bool {
8494 return Candidate.Viable &&
8495 Candidate.Function == Function &&
8496 Candidate.Conversions.size() > 0;
8497 });
8498 if (Candidate != Seq.getFailedCandidateSet().end() &&
8499 Function->getNumParams() > 0) {
8500 Candidate->Viable = false;
8501 Candidate->FailureKind = ovl_fail_bad_conversion;
8502 Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion,
8503 InitE,
8504 Function->getParamDecl(0)->getType());
8505 }
8506 }
8507 CurrentParameterCopyTypes.push_back(Entity.getType());
8508 }
8509
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008510 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith66e05fe2012-01-18 05:21:49 +00008511
Alex Lorenzde69ff92017-05-16 10:23:58 +00008512 if (ShouldTrackCopy)
8513 CurrentParameterCopyTypes.pop_back();
8514
Richard Smith66e05fe2012-01-18 05:21:49 +00008515 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00008516}
Richard Smith60437622017-02-09 19:17:44 +00008517
Richard Smith1363e8f2017-09-07 07:22:36 +00008518/// Determine whether RD is, or is derived from, a specialization of CTD.
8519static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD,
8520 ClassTemplateDecl *CTD) {
8521 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
8522 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
8523 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
8524 };
8525 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
8526}
8527
Richard Smith60437622017-02-09 19:17:44 +00008528QualType Sema::DeduceTemplateSpecializationFromInitializer(
8529 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
8530 const InitializationKind &Kind, MultiExprArg Inits) {
8531 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
8532 TSInfo->getType()->getContainedDeducedType());
8533 assert(DeducedTST && "not a deduced template specialization type");
8534
8535 // We can only perform deduction for class templates.
8536 auto TemplateName = DeducedTST->getTemplateName();
8537 auto *Template =
8538 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
8539 if (!Template) {
8540 Diag(Kind.getLocation(),
8541 diag::err_deduced_non_class_template_specialization_type)
8542 << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName;
8543 if (auto *TD = TemplateName.getAsTemplateDecl())
8544 Diag(TD->getLocation(), diag::note_template_decl_here);
8545 return QualType();
8546 }
8547
Richard Smith32918772017-02-14 00:25:28 +00008548 // Can't deduce from dependent arguments.
8549 if (Expr::hasAnyTypeDependentArguments(Inits))
8550 return Context.DependentTy;
8551
Richard Smith60437622017-02-09 19:17:44 +00008552 // FIXME: Perform "exact type" matching first, per CWG discussion?
8553 // Or implement this via an implied 'T(T) -> T' deduction guide?
8554
8555 // FIXME: Do we need/want a std::initializer_list<T> special case?
8556
Richard Smith32918772017-02-14 00:25:28 +00008557 // Look up deduction guides, including those synthesized from constructors.
8558 //
Richard Smith60437622017-02-09 19:17:44 +00008559 // C++1z [over.match.class.deduct]p1:
8560 // A set of functions and function templates is formed comprising:
Richard Smith32918772017-02-14 00:25:28 +00008561 // - For each constructor of the class template designated by the
8562 // template-name, a function template [...]
Richard Smith60437622017-02-09 19:17:44 +00008563 // - For each deduction-guide, a function or function template [...]
8564 DeclarationNameInfo NameInfo(
8565 Context.DeclarationNames.getCXXDeductionGuideName(Template),
8566 TSInfo->getTypeLoc().getEndLoc());
8567 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
8568 LookupQualifiedName(Guides, Template->getDeclContext());
Richard Smith60437622017-02-09 19:17:44 +00008569
8570 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
8571 // clear on this, but they're not found by name so access does not apply.
8572 Guides.suppressDiagnostics();
8573
8574 // Figure out if this is list-initialization.
8575 InitListExpr *ListInit =
8576 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
8577 ? dyn_cast<InitListExpr>(Inits[0])
8578 : nullptr;
8579
8580 // C++1z [over.match.class.deduct]p1:
8581 // Initialization and overload resolution are performed as described in
8582 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
8583 // (as appropriate for the type of initialization performed) for an object
8584 // of a hypothetical class type, where the selected functions and function
8585 // templates are considered to be the constructors of that class type
8586 //
8587 // Since we know we're initializing a class type of a type unrelated to that
8588 // of the initializer, this reduces to something fairly reasonable.
8589 OverloadCandidateSet Candidates(Kind.getLocation(),
8590 OverloadCandidateSet::CSK_Normal);
8591 OverloadCandidateSet::iterator Best;
8592 auto tryToResolveOverload =
8593 [&](bool OnlyListConstructors) -> OverloadingResult {
Richard Smith67ef14f2017-09-26 18:37:55 +00008594 Candidates.clear(OverloadCandidateSet::CSK_Normal);
Richard Smith32918772017-02-14 00:25:28 +00008595 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
8596 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smith60437622017-02-09 19:17:44 +00008597 if (D->isInvalidDecl())
8598 continue;
8599
Richard Smithbc491202017-02-17 20:05:37 +00008600 auto *TD = dyn_cast<FunctionTemplateDecl>(D);
8601 auto *GD = dyn_cast_or_null<CXXDeductionGuideDecl>(
8602 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
8603 if (!GD)
Richard Smith60437622017-02-09 19:17:44 +00008604 continue;
8605
8606 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
8607 // For copy-initialization, the candidate functions are all the
8608 // converting constructors (12.3.1) of that class.
8609 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
8610 // The converting constructors of T are candidate functions.
8611 if (Kind.isCopyInit() && !ListInit) {
Richard Smithafe4aa82017-02-10 02:19:05 +00008612 // Only consider converting constructors.
Richard Smithbc491202017-02-17 20:05:37 +00008613 if (GD->isExplicit())
Richard Smithafe4aa82017-02-10 02:19:05 +00008614 continue;
Richard Smith60437622017-02-09 19:17:44 +00008615
8616 // When looking for a converting constructor, deduction guides that
Richard Smithafe4aa82017-02-10 02:19:05 +00008617 // could never be called with one argument are not interesting to
8618 // check or note.
Richard Smithbc491202017-02-17 20:05:37 +00008619 if (GD->getMinRequiredArguments() > 1 ||
8620 (GD->getNumParams() == 0 && !GD->isVariadic()))
Richard Smith60437622017-02-09 19:17:44 +00008621 continue;
8622 }
8623
8624 // C++ [over.match.list]p1.1: (first phase list initialization)
8625 // Initially, the candidate functions are the initializer-list
8626 // constructors of the class T
Richard Smithbc491202017-02-17 20:05:37 +00008627 if (OnlyListConstructors && !isInitListConstructor(GD))
Richard Smith60437622017-02-09 19:17:44 +00008628 continue;
8629
8630 // C++ [over.match.list]p1.2: (second phase list initialization)
8631 // the candidate functions are all the constructors of the class T
8632 // C++ [over.match.ctor]p1: (all other cases)
8633 // the candidate functions are all the constructors of the class of
8634 // the object being initialized
8635
8636 // C++ [over.best.ics]p4:
8637 // When [...] the constructor [...] is a candidate by
8638 // - [over.match.copy] (in all cases)
8639 // FIXME: The "second phase of [over.match.list] case can also
8640 // theoretically happen here, but it's not clear whether we can
8641 // ever have a parameter of the right type.
8642 bool SuppressUserConversions = Kind.isCopyInit();
8643
Richard Smith60437622017-02-09 19:17:44 +00008644 if (TD)
Richard Smith32918772017-02-14 00:25:28 +00008645 AddTemplateOverloadCandidate(TD, I.getPair(), /*ExplicitArgs*/ nullptr,
8646 Inits, Candidates,
8647 SuppressUserConversions);
Richard Smith60437622017-02-09 19:17:44 +00008648 else
Richard Smithbc491202017-02-17 20:05:37 +00008649 AddOverloadCandidate(GD, I.getPair(), Inits, Candidates,
Richard Smith60437622017-02-09 19:17:44 +00008650 SuppressUserConversions);
8651 }
8652 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
8653 };
8654
8655 OverloadingResult Result = OR_No_Viable_Function;
8656
8657 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
8658 // try initializer-list constructors.
8659 if (ListInit) {
Richard Smith32918772017-02-14 00:25:28 +00008660 bool TryListConstructors = true;
8661
8662 // Try list constructors unless the list is empty and the class has one or
8663 // more default constructors, in which case those constructors win.
8664 if (!ListInit->getNumInits()) {
8665 for (NamedDecl *D : Guides) {
8666 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
8667 if (FD && FD->getMinRequiredArguments() == 0) {
8668 TryListConstructors = false;
8669 break;
8670 }
8671 }
Richard Smith1363e8f2017-09-07 07:22:36 +00008672 } else if (ListInit->getNumInits() == 1) {
8673 // C++ [over.match.class.deduct]:
8674 // As an exception, the first phase in [over.match.list] (considering
8675 // initializer-list constructors) is omitted if the initializer list
8676 // consists of a single expression of type cv U, where U is a
8677 // specialization of C or a class derived from a specialization of C.
8678 Expr *E = ListInit->getInit(0);
8679 auto *RD = E->getType()->getAsCXXRecordDecl();
8680 if (!isa<InitListExpr>(E) && RD &&
8681 isOrIsDerivedFromSpecializationOf(RD, Template))
8682 TryListConstructors = false;
Richard Smith32918772017-02-14 00:25:28 +00008683 }
8684
8685 if (TryListConstructors)
Richard Smith60437622017-02-09 19:17:44 +00008686 Result = tryToResolveOverload(/*OnlyListConstructor*/true);
8687 // Then unwrap the initializer list and try again considering all
8688 // constructors.
8689 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
8690 }
8691
8692 // If list-initialization fails, or if we're doing any other kind of
8693 // initialization, we (eventually) consider constructors.
8694 if (Result == OR_No_Viable_Function)
8695 Result = tryToResolveOverload(/*OnlyListConstructor*/false);
8696
8697 switch (Result) {
8698 case OR_Ambiguous:
8699 Diag(Kind.getLocation(), diag::err_deduced_class_template_ctor_ambiguous)
8700 << TemplateName;
8701 // FIXME: For list-initialization candidates, it'd usually be better to
8702 // list why they were not viable when given the initializer list itself as
8703 // an argument.
8704 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Inits);
8705 return QualType();
8706
Richard Smith32918772017-02-14 00:25:28 +00008707 case OR_No_Viable_Function: {
8708 CXXRecordDecl *Primary =
8709 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
8710 bool Complete =
8711 isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
Richard Smith60437622017-02-09 19:17:44 +00008712 Diag(Kind.getLocation(),
8713 Complete ? diag::err_deduced_class_template_ctor_no_viable
8714 : diag::err_deduced_class_template_incomplete)
Richard Smith32918772017-02-14 00:25:28 +00008715 << TemplateName << !Guides.empty();
Richard Smith60437622017-02-09 19:17:44 +00008716 Candidates.NoteCandidates(*this, OCD_AllCandidates, Inits);
8717 return QualType();
Richard Smith32918772017-02-14 00:25:28 +00008718 }
Richard Smith60437622017-02-09 19:17:44 +00008719
8720 case OR_Deleted: {
8721 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
8722 << TemplateName;
8723 NoteDeletedFunction(Best->Function);
8724 return QualType();
8725 }
8726
8727 case OR_Success:
8728 // C++ [over.match.list]p1:
8729 // In copy-list-initialization, if an explicit constructor is chosen, the
8730 // initialization is ill-formed.
Richard Smithbc491202017-02-17 20:05:37 +00008731 if (Kind.isCopyInit() && ListInit &&
8732 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
Richard Smith60437622017-02-09 19:17:44 +00008733 bool IsDeductionGuide = !Best->Function->isImplicit();
8734 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
8735 << TemplateName << IsDeductionGuide;
8736 Diag(Best->Function->getLocation(),
8737 diag::note_explicit_ctor_deduction_guide_here)
8738 << IsDeductionGuide;
8739 return QualType();
8740 }
8741
8742 // Make sure we didn't select an unusable deduction guide, and mark it
8743 // as referenced.
8744 DiagnoseUseOfDecl(Best->Function, Kind.getLocation());
8745 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
8746 break;
8747 }
8748
8749 // C++ [dcl.type.class.deduct]p1:
8750 // The placeholder is replaced by the return type of the function selected
8751 // by overload resolution for class template deduction.
8752 return SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());
8753}