blob: be33326cd42bf289b299f459be5fa7d838dab02f [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
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000035/// \brief Check whether T is compatible with a wide character type (wchar_t,
36/// 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
57/// \brief Check whether the array of type AT can be initialized by the Init
58/// 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
Douglas Gregorcde232f2009-01-29 01:05:33 +0000220/// @brief Semantic checking for initializer lists.
221///
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
380 // @brief Retrieves the fully-structured initializer list used for
381 // 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
Craig Topperc3ec1492014-05-26 06:22:03 +0000754 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000755 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
756 ILE->setInit(Init, ILE->getArrayFiller());
757 else if (!InitExpr && !ILE->hasArrayFiller()) {
758 Expr *Filler = nullptr;
759
760 if (FillWithNoInit)
761 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
762 else {
763 ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(),
764 ElementEntity,
Manman Ren073db022016-03-10 18:53:19 +0000765 /*VerifyOnly*/false,
766 TreatUnavailableAsInvalid);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000767 if (ElementInit.isInvalid()) {
768 hadError = true;
769 return;
770 }
771
772 Filler = ElementInit.getAs<Expr>();
Douglas Gregor723796a2009-12-16 06:35:08 +0000773 }
774
775 if (hadError) {
776 // Do nothing
777 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000778 // For arrays, just set the expression used for value-initialization
779 // of the "holes" in the array.
780 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
Yunzhong Gaocb779302015-06-10 00:27:52 +0000781 ILE->setArrayFiller(Filler);
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000782 else
Yunzhong Gaocb779302015-06-10 00:27:52 +0000783 ILE->setInit(Init, Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000784 } else {
785 // For arrays, just set the expression used for value-initialization
786 // of the rest of elements and exit.
787 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000788 ILE->setArrayFiller(Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000789 return;
790 }
791
Yunzhong Gaocb779302015-06-10 00:27:52 +0000792 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000793 // Empty initialization requires a constructor call, so
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000794 // extend the initializer list to include the constructor
795 // call and make a note that we'll need to take another pass
796 // through the initializer list.
Yunzhong Gaocb779302015-06-10 00:27:52 +0000797 ILE->updateInit(SemaRef.Context, Init, Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000798 RequiresSecondPass = true;
799 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000800 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000801 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000802 = dyn_cast_or_null<InitListExpr>(InitExpr))
Yunzhong Gaocb779302015-06-10 00:27:52 +0000803 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000804 ILE, Init, FillWithNoInit);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000805 else if (DesignatedInitUpdateExpr *InnerDIUE
806 = dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr))
807 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
Richard Smithf3b4ca82018-02-07 22:25:16 +0000808 RequiresSecondPass, ILE, Init,
809 /*FillWithNoInit =*/true);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000810 }
811}
812
Douglas Gregor723796a2009-12-16 06:35:08 +0000813InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000814 InitListExpr *IL, QualType &T,
Manman Ren073db022016-03-10 18:53:19 +0000815 bool VerifyOnly,
816 bool TreatUnavailableAsInvalid)
817 : SemaRef(S), VerifyOnly(VerifyOnly),
818 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid) {
Richard Smith520449d2015-02-05 06:15:50 +0000819 // FIXME: Check that IL isn't already the semantic form of some other
820 // InitListExpr. If it is, we'd create a broken AST.
821
Steve Narofff8ecff22008-05-01 22:18:59 +0000822 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000823
Richard Smith4e0d2e42013-09-20 20:10:22 +0000824 FullyStructuredList =
Craig Topperc3ec1492014-05-26 06:22:03 +0000825 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000826 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000827 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000828
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000829 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000830 bool RequiresSecondPass = false;
Richard Smithf3b4ca82018-02-07 22:25:16 +0000831 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
832 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000833 if (RequiresSecondPass && !hadError)
Richard Smith454a7cd2014-06-03 08:26:00 +0000834 FillInEmptyInitializations(Entity, FullyStructuredList,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000835 RequiresSecondPass, nullptr, 0);
Douglas Gregor723796a2009-12-16 06:35:08 +0000836 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000837}
838
839int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000840 // FIXME: use a proper constant
841 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000842 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000843 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000844 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
845 }
846 return maxElements;
847}
848
849int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000850 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000851 int InitializableMembers = 0;
Richard Smith872307e2016-03-08 22:17:41 +0000852 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
853 InitializableMembers += CXXRD->getNumBases();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000854 for (const auto *Field : structDecl->fields())
Douglas Gregor556e5862011-10-10 17:22:13 +0000855 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000856 ++InitializableMembers;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000857
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000858 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000859 return std::min(InitializableMembers, 1);
860 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000861}
862
Richard Smith283e2072017-10-03 20:36:00 +0000863/// Determine whether Entity is an entity for which it is idiomatic to elide
864/// the braces in aggregate initialization.
865static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
866 // Recursive initialization of the one and only field within an aggregate
867 // class is considered idiomatic. This case arises in particular for
868 // initialization of std::array, where the C++ standard suggests the idiom of
869 //
870 // std::array<T, N> arr = {1, 2, 3};
871 //
872 // (where std::array is an aggregate struct containing a single array field.
873
874 // FIXME: Should aggregate initialization of a struct with a single
875 // base class and no members also suppress the warning?
876 if (Entity.getKind() != InitializedEntity::EK_Member || !Entity.getParent())
877 return false;
878
879 auto *ParentRD =
880 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
881 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD))
882 if (CXXRD->getNumBases())
883 return false;
884
885 auto FieldIt = ParentRD->field_begin();
886 assert(FieldIt != ParentRD->field_end() &&
887 "no fields but have initializer for member?");
888 return ++FieldIt == ParentRD->field_end();
889}
890
Richard Smith4e0d2e42013-09-20 20:10:22 +0000891/// Check whether the range of the initializer \p ParentIList from element
892/// \p Index onwards can be used to initialize an object of type \p T. Update
893/// \p Index to indicate how many elements of the list were consumed.
894///
895/// This also fills in \p StructuredList, from element \p StructuredIndex
896/// onwards, with the fully-braced, desugared form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000897void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000898 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000899 QualType T, unsigned &Index,
900 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000901 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000902 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000903
Steve Narofff8ecff22008-05-01 22:18:59 +0000904 if (T->isArrayType())
905 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000906 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000907 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000908 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000909 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000910 else
David Blaikie83d382b2011-09-23 05:06:16 +0000911 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000912
Eli Friedmane0f832b2008-05-25 13:49:22 +0000913 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000914 if (!VerifyOnly)
915 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
916 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000917 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000918 hadError = true;
919 return;
920 }
921
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000922 // Build a structured initializer list corresponding to this subobject.
923 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000924 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
925 StructuredIndex,
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000926 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregor5741efb2009-03-01 17:12:46 +0000927 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000928 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000929
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000930 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000931 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000932 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000933 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000934 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000935 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000936
Richard Smithde229232013-06-06 11:41:05 +0000937 if (!VerifyOnly) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000938 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000939
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000940 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000941 // Update the structured sub-object initializer so that it's ending
942 // range corresponds with the end of the last initializer it used.
Reid Kleckner4a09e882015-12-09 23:18:38 +0000943 if (EndIndex < ParentIList->getNumInits() &&
944 ParentIList->getInit(EndIndex)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000945 SourceLocation EndLoc
946 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
947 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
948 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000949
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000950 // Complain about missing braces.
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +0000951 if ((T->isArrayType() || T->isRecordType()) &&
Richard Smith283e2072017-10-03 20:36:00 +0000952 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
953 !isIdiomaticBraceElisionEntity(Entity)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000954 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Richard Smithde229232013-06-06 11:41:05 +0000955 diag::warn_missing_braces)
Alp Tokerb6cc5922014-05-03 03:45:55 +0000956 << StructuredSubobjectInitList->getSourceRange()
957 << FixItHint::CreateInsertion(
958 StructuredSubobjectInitList->getLocStart(), "{")
959 << FixItHint::CreateInsertion(
960 SemaRef.getLocForEndOfToken(
961 StructuredSubobjectInitList->getLocEnd()),
962 "}");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000963 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000964 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000965}
966
Richard Smith420fa122015-02-12 01:50:05 +0000967/// Warn that \p Entity was of scalar type and was initialized by a
968/// single-element braced initializer list.
969static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
970 SourceRange Braces) {
971 // Don't warn during template instantiation. If the initialization was
972 // non-dependent, we warned during the initial parse; otherwise, the
973 // type might not be scalar in some uses of the template.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000974 if (S.inTemplateInstantiation())
Richard Smith420fa122015-02-12 01:50:05 +0000975 return;
976
977 unsigned DiagID = 0;
978
979 switch (Entity.getKind()) {
980 case InitializedEntity::EK_VectorElement:
981 case InitializedEntity::EK_ComplexElement:
982 case InitializedEntity::EK_ArrayElement:
983 case InitializedEntity::EK_Parameter:
984 case InitializedEntity::EK_Parameter_CF_Audited:
985 case InitializedEntity::EK_Result:
986 // Extra braces here are suspicious.
987 DiagID = diag::warn_braces_around_scalar_init;
988 break;
989
990 case InitializedEntity::EK_Member:
991 // Warn on aggregate initialization but not on ctor init list or
992 // default member initializer.
993 if (Entity.getParent())
994 DiagID = diag::warn_braces_around_scalar_init;
995 break;
996
997 case InitializedEntity::EK_Variable:
998 case InitializedEntity::EK_LambdaCapture:
999 // No warning, might be direct-list-initialization.
1000 // FIXME: Should we warn for copy-list-initialization in these cases?
1001 break;
1002
1003 case InitializedEntity::EK_New:
1004 case InitializedEntity::EK_Temporary:
1005 case InitializedEntity::EK_CompoundLiteralInit:
1006 // No warning, braces are part of the syntax of the underlying construct.
1007 break;
1008
1009 case InitializedEntity::EK_RelatedResult:
1010 // No warning, we already warned when initializing the result.
1011 break;
1012
1013 case InitializedEntity::EK_Exception:
1014 case InitializedEntity::EK_Base:
1015 case InitializedEntity::EK_Delegating:
1016 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00001017 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Richard Smith7873de02016-08-11 22:25:46 +00001018 case InitializedEntity::EK_Binding:
Richard Smith420fa122015-02-12 01:50:05 +00001019 llvm_unreachable("unexpected braced scalar init");
1020 }
1021
1022 if (DiagID) {
1023 S.Diag(Braces.getBegin(), DiagID)
1024 << Braces
1025 << FixItHint::CreateRemoval(Braces.getBegin())
1026 << FixItHint::CreateRemoval(Braces.getEnd());
1027 }
1028}
1029
Richard Smith4e0d2e42013-09-20 20:10:22 +00001030/// Check whether the initializer \p IList (that was written with explicit
1031/// braces) can be used to initialize an object of type \p T.
1032///
1033/// This also fills in \p StructuredList with the fully-braced, desugared
1034/// form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +00001035void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001036 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001037 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001038 bool TopLevelObject) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001039 if (!VerifyOnly) {
1040 SyntacticToSemantic[IList] = StructuredList;
1041 StructuredList->setSyntacticForm(IList);
1042 }
Richard Smith4e0d2e42013-09-20 20:10:22 +00001043
1044 unsigned Index = 0, StructuredIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001045 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +00001046 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001047 if (!VerifyOnly) {
Eli Friedman91f5ae52012-02-23 02:25:10 +00001048 QualType ExprTy = T;
1049 if (!ExprTy->isArrayType())
1050 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001051 IList->setType(ExprTy);
1052 StructuredList->setType(ExprTy);
1053 }
Eli Friedman85f54972008-05-25 13:22:35 +00001054 if (hadError)
1055 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001056
Eli Friedman85f54972008-05-25 13:22:35 +00001057 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001058 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001059 if (VerifyOnly) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001060 if (SemaRef.getLangOpts().CPlusPlus ||
1061 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001062 IList->getType()->isVectorType())) {
1063 hadError = true;
1064 }
1065 return;
1066 }
1067
Eli Friedmanbd327452009-05-29 20:20:05 +00001068 if (StructuredIndex == 1 &&
Hans Wennborg950f3182013-05-16 09:22:40 +00001069 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1070 SIF_None) {
Richard Smith1b98ccc2014-07-19 01:39:17 +00001071 unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001072 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001073 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +00001074 hadError = true;
1075 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001076 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +00001077 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +00001078 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +00001079 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +00001080 // Don't complain for incomplete types, since we'll get an error
1081 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001082 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001083 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001084 CurrentObjectType->isArrayType()? 0 :
1085 CurrentObjectType->isVectorType()? 1 :
1086 CurrentObjectType->isScalarType()? 2 :
1087 CurrentObjectType->isUnionType()? 3 :
1088 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001089
Richard Smith1b98ccc2014-07-19 01:39:17 +00001090 unsigned DK = diag::ext_excess_initializers;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001091 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanbd327452009-05-29 20:20:05 +00001092 DK = diag::err_excess_initializers;
1093 hadError = true;
1094 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00001095 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman425038c2009-07-07 21:53:06 +00001096 DK = diag::err_excess_initializers;
1097 hadError = true;
1098 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001099
Chris Lattnerb0912a52009-02-24 22:50:46 +00001100 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001101 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001102 }
1103 }
Eli Friedman6fcdec22008-05-19 20:20:43 +00001104
Richard Smith420fa122015-02-12 01:50:05 +00001105 if (!VerifyOnly && T->isScalarType() &&
1106 IList->getNumInits() == 1 && !isa<InitListExpr>(IList->getInit(0)))
1107 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
Steve Narofff8ecff22008-05-01 22:18:59 +00001108}
1109
Anders Carlsson6cabf312010-01-23 23:23:01 +00001110void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001111 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001112 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001113 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001114 unsigned &Index,
1115 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001116 unsigned &StructuredIndex,
1117 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001118 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1119 // Explicitly braced initializer for complex type can be real+imaginary
1120 // parts.
1121 CheckComplexType(Entity, IList, DeclType, Index,
1122 StructuredList, StructuredIndex);
1123 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +00001124 CheckScalarType(Entity, IList, DeclType, Index,
1125 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001126 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001127 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +00001128 StructuredList, StructuredIndex);
Richard Smithe20c83d2012-07-07 08:35:56 +00001129 } else if (DeclType->isRecordType()) {
1130 assert(DeclType->isAggregateType() &&
1131 "non-aggregate records should be handed in CheckSubElementType");
1132 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith872307e2016-03-08 22:17:41 +00001133 auto Bases =
1134 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
1135 CXXRecordDecl::base_class_iterator());
1136 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1137 Bases = CXXRD->bases();
1138 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1139 SubobjectIsDesignatorContext, Index, StructuredList,
1140 StructuredIndex, TopLevelObject);
Richard Smithe20c83d2012-07-07 08:35:56 +00001141 } else if (DeclType->isArrayType()) {
1142 llvm::APSInt Zero(
1143 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1144 false);
1145 CheckArrayType(Entity, IList, DeclType, Zero,
1146 SubobjectIsDesignatorContext, Index,
1147 StructuredList, StructuredIndex);
Steve Naroffeaf58532008-08-10 16:05:48 +00001148 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1149 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001150 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001151 if (!VerifyOnly)
1152 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1153 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +00001154 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +00001155 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +00001156 CheckReferenceType(Entity, IList, DeclType, Index,
1157 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +00001158 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001159 if (!VerifyOnly)
1160 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
1161 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +00001162 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +00001163 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001164 if (!VerifyOnly)
1165 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1166 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +00001167 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +00001168 }
1169}
1170
Anders Carlsson6cabf312010-01-23 23:23:01 +00001171void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001172 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001173 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001174 unsigned &Index,
1175 InitListExpr *StructuredList,
1176 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +00001177 Expr *expr = IList->getInit(Index);
Richard Smith72752e82013-05-31 02:56:17 +00001178
1179 if (ElemType->isReferenceType())
1180 return CheckReferenceType(Entity, IList, ElemType, Index,
1181 StructuredList, StructuredIndex);
1182
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001183 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Yunzhong Gaocb779302015-06-10 00:27:52 +00001184 if (SubInitList->getNumInits() == 1 &&
1185 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1186 SIF_None) {
1187 expr = SubInitList->getInit(0);
1188 } else if (!SemaRef.getLangOpts().CPlusPlus) {
Richard Smith4e0d2e42013-09-20 20:10:22 +00001189 InitListExpr *InnerStructuredList
Richard Smithe20c83d2012-07-07 08:35:56 +00001190 = getStructuredSubobjectInit(IList, Index, ElemType,
1191 StructuredList, StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +00001192 SubInitList->getSourceRange(), true);
Richard Smith4e0d2e42013-09-20 20:10:22 +00001193 CheckExplicitInitList(Entity, SubInitList, ElemType,
1194 InnerStructuredList);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001195
1196 if (!hadError && !VerifyOnly) {
1197 bool RequiresSecondPass = false;
1198 FillInEmptyInitializations(Entity, InnerStructuredList,
Richard Smithf3b4ca82018-02-07 22:25:16 +00001199 RequiresSecondPass, StructuredList,
1200 StructuredIndex);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001201 if (RequiresSecondPass && !hadError)
1202 FillInEmptyInitializations(Entity, InnerStructuredList,
Richard Smithf3b4ca82018-02-07 22:25:16 +00001203 RequiresSecondPass, StructuredList,
1204 StructuredIndex);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001205 }
Richard Smithe20c83d2012-07-07 08:35:56 +00001206 ++StructuredIndex;
1207 ++Index;
1208 return;
1209 }
Richard Smithe20c83d2012-07-07 08:35:56 +00001210 // C++ initialization is handled later.
Richard Smithc4158e862014-07-18 04:47:25 +00001211 } else if (isa<ImplicitValueInitExpr>(expr)) {
Richard Smith8aa561b2014-07-17 23:12:06 +00001212 // This happens during template instantiation when we see an InitListExpr
1213 // that we've already checked once.
Richard Smithc4158e862014-07-18 04:47:25 +00001214 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
Richard Smith8aa561b2014-07-17 23:12:06 +00001215 "found implicit initialization for the wrong type");
1216 if (!VerifyOnly)
1217 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1218 ++Index;
1219 return;
Richard Smithe20c83d2012-07-07 08:35:56 +00001220 }
1221
Richard Smith3c567fc2015-02-12 01:55:09 +00001222 if (SemaRef.getLangOpts().CPlusPlus) {
1223 // C++ [dcl.init.aggr]p2:
1224 // Each member is copy-initialized from the corresponding
1225 // initializer-clause.
1226
1227 // FIXME: Better EqualLoc?
1228 InitializationKind Kind =
1229 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
1230 InitializationSequence Seq(SemaRef, Entity, Kind, expr,
1231 /*TopLevelOfInitList*/ true);
1232
1233 // C++14 [dcl.init.aggr]p13:
1234 // If the assignment-expression can initialize a member, the member is
1235 // initialized. Otherwise [...] brace elision is assumed
1236 //
1237 // Brace elision is never performed if the element is not an
1238 // assignment-expression.
1239 if (Seq || isa<InitListExpr>(expr)) {
1240 if (!VerifyOnly) {
1241 ExprResult Result =
1242 Seq.Perform(SemaRef, Entity, Kind, expr);
1243 if (Result.isInvalid())
1244 hadError = true;
1245
1246 UpdateStructuredListElement(StructuredList, StructuredIndex,
1247 Result.getAs<Expr>());
Richard Smith40574cc2015-02-16 04:42:59 +00001248 } else if (!Seq)
1249 hadError = true;
Richard Smith3c567fc2015-02-12 01:55:09 +00001250 ++Index;
1251 return;
1252 }
1253
1254 // Fall through for subaggregate initialization
1255 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1256 // FIXME: Need to handle atomic aggregate types with implicit init lists.
John McCall5decec92011-02-21 07:57:55 +00001257 return CheckScalarType(Entity, IList, ElemType, Index,
1258 StructuredList, StructuredIndex);
Richard Smith3c567fc2015-02-12 01:55:09 +00001259 } else if (const ArrayType *arrayType =
1260 SemaRef.Context.getAsArrayType(ElemType)) {
John McCall5decec92011-02-21 07:57:55 +00001261 // arrayType can be incomplete if we're initializing a flexible
1262 // array member. There's nothing we can do with the completed
1263 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001264
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001265 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedmand8d7a372011-09-26 19:09:09 +00001266 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001267 CheckStringInit(expr, ElemType, arrayType, SemaRef);
1268 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedmand8d7a372011-09-26 19:09:09 +00001269 }
Douglas Gregord14247a2009-01-30 22:09:00 +00001270 ++Index;
John McCall5decec92011-02-21 07:57:55 +00001271 return;
Douglas Gregord14247a2009-01-30 22:09:00 +00001272 }
John McCall5decec92011-02-21 07:57:55 +00001273
1274 // Fall through for subaggregate initialization.
1275
John McCall5decec92011-02-21 07:57:55 +00001276 } else {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001277 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
Egor Churaev45fe70f2017-05-10 10:28:34 +00001278 ElemType->isOpenCLSpecificType()) && "Unexpected type");
Richard Smith3c567fc2015-02-12 01:55:09 +00001279
John McCall5decec92011-02-21 07:57:55 +00001280 // C99 6.7.8p13:
1281 //
1282 // The initializer for a structure or union object that has
1283 // automatic storage duration shall be either an initializer
1284 // list as described below, or a single expression that has
1285 // compatible structure or union type. In the latter case, the
1286 // initial value of the object, including unnamed members, is
1287 // that of the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001288 ExprResult ExprRes = expr;
Richard Smith3c567fc2015-02-12 01:55:09 +00001289 if (SemaRef.CheckSingleAssignmentConstraints(
1290 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
John Wiegley01296292011-04-08 18:41:53 +00001291 if (ExprRes.isInvalid())
1292 hadError = true;
1293 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001294 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001295 if (ExprRes.isInvalid())
1296 hadError = true;
John Wiegley01296292011-04-08 18:41:53 +00001297 }
1298 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001299 ExprRes.getAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +00001300 ++Index;
1301 return;
1302 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001303 ExprRes.get();
John McCall5decec92011-02-21 07:57:55 +00001304 // Fall through for subaggregate initialization
1305 }
1306
1307 // C++ [dcl.init.aggr]p12:
1308 //
1309 // [...] Otherwise, if the member is itself a non-empty
1310 // subaggregate, brace elision is assumed and the initializer is
1311 // considered for the initialization of the first member of
1312 // the subaggregate.
Yaxun Liua91da4b2016-10-11 15:53:28 +00001313 // OpenCL vector initializer is handled elsewhere.
1314 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1315 ElemType->isAggregateType()) {
John McCall5decec92011-02-21 07:57:55 +00001316 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1317 StructuredIndex);
1318 ++StructuredIndex;
1319 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001320 if (!VerifyOnly) {
1321 // We cannot initialize this element, so let
1322 // PerformCopyInitialization produce the appropriate diagnostic.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001323 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001324 /*TopLevelOfInitList=*/true);
1325 }
John McCall5decec92011-02-21 07:57:55 +00001326 hadError = true;
1327 ++Index;
1328 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +00001329 }
Eli Friedman23a9e312008-05-19 19:16:24 +00001330}
1331
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001332void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1333 InitListExpr *IList, QualType DeclType,
1334 unsigned &Index,
1335 InitListExpr *StructuredList,
1336 unsigned &StructuredIndex) {
1337 assert(Index == 0 && "Index in explicit init list must be zero");
1338
1339 // As an extension, clang supports complex initializers, which initialize
1340 // a complex number component-wise. When an explicit initializer list for
1341 // a complex number contains two two initializers, this extension kicks in:
1342 // it exepcts the initializer list to contain two elements convertible to
1343 // the element type of the complex type. The first element initializes
1344 // the real part, and the second element intitializes the imaginary part.
1345
1346 if (IList->getNumInits() != 2)
1347 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1348 StructuredIndex);
1349
1350 // This is an extension in C. (The builtin _Complex type does not exist
1351 // in the C++ standard.)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001352 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001353 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
1354 << IList->getSourceRange();
1355
1356 // Initialize the complex number.
1357 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1358 InitializedEntity ElementEntity =
1359 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1360
1361 for (unsigned i = 0; i < 2; ++i) {
1362 ElementEntity.setElementIndex(Index);
1363 CheckSubElementType(ElementEntity, IList, elementType, Index,
1364 StructuredList, StructuredIndex);
1365 }
1366}
1367
Anders Carlsson6cabf312010-01-23 23:23:01 +00001368void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001369 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +00001370 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001371 InitListExpr *StructuredList,
1372 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +00001373 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +00001374 if (!VerifyOnly)
1375 SemaRef.Diag(IList->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001376 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smithc8239732011-10-18 21:39:00 +00001377 diag::warn_cxx98_compat_empty_scalar_initializer :
1378 diag::err_empty_scalar_initializer)
1379 << IList->getSourceRange();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001380 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001381 ++Index;
1382 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001383 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001384 }
John McCall643169b2010-11-11 00:46:36 +00001385
1386 Expr *expr = IList->getInit(Index);
1387 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Richard Smithfe9d2c02013-11-19 03:41:32 +00001388 // FIXME: This is invalid, and accepting it causes overload resolution
1389 // to pick the wrong overload in some corner cases.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001390 if (!VerifyOnly)
1391 SemaRef.Diag(SubIList->getLocStart(),
Richard Smithfe9d2c02013-11-19 03:41:32 +00001392 diag::ext_many_braces_around_scalar_init)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001393 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001394
1395 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1396 StructuredIndex);
1397 return;
1398 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001399 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001400 SemaRef.Diag(expr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001401 diag::err_designator_for_scalar_init)
1402 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001403 hadError = true;
1404 ++Index;
1405 ++StructuredIndex;
1406 return;
1407 }
1408
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001409 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001410 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001411 hadError = true;
1412 ++Index;
1413 return;
1414 }
1415
John McCall643169b2010-11-11 00:46:36 +00001416 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001417 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001418 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +00001419
Craig Topperc3ec1492014-05-26 06:22:03 +00001420 Expr *ResultExpr = nullptr;
John McCall643169b2010-11-11 00:46:36 +00001421
1422 if (Result.isInvalid())
1423 hadError = true; // types weren't compatible.
1424 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001425 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001426
John McCall643169b2010-11-11 00:46:36 +00001427 if (ResultExpr != expr) {
1428 // The type was promoted, update initializer list.
1429 IList->setInit(Index, ResultExpr);
1430 }
1431 }
1432 if (hadError)
1433 ++StructuredIndex;
1434 else
1435 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1436 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001437}
1438
Anders Carlsson6cabf312010-01-23 23:23:01 +00001439void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1440 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +00001441 unsigned &Index,
1442 InitListExpr *StructuredList,
1443 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001444 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001445 // FIXME: It would be wonderful if we could point at the actual member. In
1446 // general, it would be useful to pass location information down the stack,
1447 // so that we know the location (or decl) of the "current object" being
1448 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001449 if (!VerifyOnly)
1450 SemaRef.Diag(IList->getLocStart(),
1451 diag::err_init_reference_member_uninitialized)
1452 << DeclType
1453 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +00001454 hadError = true;
1455 ++Index;
1456 ++StructuredIndex;
1457 return;
1458 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001459
1460 Expr *expr = IList->getInit(Index);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001461 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001462 if (!VerifyOnly)
1463 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1464 << DeclType << IList->getSourceRange();
1465 hadError = true;
1466 ++Index;
1467 ++StructuredIndex;
1468 return;
1469 }
1470
1471 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001472 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001473 hadError = true;
1474 ++Index;
1475 return;
1476 }
1477
1478 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001479 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1480 /*TopLevelOfInitList=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001481
1482 if (Result.isInvalid())
1483 hadError = true;
1484
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001485 expr = Result.getAs<Expr>();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001486 IList->setInit(Index, expr);
1487
1488 if (hadError)
1489 ++StructuredIndex;
1490 else
1491 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1492 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001493}
1494
Anders Carlsson6cabf312010-01-23 23:23:01 +00001495void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001496 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001497 unsigned &Index,
1498 InitListExpr *StructuredList,
1499 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001500 const VectorType *VT = DeclType->getAs<VectorType>();
1501 unsigned maxElements = VT->getNumElements();
1502 unsigned numEltsInit = 0;
1503 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001504
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001505 if (Index >= IList->getNumInits()) {
1506 // Make sure the element type can be value-initialized.
1507 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001508 CheckEmptyInitializable(
1509 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1510 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001511 return;
1512 }
1513
David Blaikiebbafb8a2012-03-11 07:00:24 +00001514 if (!SemaRef.getLangOpts().OpenCL) {
John McCall6a16b2f2010-10-30 00:11:39 +00001515 // If the initializing element is a vector, try to copy-initialize
1516 // instead of breaking it apart (which is doomed to failure anyway).
1517 Expr *Init = IList->getInit(Index);
1518 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001519 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001520 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001521 hadError = true;
1522 ++Index;
1523 return;
1524 }
1525
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001526 ExprResult Result =
1527 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
1528 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001529
Craig Topperc3ec1492014-05-26 06:22:03 +00001530 Expr *ResultExpr = nullptr;
John McCall6a16b2f2010-10-30 00:11:39 +00001531 if (Result.isInvalid())
1532 hadError = true; // types weren't compatible.
1533 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001534 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001535
John McCall6a16b2f2010-10-30 00:11:39 +00001536 if (ResultExpr != Init) {
1537 // The type was promoted, update initializer list.
1538 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001539 }
1540 }
John McCall6a16b2f2010-10-30 00:11:39 +00001541 if (hadError)
1542 ++StructuredIndex;
1543 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001544 UpdateStructuredListElement(StructuredList, StructuredIndex,
1545 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001546 ++Index;
1547 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001548 }
Mike Stump11289f42009-09-09 15:08:12 +00001549
John McCall6a16b2f2010-10-30 00:11:39 +00001550 InitializedEntity ElementEntity =
1551 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001552
John McCall6a16b2f2010-10-30 00:11:39 +00001553 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1554 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001555 if (Index >= IList->getNumInits()) {
1556 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001557 CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
John McCall6a16b2f2010-10-30 00:11:39 +00001558 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001559 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001560
John McCall6a16b2f2010-10-30 00:11:39 +00001561 ElementEntity.setElementIndex(Index);
1562 CheckSubElementType(ElementEntity, IList, elementType, Index,
1563 StructuredList, StructuredIndex);
1564 }
James Molloy9eef2652014-06-20 14:35:13 +00001565
1566 if (VerifyOnly)
1567 return;
1568
1569 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1570 const VectorType *T = Entity.getType()->getAs<VectorType>();
1571 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1572 T->getVectorKind() == VectorType::NeonPolyVector)) {
1573 // The ability to use vector initializer lists is a GNU vector extension
1574 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1575 // endian machines it works fine, however on big endian machines it
1576 // exhibits surprising behaviour:
1577 //
1578 // uint32x2_t x = {42, 64};
1579 // return vget_lane_u32(x, 0); // Will return 64.
1580 //
1581 // Because of this, explicitly call out that it is non-portable.
1582 //
1583 SemaRef.Diag(IList->getLocStart(),
1584 diag::warn_neon_vector_initializer_non_portable);
1585
1586 const char *typeCode;
1587 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1588
1589 if (elementType->isFloatingType())
1590 typeCode = "f";
1591 else if (elementType->isSignedIntegerType())
1592 typeCode = "s";
1593 else if (elementType->isUnsignedIntegerType())
1594 typeCode = "u";
1595 else
1596 llvm_unreachable("Invalid element type!");
1597
1598 SemaRef.Diag(IList->getLocStart(),
1599 SemaRef.Context.getTypeSize(VT) > 64 ?
1600 diag::note_neon_vector_initializer_non_portable_q :
1601 diag::note_neon_vector_initializer_non_portable)
1602 << typeCode << typeSize;
1603 }
1604
John McCall6a16b2f2010-10-30 00:11:39 +00001605 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001606 }
John McCall6a16b2f2010-10-30 00:11:39 +00001607
1608 InitializedEntity ElementEntity =
1609 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001610
John McCall6a16b2f2010-10-30 00:11:39 +00001611 // OpenCL initializers allows vectors to be constructed from vectors.
1612 for (unsigned i = 0; i < maxElements; ++i) {
1613 // Don't attempt to go past the end of the init list
1614 if (Index >= IList->getNumInits())
1615 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001616
John McCall6a16b2f2010-10-30 00:11:39 +00001617 ElementEntity.setElementIndex(Index);
1618
1619 QualType IType = IList->getInit(Index)->getType();
1620 if (!IType->isVectorType()) {
1621 CheckSubElementType(ElementEntity, IList, elementType, Index,
1622 StructuredList, StructuredIndex);
1623 ++numEltsInit;
1624 } else {
1625 QualType VecType;
1626 const VectorType *IVT = IType->getAs<VectorType>();
1627 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001628
John McCall6a16b2f2010-10-30 00:11:39 +00001629 if (IType->isExtVectorType())
1630 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1631 else
1632 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001633 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001634 CheckSubElementType(ElementEntity, IList, VecType, Index,
1635 StructuredList, StructuredIndex);
1636 numEltsInit += numIElts;
1637 }
1638 }
1639
1640 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001641 if (numEltsInit != maxElements) {
1642 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001643 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001644 diag::err_vector_incorrect_num_initializers)
1645 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1646 hadError = true;
1647 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001648}
1649
Anders Carlsson6cabf312010-01-23 23:23:01 +00001650void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001651 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001652 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001653 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001654 unsigned &Index,
1655 InitListExpr *StructuredList,
1656 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001657 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1658
Steve Narofff8ecff22008-05-01 22:18:59 +00001659 // Check for the special-case of initializing an array with a string.
1660 if (Index < IList->getNumInits()) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001661 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1662 SIF_None) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001663 // We place the string literal directly into the resulting
1664 // initializer list. This is the only place where the structure
1665 // of the structured initializer list doesn't match exactly,
1666 // because doing so would involve allocating one character
1667 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001668 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001669 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1670 UpdateStructuredListElement(StructuredList, StructuredIndex,
1671 IList->getInit(Index));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001672 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1673 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001674 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001675 return;
1676 }
1677 }
John McCall66884dd2011-02-21 07:22:22 +00001678 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001679 // Check for VLAs; in standard C it would be possible to check this
1680 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1681 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001682 if (!VerifyOnly)
1683 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1684 diag::err_variable_object_no_init)
1685 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001686 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001687 ++Index;
1688 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001689 return;
1690 }
1691
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001692 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001693 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1694 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001695 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001696 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001697 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001698 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001699 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001700 maxElementsKnown = true;
1701 }
1702
John McCall66884dd2011-02-21 07:22:22 +00001703 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001704 while (Index < IList->getNumInits()) {
1705 Expr *Init = IList->getInit(Index);
1706 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001707 // If we're not the subobject that matches up with the '{' for
1708 // the designator, we shouldn't be handling the
1709 // designator. Return immediately.
1710 if (!SubobjectIsDesignatorContext)
1711 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001712
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001713 // Handle this designated initializer. elementIndex will be
1714 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001715 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001716 DeclType, nullptr, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001717 StructuredList, StructuredIndex, true,
1718 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001719 hadError = true;
1720 continue;
1721 }
1722
Douglas Gregor033d1252009-01-23 16:54:12 +00001723 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001724 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001725 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001726 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001727 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001728
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001729 // If the array is of incomplete type, keep track of the number of
1730 // elements in the initializer.
1731 if (!maxElementsKnown && elementIndex > maxElements)
1732 maxElements = elementIndex;
1733
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001734 continue;
1735 }
1736
1737 // If we know the maximum number of elements, and we've already
1738 // hit it, stop consuming elements in the initializer list.
1739 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001740 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001741
Anders Carlsson6cabf312010-01-23 23:23:01 +00001742 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001743 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001744 Entity);
1745 // Check this element.
1746 CheckSubElementType(ElementEntity, IList, elementType, Index,
1747 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001748 ++elementIndex;
1749
1750 // If the array is of incomplete type, keep track of the number of
1751 // elements in the initializer.
1752 if (!maxElementsKnown && elementIndex > maxElements)
1753 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001754 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001755 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001756 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001757 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001758 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Richard Smith73edb6d2017-01-24 23:18:28 +00001759 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001760 // Sizing an array implicitly to zero is not allowed by ISO C,
1761 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001762 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001763 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001764 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001765
Mike Stump11289f42009-09-09 15:08:12 +00001766 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001767 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001768 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001769 if (!hadError && VerifyOnly) {
Richard Smith0511d232016-10-05 22:41:02 +00001770 // If there are any members of the array that get value-initialized, check
1771 // that is possible. That happens if we know the bound and don't have
1772 // enough elements, or if we're performing an array new with an unknown
1773 // bound.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001774 // FIXME: This needs to detect holes left by designated initializers too.
Richard Smith0511d232016-10-05 22:41:02 +00001775 if ((maxElementsKnown && elementIndex < maxElements) ||
1776 Entity.isVariableLengthArrayNew())
Richard Smith454a7cd2014-06-03 08:26:00 +00001777 CheckEmptyInitializable(InitializedEntity::InitializeElement(
1778 SemaRef.Context, 0, Entity),
1779 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001780 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001781}
1782
Eli Friedman3fa64df2011-08-23 22:24:57 +00001783bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1784 Expr *InitExpr,
1785 FieldDecl *Field,
1786 bool TopLevelObject) {
1787 // Handle GNU flexible array initializers.
1788 unsigned FlexArrayDiag;
1789 if (isa<InitListExpr>(InitExpr) &&
1790 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1791 // Empty flexible array init always allowed as an extension
1792 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001793 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedman3fa64df2011-08-23 22:24:57 +00001794 // Disallow flexible array init in C++; it is not required for gcc
1795 // compatibility, and it needs work to IRGen correctly in general.
1796 FlexArrayDiag = diag::err_flexible_array_init;
1797 } else if (!TopLevelObject) {
1798 // Disallow flexible array init on non-top-level object
1799 FlexArrayDiag = diag::err_flexible_array_init;
1800 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1801 // Disallow flexible array init on anything which is not a variable.
1802 FlexArrayDiag = diag::err_flexible_array_init;
1803 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1804 // Disallow flexible array init on local variables.
1805 FlexArrayDiag = diag::err_flexible_array_init;
1806 } else {
1807 // Allow other cases.
1808 FlexArrayDiag = diag::ext_flexible_array_init;
1809 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001810
1811 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001812 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001813 FlexArrayDiag)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001814 << InitExpr->getLocStart();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001815 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1816 << Field;
1817 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001818
1819 return FlexArrayDiag != diag::ext_flexible_array_init;
1820}
1821
Richard Smith872307e2016-03-08 22:17:41 +00001822void InitListChecker::CheckStructUnionTypes(
1823 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
1824 CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field,
1825 bool SubobjectIsDesignatorContext, unsigned &Index,
1826 InitListExpr *StructuredList, unsigned &StructuredIndex,
1827 bool TopLevelObject) {
1828 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001829
Eli Friedman23a9e312008-05-19 19:16:24 +00001830 // If the record is invalid, some of it's members are invalid. To avoid
1831 // confusion, we forgo checking the intializer for the entire record.
1832 if (structDecl->isInvalidDecl()) {
Richard Smith845aa662012-09-28 21:23:50 +00001833 // Assume it was supposed to consume a single initializer.
1834 ++Index;
Eli Friedman23a9e312008-05-19 19:16:24 +00001835 hadError = true;
1836 return;
Mike Stump11289f42009-09-09 15:08:12 +00001837 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001838
1839 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001840 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith852c9db2013-04-20 22:23:05 +00001841
1842 // If there's a default initializer, use it.
1843 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1844 if (VerifyOnly)
1845 return;
1846 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1847 Field != FieldEnd; ++Field) {
1848 if (Field->hasInClassInitializer()) {
1849 StructuredList->setInitializedFieldInUnion(*Field);
1850 // FIXME: Actually build a CXXDefaultInitExpr?
1851 return;
1852 }
1853 }
1854 }
1855
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001856 // Value-initialize the first member of the union that isn't an unnamed
1857 // bitfield.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001858 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1859 Field != FieldEnd; ++Field) {
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001860 if (!Field->isUnnamedBitfield()) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001861 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001862 CheckEmptyInitializable(
1863 InitializedEntity::InitializeMember(*Field, &Entity),
1864 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001865 else
David Blaikie40ed2972012-06-06 20:45:41 +00001866 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001867 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001868 }
1869 }
1870 return;
1871 }
1872
Richard Smith872307e2016-03-08 22:17:41 +00001873 bool InitializedSomething = false;
1874
1875 // If we have any base classes, they are initialized prior to the fields.
1876 for (auto &Base : Bases) {
1877 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
1878 SourceLocation InitLoc = Init ? Init->getLocStart() : IList->getLocEnd();
1879
1880 // Designated inits always initialize fields, so if we see one, all
1881 // remaining base classes have no explicit initializer.
1882 if (Init && isa<DesignatedInitExpr>(Init))
1883 Init = nullptr;
1884
1885 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
1886 SemaRef.Context, &Base, false, &Entity);
1887 if (Init) {
1888 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
1889 StructuredList, StructuredIndex);
1890 InitializedSomething = true;
1891 } else if (VerifyOnly) {
1892 CheckEmptyInitializable(BaseEntity, InitLoc);
1893 }
1894 }
1895
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001896 // If structDecl is a forward declaration, this loop won't do
1897 // anything except look at designated initializers; That's okay,
1898 // because an error should get printed out elsewhere. It might be
1899 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001900 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001901 RecordDecl::field_iterator FieldEnd = RD->field_end();
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00001902 bool CheckForMissingFields =
1903 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
1904
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001905 while (Index < IList->getNumInits()) {
1906 Expr *Init = IList->getInit(Index);
1907
1908 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001909 // If we're not the subobject that matches up with the '{' for
1910 // the designator, we shouldn't be handling the
1911 // designator. Return immediately.
1912 if (!SubobjectIsDesignatorContext)
1913 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001914
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001915 // Handle this designated initializer. Field will be updated to
1916 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001917 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001918 DeclType, &Field, nullptr, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001919 StructuredList, StructuredIndex,
1920 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001921 hadError = true;
1922
Douglas Gregora9add4e2009-02-12 19:00:39 +00001923 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001924
1925 // Disable check for missing fields when designators are used.
1926 // This matches gcc behaviour.
1927 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001928 continue;
1929 }
1930
1931 if (Field == FieldEnd) {
1932 // We've run out of fields. We're done.
1933 break;
1934 }
1935
Douglas Gregora9add4e2009-02-12 19:00:39 +00001936 // We've already initialized a member of a union. We're done.
1937 if (InitializedSomething && DeclType->isUnionType())
1938 break;
1939
Douglas Gregor91f84212008-12-11 16:49:14 +00001940 // If we've hit the flexible array member at the end, we're done.
1941 if (Field->getType()->isIncompleteArrayType())
1942 break;
1943
Douglas Gregor51695702009-01-29 16:53:55 +00001944 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001945 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001946 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001947 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001948 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001949
Douglas Gregora82064c2011-06-29 21:51:31 +00001950 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001951 bool InvalidUse;
1952 if (VerifyOnly)
Manman Ren073db022016-03-10 18:53:19 +00001953 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001954 else
David Blaikie40ed2972012-06-06 20:45:41 +00001955 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001956 IList->getInit(Index)->getLocStart());
1957 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001958 ++Index;
1959 ++Field;
1960 hadError = true;
1961 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001962 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001963
Anders Carlsson6cabf312010-01-23 23:23:01 +00001964 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001965 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001966 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1967 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001968 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001969
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001970 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001971 // Initialize the first field within the union.
David Blaikie40ed2972012-06-06 20:45:41 +00001972 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001973 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001974
1975 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001976 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001977
John McCalle40b58e2010-03-11 19:32:38 +00001978 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001979 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1980 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1981 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001982 // It is possible we have one or more unnamed bitfields remaining.
1983 // Find first (if any) named field and emit warning.
1984 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1985 it != end; ++it) {
Richard Smith852c9db2013-04-20 22:23:05 +00001986 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCalle40b58e2010-03-11 19:32:38 +00001987 SemaRef.Diag(IList->getSourceRange().getEnd(),
Aaron Ballmanb9bb2012014-01-03 14:54:10 +00001988 diag::warn_missing_field_initializers) << *it;
John McCalle40b58e2010-03-11 19:32:38 +00001989 break;
1990 }
1991 }
1992 }
1993
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001994 // Check that any remaining fields can be value-initialized.
1995 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1996 !Field->getType()->isIncompleteArrayType()) {
1997 // FIXME: Should check for holes left by designated initializers too.
1998 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smith852c9db2013-04-20 22:23:05 +00001999 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Richard Smith454a7cd2014-06-03 08:26:00 +00002000 CheckEmptyInitializable(
2001 InitializedEntity::InitializeMember(*Field, &Entity),
2002 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00002003 }
2004 }
2005
Mike Stump11289f42009-09-09 15:08:12 +00002006 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00002007 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002008 return;
2009
David Blaikie40ed2972012-06-06 20:45:41 +00002010 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00002011 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002012 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00002013 ++Index;
2014 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002015 }
2016
Anders Carlsson6cabf312010-01-23 23:23:01 +00002017 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002018 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002019
Anders Carlsson6cabf312010-01-23 23:23:01 +00002020 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002021 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00002022 StructuredList, StructuredIndex);
2023 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002024 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00002025 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00002026}
Steve Narofff8ecff22008-05-01 22:18:59 +00002027
Douglas Gregord5846a12009-04-15 06:41:24 +00002028/// \brief Expand a field designator that refers to a member of an
2029/// anonymous struct or union into a series of field designators that
2030/// refers to the field within the appropriate subobject.
2031///
Douglas Gregord5846a12009-04-15 06:41:24 +00002032static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00002033 DesignatedInitExpr *DIE,
2034 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002035 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00002036 typedef DesignatedInitExpr::Designator Designator;
2037
Douglas Gregord5846a12009-04-15 06:41:24 +00002038 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002039 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002040 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2041 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2042 if (PI + 1 == PE)
Craig Topperc3ec1492014-05-26 06:22:03 +00002043 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
Douglas Gregord5846a12009-04-15 06:41:24 +00002044 DIE->getDesignator(DesigIdx)->getDotLoc(),
2045 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2046 else
Craig Topperc3ec1492014-05-26 06:22:03 +00002047 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2048 SourceLocation(), SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002049 assert(isa<FieldDecl>(*PI));
2050 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00002051 }
2052
2053 // Expand the current designator into the set of replacement
2054 // designators, so we have a full subobject path down to where the
2055 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00002056 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00002057 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002058}
Mike Stump11289f42009-09-09 15:08:12 +00002059
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002060static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
2061 DesignatedInitExpr *DIE) {
2062 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2063 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2064 for (unsigned I = 0; I < NumIndexExprs; ++I)
2065 IndexExprs[I] = DIE->getSubExpr(I + 1);
David Majnemerf7e36092016-06-23 00:15:04 +00002066 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2067 IndexExprs,
Benjamin Kramerc215e762012-08-24 11:54:20 +00002068 DIE->getEqualOrColonLoc(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002069 DIE->usesGNUSyntax(), DIE->getInit());
2070}
2071
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002072namespace {
2073
2074// Callback to only accept typo corrections that are for field members of
2075// the given struct or union.
2076class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
2077 public:
2078 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
2079 : Record(RD) {}
2080
Craig Toppere14c0f82014-03-12 04:55:44 +00002081 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002082 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2083 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2084 }
2085
2086 private:
2087 RecordDecl *Record;
2088};
2089
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002090} // end anonymous namespace
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002091
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002092/// @brief Check the well-formedness of a C99 designated initializer.
2093///
2094/// Determines whether the designated initializer @p DIE, which
2095/// resides at the given @p Index within the initializer list @p
2096/// IList, is well-formed for a current object of type @p DeclType
2097/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00002098/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002099/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002100///
2101/// @param IList The initializer list in which this designated
2102/// initializer occurs.
2103///
Douglas Gregora5324162009-04-15 04:56:10 +00002104/// @param DIE The designated initializer expression.
2105///
2106/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002107///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002108/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002109/// into which the designation in @p DIE should refer.
2110///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002111/// @param NextField If non-NULL and the first designator in @p DIE is
2112/// a field, this will be set to the field declaration corresponding
2113/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002114///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002115/// @param NextElementIndex If non-NULL and the first designator in @p
2116/// DIE is an array designator or GNU array-range designator, this
2117/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002118///
2119/// @param Index Index into @p IList where the designated initializer
2120/// @p DIE occurs.
2121///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002122/// @param StructuredList The initializer list expression that
2123/// describes all of the subobject initializers in the order they'll
2124/// actually be initialized.
2125///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002126/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002127bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00002128InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002129 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002130 DesignatedInitExpr *DIE,
2131 unsigned DesigIdx,
2132 QualType &CurrentObjectType,
2133 RecordDecl::field_iterator *NextField,
2134 llvm::APSInt *NextElementIndex,
2135 unsigned &Index,
2136 InitListExpr *StructuredList,
2137 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002138 bool FinishSubobjectInit,
2139 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00002140 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002141 // Check the actual initialization for the designated object type.
2142 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00002143
2144 // Temporarily remove the designator expression from the
2145 // initializer list that the child calls see, so that we don't try
2146 // to re-process the designator.
2147 unsigned OldIndex = Index;
2148 IList->setInit(OldIndex, DIE->getInit());
2149
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002150 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002151 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00002152
2153 // Restore the designated initializer expression in the syntactic
2154 // form of the initializer list.
2155 if (IList->getInit(OldIndex) != DIE->getInit())
2156 DIE->setInit(IList->getInit(OldIndex));
2157 IList->setInit(OldIndex, DIE);
2158
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002159 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002160 }
2161
Douglas Gregora5324162009-04-15 04:56:10 +00002162 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002163 bool IsFirstDesignator = (DesigIdx == 0);
2164 if (!VerifyOnly) {
2165 assert((IsFirstDesignator || StructuredList) &&
2166 "Need a non-designated initializer list to start from");
2167
2168 // Determine the structural initializer list that corresponds to the
2169 // current subobject.
Yunzhong Gaocb779302015-06-10 00:27:52 +00002170 if (IsFirstDesignator)
2171 StructuredList = SyntacticToSemantic.lookup(IList);
2172 else {
2173 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2174 StructuredList->getInit(StructuredIndex) : nullptr;
2175 if (!ExistingInit && StructuredList->hasArrayFiller())
2176 ExistingInit = StructuredList->getArrayFiller();
2177
2178 if (!ExistingInit)
2179 StructuredList =
2180 getStructuredSubobjectInit(IList, Index, CurrentObjectType,
2181 StructuredList, StructuredIndex,
2182 SourceRange(D->getLocStart(),
2183 DIE->getLocEnd()));
2184 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2185 StructuredList = Result;
2186 else {
2187 if (DesignatedInitUpdateExpr *E =
2188 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2189 StructuredList = E->getUpdater();
2190 else {
2191 DesignatedInitUpdateExpr *DIUE =
2192 new (SemaRef.Context) DesignatedInitUpdateExpr(SemaRef.Context,
2193 D->getLocStart(), ExistingInit,
2194 DIE->getLocEnd());
2195 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2196 StructuredList = DIUE->getUpdater();
2197 }
2198
2199 // We need to check on source range validity because the previous
2200 // initializer does not have to be an explicit initializer. e.g.,
2201 //
2202 // struct P { int a, b; };
2203 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2204 //
2205 // There is an overwrite taking place because the first braced initializer
2206 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
2207 if (ExistingInit->getSourceRange().isValid()) {
2208 // We are creating an initializer list that initializes the
2209 // subobjects of the current object, but there was already an
2210 // initialization that completely initialized the current
2211 // subobject, e.g., by a compound literal:
2212 //
2213 // struct X { int a, b; };
2214 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2215 //
2216 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2217 // designated initializer re-initializes the whole
2218 // subobject [0], overwriting previous initializers.
2219 SemaRef.Diag(D->getLocStart(),
2220 diag::warn_subobject_initializer_overrides)
2221 << SourceRange(D->getLocStart(), DIE->getLocEnd());
2222
2223 SemaRef.Diag(ExistingInit->getLocStart(),
2224 diag::note_previous_initializer)
2225 << /*FIXME:has side effects=*/0
2226 << ExistingInit->getSourceRange();
2227 }
2228 }
2229 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002230 assert(StructuredList && "Expected a structured initializer list");
2231 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002232
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002233 if (D->isFieldDesignator()) {
2234 // C99 6.7.8p7:
2235 //
2236 // If a designator has the form
2237 //
2238 // . identifier
2239 //
2240 // then the current object (defined below) shall have
2241 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00002242 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002243 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002244 if (!RT) {
2245 SourceLocation Loc = D->getDotLoc();
2246 if (Loc.isInvalid())
2247 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002248 if (!VerifyOnly)
2249 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002250 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002251 ++Index;
2252 return true;
2253 }
2254
Douglas Gregord5846a12009-04-15 06:41:24 +00002255 FieldDecl *KnownField = D->getField();
David Majnemer36ef8982014-08-11 18:33:59 +00002256 if (!KnownField) {
2257 IdentifierInfo *FieldName = D->getFieldName();
2258 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
2259 for (NamedDecl *ND : Lookup) {
2260 if (auto *FD = dyn_cast<FieldDecl>(ND)) {
2261 KnownField = FD;
2262 break;
2263 }
2264 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002265 // In verify mode, don't modify the original.
2266 if (VerifyOnly)
2267 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
David Majnemer36ef8982014-08-11 18:33:59 +00002268 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002269 D = DIE->getDesignator(DesigIdx);
David Majnemer36ef8982014-08-11 18:33:59 +00002270 KnownField = cast<FieldDecl>(*IFD->chain_begin());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002271 break;
2272 }
2273 }
David Majnemer36ef8982014-08-11 18:33:59 +00002274 if (!KnownField) {
2275 if (VerifyOnly) {
2276 ++Index;
2277 return true; // No typo correction when just trying this out.
2278 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002279
David Majnemer36ef8982014-08-11 18:33:59 +00002280 // Name lookup found something, but it wasn't a field.
2281 if (!Lookup.empty()) {
2282 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2283 << FieldName;
2284 SemaRef.Diag(Lookup.front()->getLocation(),
2285 diag::note_field_designator_found);
2286 ++Index;
2287 return true;
2288 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002289
David Majnemer36ef8982014-08-11 18:33:59 +00002290 // Name lookup didn't find anything.
2291 // Determine whether this was a typo for another field name.
Richard Smithf9b15102013-08-17 00:46:16 +00002292 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2293 DeclarationNameInfo(FieldName, D->getFieldLoc()),
David Majnemer36ef8982014-08-11 18:33:59 +00002294 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002295 llvm::make_unique<FieldInitializerValidatorCCC>(RT->getDecl()),
2296 Sema::CTK_ErrorRecovery, RT->getDecl())) {
Richard Smithf9b15102013-08-17 00:46:16 +00002297 SemaRef.diagnoseTypo(
2298 Corrected,
2299 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
David Majnemer36ef8982014-08-11 18:33:59 +00002300 << FieldName << CurrentObjectType);
2301 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
Benjamin Kramerafe718f2011-09-25 02:41:26 +00002302 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002303 } else {
David Majnemer36ef8982014-08-11 18:33:59 +00002304 // Typo correction didn't find anything.
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002305 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
2306 << FieldName << CurrentObjectType;
2307 ++Index;
2308 return true;
2309 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002310 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002311 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002312
David Majnemer58e4ea92014-08-23 01:48:50 +00002313 unsigned FieldIndex = 0;
Akira Hatanaka8eccb9b2017-01-17 19:35:54 +00002314
2315 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2316 FieldIndex = CXXRD->getNumBases();
2317
David Majnemer58e4ea92014-08-23 01:48:50 +00002318 for (auto *FI : RT->getDecl()->fields()) {
2319 if (FI->isUnnamedBitfield())
2320 continue;
Richard Smithfe1bc702016-04-08 19:57:40 +00002321 if (declaresSameEntity(KnownField, FI)) {
2322 KnownField = FI;
David Majnemer58e4ea92014-08-23 01:48:50 +00002323 break;
Richard Smithfe1bc702016-04-08 19:57:40 +00002324 }
David Majnemer58e4ea92014-08-23 01:48:50 +00002325 ++FieldIndex;
2326 }
2327
David Majnemer36ef8982014-08-11 18:33:59 +00002328 RecordDecl::field_iterator Field =
2329 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2330
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002331 // All of the fields of a union are located at the same place in
2332 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00002333 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002334 FieldIndex = 0;
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002335 if (!VerifyOnly) {
2336 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
Richard Smithfe1bc702016-04-08 19:57:40 +00002337 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002338 assert(StructuredList->getNumInits() == 1
2339 && "A union should never have more than one initializer!");
2340
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002341 Expr *ExistingInit = StructuredList->getInit(0);
Vassil Vassilev1a1678e2017-04-14 08:48:08 +00002342 if (ExistingInit) {
2343 // We're about to throw away an initializer, emit warning.
2344 SemaRef.Diag(D->getFieldLoc(),
2345 diag::warn_initializer_overrides)
2346 << D->getSourceRange();
2347 SemaRef.Diag(ExistingInit->getLocStart(),
2348 diag::note_previous_initializer)
2349 << /*FIXME:has side effects=*/0
2350 << ExistingInit->getSourceRange();
2351 }
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002352
2353 // remove existing initializer
2354 StructuredList->resizeInits(SemaRef.Context, 0);
Craig Topperc3ec1492014-05-26 06:22:03 +00002355 StructuredList->setInitializedFieldInUnion(nullptr);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002356 }
2357
David Blaikie40ed2972012-06-06 20:45:41 +00002358 StructuredList->setInitializedFieldInUnion(*Field);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002359 }
Douglas Gregor51695702009-01-29 16:53:55 +00002360 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002361
Douglas Gregora82064c2011-06-29 21:51:31 +00002362 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002363 bool InvalidUse;
2364 if (VerifyOnly)
Manman Ren073db022016-03-10 18:53:19 +00002365 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002366 else
David Blaikie40ed2972012-06-06 20:45:41 +00002367 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002368 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00002369 ++Index;
2370 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002371 }
Douglas Gregora82064c2011-06-29 21:51:31 +00002372
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002373 if (!VerifyOnly) {
2374 // Update the designator with the field declaration.
David Blaikie40ed2972012-06-06 20:45:41 +00002375 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00002376
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002377 // Make sure that our non-designated initializer list has space
2378 // for a subobject corresponding to this field.
2379 if (FieldIndex >= StructuredList->getNumInits())
2380 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2381 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002382
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002383 // This designator names a flexible array member.
2384 if (Field->getType()->isIncompleteArrayType()) {
2385 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00002386 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002387 // We can't designate an object within the flexible array
2388 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002389 if (!VerifyOnly) {
2390 DesignatedInitExpr::Designator *NextD
2391 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002392 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002393 diag::err_designator_into_flexible_array_member)
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002394 << SourceRange(NextD->getLocStart(),
2395 DIE->getLocEnd());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002396 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002397 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002398 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002399 Invalid = true;
2400 }
2401
Chris Lattner001b29c2010-10-10 17:49:49 +00002402 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2403 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002404 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002405 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002406 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002407 diag::err_flexible_array_init_needs_braces)
2408 << DIE->getInit()->getSourceRange();
2409 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002410 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002411 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002412 Invalid = true;
2413 }
2414
Eli Friedman3fa64df2011-08-23 22:24:57 +00002415 // Check GNU flexible array initializer.
David Blaikie40ed2972012-06-06 20:45:41 +00002416 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00002417 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002418 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002419
2420 if (Invalid) {
2421 ++Index;
2422 return true;
2423 }
2424
2425 // Initialize the array.
2426 bool prevHadError = hadError;
2427 unsigned newStructuredIndex = FieldIndex;
2428 unsigned OldIndex = Index;
2429 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00002430
2431 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002432 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002433 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002434 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002435
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002436 IList->setInit(OldIndex, DIE);
2437 if (hadError && !prevHadError) {
2438 ++Field;
2439 ++FieldIndex;
2440 if (NextField)
2441 *NextField = Field;
2442 StructuredIndex = FieldIndex;
2443 return true;
2444 }
2445 } else {
2446 // Recurse to check later designated subobjects.
David Blaikie2d7c57e2012-04-30 02:36:29 +00002447 QualType FieldType = Field->getType();
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002448 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002449
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002450 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002451 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002452 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002453 FieldType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002454 StructuredList, newStructuredIndex,
Alexey Bataev86a489e2016-01-25 05:14:03 +00002455 FinishSubobjectInit, false))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002456 return true;
2457 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002458
2459 // Find the position of the next field to be initialized in this
2460 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002461 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002462 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002463
2464 // If this the first designator, our caller will continue checking
2465 // the rest of this struct/class/union subobject.
2466 if (IsFirstDesignator) {
2467 if (NextField)
2468 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002469 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002470 return false;
2471 }
2472
Douglas Gregor17bd0942009-01-28 23:36:17 +00002473 if (!FinishSubobjectInit)
2474 return false;
2475
Douglas Gregord5846a12009-04-15 06:41:24 +00002476 // We've already initialized something in the union; we're done.
2477 if (RT->getDecl()->isUnion())
2478 return hadError;
2479
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002480 // Check the remaining fields within this class/struct/union subobject.
2481 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002482
Richard Smith872307e2016-03-08 22:17:41 +00002483 auto NoBases =
2484 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
2485 CXXRecordDecl::base_class_iterator());
2486 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2487 false, Index, StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002488 return hadError && !prevHadError;
2489 }
2490
2491 // C99 6.7.8p6:
2492 //
2493 // If a designator has the form
2494 //
2495 // [ constant-expression ]
2496 //
2497 // then the current object (defined below) shall have array
2498 // type and the expression shall be an integer constant
2499 // expression. If the array is of unknown size, any
2500 // nonnegative value is valid.
2501 //
2502 // Additionally, cope with the GNU extension that permits
2503 // designators of the form
2504 //
2505 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00002506 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002507 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002508 if (!VerifyOnly)
2509 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2510 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002511 ++Index;
2512 return true;
2513 }
2514
Craig Topperc3ec1492014-05-26 06:22:03 +00002515 Expr *IndexExpr = nullptr;
Douglas Gregor17bd0942009-01-28 23:36:17 +00002516 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2517 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002518 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00002519 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002520 DesignatedEndIndex = DesignatedStartIndex;
2521 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002522 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00002523
Mike Stump11289f42009-09-09 15:08:12 +00002524 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002525 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002526 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002527 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002528 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002529
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00002530 // Codegen can't handle evaluating array range designators that have side
2531 // effects, because we replicate the AST value for each initialized element.
2532 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2533 // elements with something that has a side effect, so codegen can emit an
2534 // "error unsupported" error instead of miscompiling the app.
2535 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002536 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00002537 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002538 }
2539
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002540 if (isa<ConstantArrayType>(AT)) {
2541 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002542 DesignatedStartIndex
2543 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002544 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00002545 DesignatedEndIndex
2546 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002547 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2548 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00002549 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002550 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002551 diag::err_array_designator_too_large)
2552 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2553 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002554 ++Index;
2555 return true;
2556 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00002557 } else {
Argyrios Kyrtzidis4746c2f2015-07-27 23:16:53 +00002558 unsigned DesignatedIndexBitWidth =
2559 ConstantArrayType::getMaxSizeBits(SemaRef.Context);
2560 DesignatedStartIndex =
2561 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
2562 DesignatedEndIndex =
2563 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002564 DesignatedStartIndex.setIsUnsigned(true);
2565 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002566 }
Mike Stump11289f42009-09-09 15:08:12 +00002567
Eli Friedman1f16b742013-06-11 21:48:11 +00002568 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2569 // We're modifying a string literal init; we have to decompose the string
2570 // so we can modify the individual characters.
2571 ASTContext &Context = SemaRef.Context;
2572 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2573
2574 // Compute the character type
2575 QualType CharTy = AT->getElementType();
2576
2577 // Compute the type of the integer literals.
2578 QualType PromotedCharTy = CharTy;
2579 if (CharTy->isPromotableIntegerType())
2580 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2581 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2582
2583 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2584 // Get the length of the string.
2585 uint64_t StrLen = SL->getLength();
2586 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2587 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2588 StructuredList->resizeInits(Context, StrLen);
2589
2590 // Build a literal for each character in the string, and put them into
2591 // the init list.
2592 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2593 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2594 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002595 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002596 if (CharTy != PromotedCharTy)
2597 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002598 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002599 StructuredList->updateInit(Context, i, Init);
2600 }
2601 } else {
2602 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2603 std::string Str;
2604 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2605
2606 // Get the length of the string.
2607 uint64_t StrLen = Str.size();
2608 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2609 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2610 StructuredList->resizeInits(Context, StrLen);
2611
2612 // Build a literal for each character in the string, and put them into
2613 // the init list.
2614 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2615 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2616 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002617 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002618 if (CharTy != PromotedCharTy)
2619 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002620 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002621 StructuredList->updateInit(Context, i, Init);
2622 }
2623 }
2624 }
2625
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002626 // Make sure that our non-designated initializer list has space
2627 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002628 if (!VerifyOnly &&
2629 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00002630 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00002631 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002632
Douglas Gregor17bd0942009-01-28 23:36:17 +00002633 // Repeatedly perform subobject initializations in the range
2634 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002635
Douglas Gregor17bd0942009-01-28 23:36:17 +00002636 // Move to the next designator
2637 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2638 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002639
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002640 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00002641 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002642
Douglas Gregor17bd0942009-01-28 23:36:17 +00002643 while (DesignatedStartIndex <= DesignatedEndIndex) {
2644 // Recurse to check later designated subobjects.
2645 QualType ElementType = AT->getElementType();
2646 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002647
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002648 ElementEntity.setElementIndex(ElementIndex);
Alexey Bataev86a489e2016-01-25 05:14:03 +00002649 if (CheckDesignatedInitializer(
2650 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
2651 nullptr, Index, StructuredList, ElementIndex,
2652 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
2653 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002654 return true;
2655
2656 // Move to the next index in the array that we'll be initializing.
2657 ++DesignatedStartIndex;
2658 ElementIndex = DesignatedStartIndex.getZExtValue();
2659 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002660
2661 // If this the first designator, our caller will continue checking
2662 // the rest of this array subobject.
2663 if (IsFirstDesignator) {
2664 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002665 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002666 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002667 return false;
2668 }
Mike Stump11289f42009-09-09 15:08:12 +00002669
Douglas Gregor17bd0942009-01-28 23:36:17 +00002670 if (!FinishSubobjectInit)
2671 return false;
2672
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002673 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002674 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002675 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002676 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002677 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002678 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002679}
2680
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002681// Get the structured initializer list for a subobject of type
2682// @p CurrentObjectType.
2683InitListExpr *
2684InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2685 QualType CurrentObjectType,
2686 InitListExpr *StructuredList,
2687 unsigned StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +00002688 SourceRange InitRange,
2689 bool IsFullyOverwritten) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002690 if (VerifyOnly)
Craig Topperc3ec1492014-05-26 06:22:03 +00002691 return nullptr; // No structured list in verification-only mode.
2692 Expr *ExistingInit = nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002693 if (!StructuredList)
Benjamin Kramer6b441d62012-02-23 14:48:40 +00002694 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002695 else if (StructuredIndex < StructuredList->getNumInits())
2696 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002697
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002698 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
Yunzhong Gaocb779302015-06-10 00:27:52 +00002699 // There might have already been initializers for subobjects of the current
2700 // object, but a subsequent initializer list will overwrite the entirety
2701 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
2702 //
2703 // struct P { char x[6]; };
2704 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
2705 //
2706 // The first designated initializer is ignored, and l.x is just "f".
2707 if (!IsFullyOverwritten)
2708 return Result;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002709
2710 if (ExistingInit) {
2711 // We are creating an initializer list that initializes the
2712 // subobjects of the current object, but there was already an
2713 // initialization that completely initialized the current
2714 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002715 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002716 // struct X { int a, b; };
2717 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002718 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002719 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2720 // designated initializer re-initializes the whole
2721 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002722 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002723 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002724 << InitRange;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002725 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002726 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002727 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002728 << ExistingInit->getSourceRange();
2729 }
2730
Mike Stump11289f42009-09-09 15:08:12 +00002731 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002732 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko78852e92013-05-05 20:40:26 +00002733 InitRange.getBegin(), None,
Ted Kremenek013041e2010-02-19 01:50:18 +00002734 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002735
Eli Friedman91f5ae52012-02-23 02:25:10 +00002736 QualType ResultType = CurrentObjectType;
2737 if (!ResultType->isArrayType())
2738 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2739 Result->setType(ResultType);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002740
Douglas Gregor6d00c992009-03-20 23:58:33 +00002741 // Pre-allocate storage for the structured initializer list.
2742 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002743 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002744 bool GotNumInits = false;
2745 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002746 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002747 GotNumInits = true;
2748 } else if (Index < IList->getNumInits()) {
2749 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002750 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002751 GotNumInits = true;
2752 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002753 }
2754
Mike Stump11289f42009-09-09 15:08:12 +00002755 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002756 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2757 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2758 NumElements = CAType->getSize().getZExtValue();
2759 // Simple heuristic so that we don't allocate a very large
2760 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002761 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002762 NumElements = 0;
2763 }
John McCall9dd450b2009-09-21 23:43:11 +00002764 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002765 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002766 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002767 RecordDecl *RDecl = RType->getDecl();
2768 if (RDecl->isUnion())
2769 NumElements = 1;
2770 else
Aaron Ballman62e47c42014-03-10 13:43:55 +00002771 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002772 }
2773
Ted Kremenekac034612010-04-13 23:39:13 +00002774 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002775
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002776 // Link this new initializer list into the structured initializer
2777 // lists.
2778 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002779 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002780 else {
2781 Result->setSyntacticForm(IList);
2782 SyntacticToSemantic[IList] = Result;
2783 }
2784
2785 return Result;
2786}
2787
2788/// Update the initializer at index @p StructuredIndex within the
2789/// structured initializer list to the value @p expr.
2790void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2791 unsigned &StructuredIndex,
2792 Expr *expr) {
2793 // No structured initializer list to update
2794 if (!StructuredList)
2795 return;
2796
Ted Kremenekac034612010-04-13 23:39:13 +00002797 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2798 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002799 // This initializer overwrites a previous initializer. Warn.
Yunzhong Gaocb779302015-06-10 00:27:52 +00002800 // We need to check on source range validity because the previous
2801 // initializer does not have to be an explicit initializer.
2802 // struct P { int a, b; };
2803 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2804 // There is an overwrite taking place because the first braced initializer
2805 // list "{ .a = 2 }' already provides value for .p.b (which is zero).
2806 if (PrevInit->getSourceRange().isValid()) {
2807 SemaRef.Diag(expr->getLocStart(),
2808 diag::warn_initializer_overrides)
2809 << expr->getSourceRange();
2810
2811 SemaRef.Diag(PrevInit->getLocStart(),
2812 diag::note_previous_initializer)
2813 << /*FIXME:has side effects=*/0
2814 << PrevInit->getSourceRange();
2815 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002816 }
Mike Stump11289f42009-09-09 15:08:12 +00002817
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002818 ++StructuredIndex;
2819}
2820
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002821/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002822/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002823/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002824/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002825/// failure. Returns the index expression, possibly with an implicit cast
2826/// added, on success. If everything went okay, Value will receive the
2827/// value of the constant expression.
2828static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002829CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002830 SourceLocation Loc = Index->getLocStart();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002831
2832 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002833 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2834 if (Result.isInvalid())
2835 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002836
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002837 if (Value.isSigned() && Value.isNegative())
2838 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002839 << Value.toString(10) << Index->getSourceRange();
2840
Douglas Gregor51650d32009-01-23 21:04:18 +00002841 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002842 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002843}
2844
John McCalldadc5752010-08-24 06:29:42 +00002845ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002846 SourceLocation Loc,
2847 bool GNUSyntax,
2848 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002849 typedef DesignatedInitExpr::Designator ASTDesignator;
2850
2851 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002852 SmallVector<ASTDesignator, 32> Designators;
2853 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002854
2855 // Build designators and check array designator expressions.
2856 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2857 const Designator &D = Desig.getDesignator(Idx);
2858 switch (D.getKind()) {
2859 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002860 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002861 D.getFieldLoc()));
2862 break;
2863
2864 case Designator::ArrayDesignator: {
2865 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2866 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00002867 if (!Index->isTypeDependent() && !Index->isValueDependent())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002868 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002869 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002870 Invalid = true;
2871 else {
2872 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002873 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002874 D.getRBracketLoc()));
2875 InitExpressions.push_back(Index);
2876 }
2877 break;
2878 }
2879
2880 case Designator::ArrayRangeDesignator: {
2881 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2882 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2883 llvm::APSInt StartValue;
2884 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002885 bool StartDependent = StartIndex->isTypeDependent() ||
2886 StartIndex->isValueDependent();
2887 bool EndDependent = EndIndex->isTypeDependent() ||
2888 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00002889 if (!StartDependent)
2890 StartIndex =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002891 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002892 if (!EndDependent)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002893 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002894
2895 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002896 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002897 else {
2898 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002899 if (StartDependent || EndDependent) {
2900 // Nothing to compute.
2901 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002902 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002903 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002904 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002905
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002906 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002907 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002908 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002909 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2910 Invalid = true;
2911 } else {
2912 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002913 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002914 D.getEllipsisLoc(),
2915 D.getRBracketLoc()));
2916 InitExpressions.push_back(StartIndex);
2917 InitExpressions.push_back(EndIndex);
2918 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002919 }
2920 break;
2921 }
2922 }
2923 }
2924
2925 if (Invalid || Init.isInvalid())
2926 return ExprError();
2927
2928 // Clear out the expressions within the designation.
2929 Desig.ClearExprs(*this);
2930
2931 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002932 = DesignatedInitExpr::Create(Context,
David Majnemerf7e36092016-06-23 00:15:04 +00002933 Designators,
Benjamin Kramerc215e762012-08-24 11:54:20 +00002934 InitExpressions, Loc, GNUSyntax,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002935 Init.getAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002936
David Blaikiebbafb8a2012-03-11 07:00:24 +00002937 if (!getLangOpts().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002938 Diag(DIE->getLocStart(), diag::ext_designated_init)
2939 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002940
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002941 return DIE;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002942}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002943
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002944//===----------------------------------------------------------------------===//
2945// Initialization entity
2946//===----------------------------------------------------------------------===//
2947
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002948InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002949 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002950 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002951{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002952 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2953 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002954 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002955 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002956 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002957 Type = VT->getElementType();
2958 } else {
2959 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2960 assert(CT && "Unexpected type");
2961 Kind = EK_ComplexElement;
2962 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002963 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002964}
2965
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002966InitializedEntity
2967InitializedEntity::InitializeBase(ASTContext &Context,
2968 const CXXBaseSpecifier *Base,
Richard Smith872307e2016-03-08 22:17:41 +00002969 bool IsInheritedVirtualBase,
2970 const InitializedEntity *Parent) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002971 InitializedEntity Result;
2972 Result.Kind = EK_Base;
Richard Smith872307e2016-03-08 22:17:41 +00002973 Result.Parent = Parent;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002974 Result.Base = reinterpret_cast<uintptr_t>(Base);
2975 if (IsInheritedVirtualBase)
2976 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002977
Douglas Gregor1b303932009-12-22 15:35:07 +00002978 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002979 return Result;
2980}
2981
Douglas Gregor85dabae2009-12-16 01:38:02 +00002982DeclarationName InitializedEntity::getName() const {
2983 switch (getKind()) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002984 case EK_Parameter:
2985 case EK_Parameter_CF_Audited: {
John McCall31168b02011-06-15 23:02:42 +00002986 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2987 return (D ? D->getDeclName() : DeclarationName());
2988 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002989
2990 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002991 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00002992 case EK_Binding:
Richard Smith410306b2016-12-12 02:53:20 +00002993 return Variable.VariableOrMember->getDeclName();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002994
Douglas Gregor19666fb2012-02-15 16:57:26 +00002995 case EK_LambdaCapture:
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00002996 return DeclarationName(Capture.VarID);
Douglas Gregor19666fb2012-02-15 16:57:26 +00002997
Douglas Gregor85dabae2009-12-16 01:38:02 +00002998 case EK_Result:
2999 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003000 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00003001 case EK_Temporary:
3002 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003003 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003004 case EK_ArrayElement:
3005 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003006 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003007 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00003008 case EK_LambdaToBlockConversionBlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00003009 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003010 case EK_RelatedResult:
Douglas Gregor85dabae2009-12-16 01:38:02 +00003011 return DeclarationName();
3012 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003013
David Blaikie8a40f702012-01-17 06:56:22 +00003014 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00003015}
3016
Richard Smith7873de02016-08-11 22:25:46 +00003017ValueDecl *InitializedEntity::getDecl() const {
Douglas Gregora4b592a2009-12-19 03:01:41 +00003018 switch (getKind()) {
3019 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003020 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00003021 case EK_Binding:
Richard Smith410306b2016-12-12 02:53:20 +00003022 return Variable.VariableOrMember;
Douglas Gregora4b592a2009-12-19 03:01:41 +00003023
John McCall31168b02011-06-15 23:02:42 +00003024 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003025 case EK_Parameter_CF_Audited:
John McCall31168b02011-06-15 23:02:42 +00003026 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
3027
Douglas Gregora4b592a2009-12-19 03:01:41 +00003028 case EK_Result:
3029 case EK_Exception:
3030 case EK_New:
3031 case EK_Temporary:
3032 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003033 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003034 case EK_ArrayElement:
3035 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003036 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003037 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00003038 case EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00003039 case EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00003040 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003041 case EK_RelatedResult:
Craig Topperc3ec1492014-05-26 06:22:03 +00003042 return nullptr;
Douglas Gregora4b592a2009-12-19 03:01:41 +00003043 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003044
David Blaikie8a40f702012-01-17 06:56:22 +00003045 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00003046}
3047
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003048bool InitializedEntity::allowsNRVO() const {
3049 switch (getKind()) {
3050 case EK_Result:
3051 case EK_Exception:
3052 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003053
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003054 case EK_Variable:
3055 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003056 case EK_Parameter_CF_Audited:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003057 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00003058 case EK_Binding:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003059 case EK_New:
3060 case EK_Temporary:
Jordan Rose6c0505e2013-05-06 16:48:12 +00003061 case EK_CompoundLiteralInit:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003062 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003063 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003064 case EK_ArrayElement:
3065 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003066 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003067 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00003068 case EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00003069 case EK_LambdaCapture:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003070 case EK_RelatedResult:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003071 break;
3072 }
3073
3074 return false;
3075}
3076
Richard Smithe6c01442013-06-05 00:46:14 +00003077unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
Richard Smithe3b28bc2013-06-12 21:51:50 +00003078 assert(getParent() != this);
Richard Smithe6c01442013-06-05 00:46:14 +00003079 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3080 for (unsigned I = 0; I != Depth; ++I)
3081 OS << "`-";
3082
3083 switch (getKind()) {
3084 case EK_Variable: OS << "Variable"; break;
3085 case EK_Parameter: OS << "Parameter"; break;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003086 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3087 break;
Richard Smithe6c01442013-06-05 00:46:14 +00003088 case EK_Result: OS << "Result"; break;
3089 case EK_Exception: OS << "Exception"; break;
3090 case EK_Member: OS << "Member"; break;
Richard Smith7873de02016-08-11 22:25:46 +00003091 case EK_Binding: OS << "Binding"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00003092 case EK_New: OS << "New"; break;
3093 case EK_Temporary: OS << "Temporary"; break;
3094 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003095 case EK_RelatedResult: OS << "RelatedResult"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00003096 case EK_Base: OS << "Base"; break;
3097 case EK_Delegating: OS << "Delegating"; break;
3098 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3099 case EK_VectorElement: OS << "VectorElement " << Index; break;
3100 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3101 case EK_BlockElement: OS << "Block"; break;
Alex Lorenzb4791c72017-04-06 12:53:43 +00003102 case EK_LambdaToBlockConversionBlockElement:
3103 OS << "Block (lambda)";
3104 break;
Richard Smithe6c01442013-06-05 00:46:14 +00003105 case EK_LambdaCapture:
3106 OS << "LambdaCapture ";
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00003107 OS << DeclarationName(Capture.VarID);
Richard Smithe6c01442013-06-05 00:46:14 +00003108 break;
3109 }
3110
Richard Smith7873de02016-08-11 22:25:46 +00003111 if (auto *D = getDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00003112 OS << " ";
Richard Smith7873de02016-08-11 22:25:46 +00003113 D->printQualifiedName(OS);
Richard Smithe6c01442013-06-05 00:46:14 +00003114 }
3115
3116 OS << " '" << getType().getAsString() << "'\n";
3117
3118 return Depth + 1;
3119}
3120
Yaron Kerencdae9412016-01-29 19:38:18 +00003121LLVM_DUMP_METHOD void InitializedEntity::dump() const {
Richard Smithe6c01442013-06-05 00:46:14 +00003122 dumpImpl(llvm::errs());
3123}
3124
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003125//===----------------------------------------------------------------------===//
3126// Initialization sequence
3127//===----------------------------------------------------------------------===//
3128
3129void InitializationSequence::Step::Destroy() {
3130 switch (Kind) {
3131 case SK_ResolveAddressOfOverloadedFunction:
3132 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003133 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003134 case SK_CastDerivedToBaseLValue:
3135 case SK_BindReference:
3136 case SK_BindReferenceToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00003137 case SK_FinalCopy:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003138 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003139 case SK_UserConversion:
3140 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003141 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003142 case SK_QualificationConversionLValue:
Richard Smith77be48a2014-07-31 06:31:19 +00003143 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00003144 case SK_LValueToRValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00003145 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00003146 case SK_UnwrapInitList:
3147 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003148 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00003149 case SK_ConstructorInitializationFromList:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003150 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00003151 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003152 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003153 case SK_ObjCObjectConversion:
Richard Smith410306b2016-12-12 02:53:20 +00003154 case SK_ArrayLoopIndex:
3155 case SK_ArrayLoopInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003156 case SK_ArrayInit:
Richard Smith378b8c82016-12-14 03:22:16 +00003157 case SK_GNUArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00003158 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00003159 case SK_PassByIndirectCopyRestore:
3160 case SK_PassByIndirectRestore:
3161 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00003162 case SK_StdInitializerList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00003163 case SK_StdInitializerListConstructorCall:
Guy Benyei61054192013-02-07 10:55:47 +00003164 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003165 case SK_OCLZeroEvent:
Egor Churaev89831422016-12-23 14:55:49 +00003166 case SK_OCLZeroQueue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003167 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003168
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003169 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00003170 case SK_ConversionSequenceNoNarrowing:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003171 delete ICS;
3172 }
3173}
3174
Douglas Gregor838fcc32010-03-26 20:14:36 +00003175bool InitializationSequence::isDirectReferenceBinding() const {
Richard Smithb8c0f552016-12-09 18:49:13 +00003176 // There can be some lvalue adjustments after the SK_BindReference step.
3177 for (auto I = Steps.rbegin(); I != Steps.rend(); ++I) {
3178 if (I->Kind == SK_BindReference)
3179 return true;
3180 if (I->Kind == SK_BindReferenceToTemporary)
3181 return false;
3182 }
3183 return false;
Douglas Gregor838fcc32010-03-26 20:14:36 +00003184}
3185
3186bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00003187 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00003188 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003189
Douglas Gregor838fcc32010-03-26 20:14:36 +00003190 switch (getFailureKind()) {
3191 case FK_TooManyInitsForReference:
Richard Smith49a6b6e2017-03-24 01:14:25 +00003192 case FK_ParenthesizedListInitForReference:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003193 case FK_ArrayNeedsInitList:
3194 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00003195 case FK_ArrayNeedsInitListOrWideStringLiteral:
3196 case FK_NarrowStringIntoWideCharArray:
3197 case FK_WideStringIntoCharArray:
3198 case FK_IncompatWideStringIntoWideChar:
Richard Smith3a8244d2018-05-01 05:02:45 +00003199 case FK_PlainStringIntoUTF8Char:
3200 case FK_UTF8StringIntoPlainChar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003201 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3202 case FK_NonConstLValueReferenceBindingToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00003203 case FK_NonConstLValueReferenceBindingToBitfield:
3204 case FK_NonConstLValueReferenceBindingToVectorElement:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003205 case FK_NonConstLValueReferenceBindingToUnrelated:
3206 case FK_RValueReferenceBindingToLValue:
3207 case FK_ReferenceInitDropsQualifiers:
3208 case FK_ReferenceInitFailed:
3209 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00003210 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003211 case FK_TooManyInitsForScalar:
Richard Smith49a6b6e2017-03-24 01:14:25 +00003212 case FK_ParenthesizedListInitForScalar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003213 case FK_ReferenceBindingToInitList:
3214 case FK_InitListBadDestinationType:
3215 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003216 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003217 case FK_ArrayTypeMismatch:
3218 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00003219 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00003220 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00003221 case FK_PlaceholderType:
Sebastian Redl048a6d72012-04-01 19:54:59 +00003222 case FK_ExplicitConstructor:
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003223 case FK_AddressOfUnaddressableFunction:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003224 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003225
Douglas Gregor838fcc32010-03-26 20:14:36 +00003226 case FK_ReferenceInitOverloadFailed:
3227 case FK_UserConversionOverloadFailed:
3228 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003229 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003230 return FailedOverloadResult == OR_Ambiguous;
3231 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003232
David Blaikie8a40f702012-01-17 06:56:22 +00003233 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00003234}
3235
Douglas Gregorb33eed02010-04-16 22:09:46 +00003236bool InitializationSequence::isConstructorInitialization() const {
3237 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3238}
3239
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003240void
3241InitializationSequence
3242::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3243 DeclAccessPair Found,
3244 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003245 Step S;
3246 S.Kind = SK_ResolveAddressOfOverloadedFunction;
3247 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003248 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003249 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00003250 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003251 Steps.push_back(S);
3252}
3253
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003254void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00003255 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003256 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00003257 switch (VK) {
3258 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
3259 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3260 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003261 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003262 S.Type = BaseType;
3263 Steps.push_back(S);
3264}
3265
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003266void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003267 bool BindingTemporary) {
3268 Step S;
3269 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3270 S.Type = T;
3271 Steps.push_back(S);
3272}
3273
Richard Smithb8c0f552016-12-09 18:49:13 +00003274void InitializationSequence::AddFinalCopy(QualType T) {
3275 Step S;
3276 S.Kind = SK_FinalCopy;
3277 S.Type = T;
3278 Steps.push_back(S);
3279}
3280
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003281void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
3282 Step S;
3283 S.Kind = SK_ExtraneousCopyToTemporary;
3284 S.Type = T;
3285 Steps.push_back(S);
3286}
3287
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003288void
3289InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
3290 DeclAccessPair FoundDecl,
3291 QualType T,
3292 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003293 Step S;
3294 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003295 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003296 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003297 S.Function.Function = Function;
3298 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003299 Steps.push_back(S);
3300}
3301
3302void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00003303 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003304 Step S;
John McCall7a1da892010-08-26 16:36:35 +00003305 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00003306 switch (VK) {
3307 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003308 S.Kind = SK_QualificationConversionRValue;
3309 break;
John McCall2536c6d2010-08-25 10:28:54 +00003310 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003311 S.Kind = SK_QualificationConversionXValue;
3312 break;
John McCall2536c6d2010-08-25 10:28:54 +00003313 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003314 S.Kind = SK_QualificationConversionLValue;
3315 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003316 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003317 S.Type = Ty;
3318 Steps.push_back(S);
3319}
3320
Richard Smith77be48a2014-07-31 06:31:19 +00003321void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
3322 Step S;
3323 S.Kind = SK_AtomicConversion;
3324 S.Type = Ty;
3325 Steps.push_back(S);
3326}
3327
Jordan Roseb1312a52013-04-11 00:58:58 +00003328void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
3329 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
3330
3331 Step S;
3332 S.Kind = SK_LValueToRValue;
3333 S.Type = Ty;
3334 Steps.push_back(S);
3335}
3336
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003337void InitializationSequence::AddConversionSequenceStep(
Richard Smithaaa0ec42013-09-21 21:19:19 +00003338 const ImplicitConversionSequence &ICS, QualType T,
3339 bool TopLevelOfInitList) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003340 Step S;
Richard Smithaaa0ec42013-09-21 21:19:19 +00003341 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3342 : SK_ConversionSequence;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003343 S.Type = T;
3344 S.ICS = new ImplicitConversionSequence(ICS);
3345 Steps.push_back(S);
3346}
3347
Douglas Gregor51e77d52009-12-10 17:56:55 +00003348void InitializationSequence::AddListInitializationStep(QualType T) {
3349 Step S;
3350 S.Kind = SK_ListInitialization;
3351 S.Type = T;
3352 Steps.push_back(S);
3353}
3354
Richard Smith55c28882016-05-12 23:45:49 +00003355void InitializationSequence::AddConstructorInitializationStep(
3356 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3357 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003358 Step S;
Richard Smithf8adcdc2014-07-17 05:12:35 +00003359 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
Richard Smith53324112014-07-16 21:33:43 +00003360 : SK_ConstructorInitializationFromList
3361 : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003362 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003363 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003364 S.Function.Function = Constructor;
Richard Smith55c28882016-05-12 23:45:49 +00003365 S.Function.FoundDecl = FoundDecl;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003366 Steps.push_back(S);
3367}
3368
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003369void InitializationSequence::AddZeroInitializationStep(QualType T) {
3370 Step S;
3371 S.Kind = SK_ZeroInitialization;
3372 S.Type = T;
3373 Steps.push_back(S);
3374}
3375
Douglas Gregore1314a62009-12-18 05:02:21 +00003376void InitializationSequence::AddCAssignmentStep(QualType T) {
3377 Step S;
3378 S.Kind = SK_CAssignment;
3379 S.Type = T;
3380 Steps.push_back(S);
3381}
3382
Eli Friedman78275202009-12-19 08:11:05 +00003383void InitializationSequence::AddStringInitStep(QualType T) {
3384 Step S;
3385 S.Kind = SK_StringInit;
3386 S.Type = T;
3387 Steps.push_back(S);
3388}
3389
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003390void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3391 Step S;
3392 S.Kind = SK_ObjCObjectConversion;
3393 S.Type = T;
3394 Steps.push_back(S);
3395}
3396
Richard Smith378b8c82016-12-14 03:22:16 +00003397void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00003398 Step S;
Richard Smith378b8c82016-12-14 03:22:16 +00003399 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
Douglas Gregore2f943b2011-02-22 18:29:51 +00003400 S.Type = T;
3401 Steps.push_back(S);
3402}
3403
Richard Smith410306b2016-12-12 02:53:20 +00003404void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
3405 Step S;
3406 S.Kind = SK_ArrayLoopIndex;
3407 S.Type = EltT;
3408 Steps.insert(Steps.begin(), S);
3409
3410 S.Kind = SK_ArrayLoopInit;
3411 S.Type = T;
3412 Steps.push_back(S);
3413}
3414
Richard Smithebeed412012-02-15 22:38:09 +00003415void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3416 Step S;
3417 S.Kind = SK_ParenthesizedArrayInit;
3418 S.Type = T;
3419 Steps.push_back(S);
3420}
3421
John McCall31168b02011-06-15 23:02:42 +00003422void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3423 bool shouldCopy) {
3424 Step s;
3425 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3426 : SK_PassByIndirectRestore);
3427 s.Type = type;
3428 Steps.push_back(s);
3429}
3430
3431void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3432 Step S;
3433 S.Kind = SK_ProduceObjCObject;
3434 S.Type = T;
3435 Steps.push_back(S);
3436}
3437
Sebastian Redlc1839b12012-01-17 22:49:42 +00003438void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3439 Step S;
3440 S.Kind = SK_StdInitializerList;
3441 S.Type = T;
3442 Steps.push_back(S);
3443}
3444
Guy Benyei61054192013-02-07 10:55:47 +00003445void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3446 Step S;
3447 S.Kind = SK_OCLSamplerInit;
3448 S.Type = T;
3449 Steps.push_back(S);
3450}
3451
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003452void InitializationSequence::AddOCLZeroEventStep(QualType T) {
3453 Step S;
3454 S.Kind = SK_OCLZeroEvent;
3455 S.Type = T;
3456 Steps.push_back(S);
3457}
3458
Egor Churaev89831422016-12-23 14:55:49 +00003459void InitializationSequence::AddOCLZeroQueueStep(QualType T) {
3460 Step S;
3461 S.Kind = SK_OCLZeroQueue;
3462 S.Type = T;
3463 Steps.push_back(S);
3464}
3465
Sebastian Redl29526f02011-11-27 16:50:07 +00003466void InitializationSequence::RewrapReferenceInitList(QualType T,
3467 InitListExpr *Syntactic) {
3468 assert(Syntactic->getNumInits() == 1 &&
3469 "Can only rewrap trivial init lists.");
3470 Step S;
3471 S.Kind = SK_UnwrapInitList;
3472 S.Type = Syntactic->getInit(0)->getType();
3473 Steps.insert(Steps.begin(), S);
3474
3475 S.Kind = SK_RewrapInitList;
3476 S.Type = T;
3477 S.WrappingSyntacticList = Syntactic;
3478 Steps.push_back(S);
3479}
3480
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003481void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003482 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00003483 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003484 this->Failure = Failure;
3485 this->FailedOverloadResult = Result;
3486}
3487
3488//===----------------------------------------------------------------------===//
3489// Attempt initialization
3490//===----------------------------------------------------------------------===//
3491
Nico Weber337d5aa2015-04-17 08:32:38 +00003492/// Tries to add a zero initializer. Returns true if that worked.
3493static bool
3494maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
3495 const InitializedEntity &Entity) {
3496 if (Entity.getKind() != InitializedEntity::EK_Variable)
3497 return false;
3498
3499 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
3500 if (VD->getInit() || VD->getLocEnd().isMacroID())
3501 return false;
3502
3503 QualType VariableTy = VD->getType().getCanonicalType();
3504 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
3505 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3506 if (!Init.empty()) {
3507 Sequence.AddZeroInitializationStep(Entity.getType());
3508 Sequence.SetZeroInitializationFixit(Init, Loc);
3509 return true;
3510 }
3511 return false;
3512}
3513
John McCall31168b02011-06-15 23:02:42 +00003514static void MaybeProduceObjCObject(Sema &S,
3515 InitializationSequence &Sequence,
3516 const InitializedEntity &Entity) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003517 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCall31168b02011-06-15 23:02:42 +00003518
3519 /// When initializing a parameter, produce the value if it's marked
3520 /// __attribute__((ns_consumed)).
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003521 if (Entity.isParameterKind()) {
John McCall31168b02011-06-15 23:02:42 +00003522 if (!Entity.isParameterConsumed())
3523 return;
3524
3525 assert(Entity.getType()->isObjCRetainableType() &&
3526 "consuming an object of unretainable type?");
3527 Sequence.AddProduceObjCObjectStep(Entity.getType());
3528
3529 /// When initializing a return value, if the return type is a
3530 /// retainable type, then returns need to immediately retain the
3531 /// object. If an autorelease is required, it will be done at the
3532 /// last instant.
3533 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
3534 if (!Entity.getType()->isObjCRetainableType())
3535 return;
3536
3537 Sequence.AddProduceObjCObjectStep(Entity.getType());
3538 }
3539}
3540
Richard Smithcc1b96d2013-06-12 22:31:48 +00003541static void TryListInitialization(Sema &S,
3542 const InitializedEntity &Entity,
3543 const InitializationKind &Kind,
3544 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00003545 InitializationSequence &Sequence,
3546 bool TreatUnavailableAsInvalid);
Richard Smithcc1b96d2013-06-12 22:31:48 +00003547
Richard Smithd86812d2012-07-05 08:39:21 +00003548/// \brief When initializing from init list via constructor, handle
3549/// initialization of an object of type std::initializer_list<T>.
Sebastian Redled2e5322011-12-22 14:44:04 +00003550///
Richard Smithd86812d2012-07-05 08:39:21 +00003551/// \return true if we have handled initialization of an object of type
3552/// std::initializer_list<T>, false otherwise.
3553static bool TryInitializerListConstruction(Sema &S,
3554 InitListExpr *List,
3555 QualType DestType,
Manman Ren073db022016-03-10 18:53:19 +00003556 InitializationSequence &Sequence,
3557 bool TreatUnavailableAsInvalid) {
Richard Smithd86812d2012-07-05 08:39:21 +00003558 QualType E;
3559 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1bfe0682012-02-14 21:14:13 +00003560 return false;
3561
Richard Smithdb0ac552015-12-18 22:40:25 +00003562 if (!S.isCompleteType(List->getExprLoc(), E)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00003563 Sequence.setIncompleteTypeFailure(E);
3564 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003565 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00003566
3567 // Try initializing a temporary array from the init list.
3568 QualType ArrayType = S.Context.getConstantArrayType(
3569 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3570 List->getNumInits()),
3571 clang::ArrayType::Normal, 0);
3572 InitializedEntity HiddenArray =
3573 InitializedEntity::InitializeTemporary(ArrayType);
Vedant Kumara14a1f92018-01-17 18:53:51 +00003574 InitializationKind Kind = InitializationKind::CreateDirectList(
3575 List->getExprLoc(), List->getLocStart(), List->getLocEnd());
Manman Ren073db022016-03-10 18:53:19 +00003576 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
3577 TreatUnavailableAsInvalid);
Richard Smithcc1b96d2013-06-12 22:31:48 +00003578 if (Sequence)
3579 Sequence.AddStdInitializerListConstructionStep(DestType);
Richard Smithd86812d2012-07-05 08:39:21 +00003580 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003581}
3582
Richard Smith7c2bcc92016-09-07 02:14:33 +00003583/// Determine if the constructor has the signature of a copy or move
3584/// constructor for the type T of the class in which it was found. That is,
3585/// determine if its first parameter is of type T or reference to (possibly
3586/// cv-qualified) T.
3587static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
3588 const ConstructorInfo &Info) {
3589 if (Info.Constructor->getNumParams() == 0)
3590 return false;
3591
3592 QualType ParmT =
3593 Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
3594 QualType ClassT =
3595 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
3596
3597 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
3598}
3599
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003600static OverloadingResult
3601ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003602 MultiExprArg Args,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003603 OverloadCandidateSet &CandidateSet,
Richard Smith67ef14f2017-09-26 18:37:55 +00003604 QualType DestType,
Richard Smith40c78062015-02-21 02:31:57 +00003605 DeclContext::lookup_result Ctors,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003606 OverloadCandidateSet::iterator &Best,
3607 bool CopyInitializing, bool AllowExplicit,
Richard Smith7c2bcc92016-09-07 02:14:33 +00003608 bool OnlyListConstructors, bool IsListInit,
3609 bool SecondStepOfCopyInit = false) {
Richard Smith67ef14f2017-09-26 18:37:55 +00003610 CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003611
Richard Smith40c78062015-02-21 02:31:57 +00003612 for (NamedDecl *D : Ctors) {
Richard Smithc2bebe92016-05-11 20:37:46 +00003613 auto Info = getConstructorInfo(D);
Richard Smith7c2bcc92016-09-07 02:14:33 +00003614 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
Richard Smithc2bebe92016-05-11 20:37:46 +00003615 continue;
3616
Richard Smith7c2bcc92016-09-07 02:14:33 +00003617 if (!AllowExplicit && Info.Constructor->isExplicit())
3618 continue;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003619
Richard Smith7c2bcc92016-09-07 02:14:33 +00003620 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
3621 continue;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003622
Richard Smith7c2bcc92016-09-07 02:14:33 +00003623 // C++11 [over.best.ics]p4:
3624 // ... and the constructor or user-defined conversion function is a
3625 // candidate by
3626 // - 13.3.1.3, when the argument is the temporary in the second step
3627 // of a class copy-initialization, or
3628 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
3629 // - the second phase of 13.3.1.7 when the initializer list has exactly
3630 // one element that is itself an initializer list, and the target is
3631 // the first parameter of a constructor of class X, and the conversion
3632 // is to X or reference to (possibly cv-qualified X),
3633 // user-defined conversion sequences are not considered.
3634 bool SuppressUserConversions =
3635 SecondStepOfCopyInit ||
3636 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
3637 hasCopyOrMoveCtorParam(S.Context, Info));
3638
3639 if (Info.ConstructorTmpl)
3640 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3641 /*ExplicitArgs*/ nullptr, Args,
3642 CandidateSet, SuppressUserConversions);
3643 else {
3644 // C++ [over.match.copy]p1:
3645 // - When initializing a temporary to be bound to the first parameter
3646 // of a constructor [for type T] that takes a reference to possibly
3647 // cv-qualified T as its first argument, called with a single
3648 // argument in the context of direct-initialization, explicit
3649 // conversion functions are also considered.
3650 // FIXME: What if a constructor template instantiates to such a signature?
3651 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
3652 Args.size() == 1 &&
3653 hasCopyOrMoveCtorParam(S.Context, Info);
3654 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
3655 CandidateSet, SuppressUserConversions,
3656 /*PartialOverloading=*/false,
3657 /*AllowExplicit=*/AllowExplicitConv);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003658 }
3659 }
3660
Richard Smith67ef14f2017-09-26 18:37:55 +00003661 // FIXME: Work around a bug in C++17 guaranteed copy elision.
3662 //
3663 // When initializing an object of class type T by constructor
3664 // ([over.match.ctor]) or by list-initialization ([over.match.list])
3665 // from a single expression of class type U, conversion functions of
3666 // U that convert to the non-reference type cv T are candidates.
3667 // Explicit conversion functions are only candidates during
3668 // direct-initialization.
3669 //
3670 // Note: SecondStepOfCopyInit is only ever true in this case when
3671 // evaluating whether to produce a C++98 compatibility warning.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003672 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
Richard Smith67ef14f2017-09-26 18:37:55 +00003673 !SecondStepOfCopyInit) {
3674 Expr *Initializer = Args[0];
3675 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
3676 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
3677 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
3678 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3679 NamedDecl *D = *I;
3680 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3681 D = D->getUnderlyingDecl();
3682
3683 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3684 CXXConversionDecl *Conv;
3685 if (ConvTemplate)
3686 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3687 else
3688 Conv = cast<CXXConversionDecl>(D);
3689
3690 if ((AllowExplicit && !CopyInitializing) || !Conv->isExplicit()) {
3691 if (ConvTemplate)
3692 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3693 ActingDC, Initializer, DestType,
3694 CandidateSet, AllowExplicit,
3695 /*AllowResultConversion*/false);
3696 else
3697 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
3698 DestType, CandidateSet, AllowExplicit,
3699 /*AllowResultConversion*/false);
3700 }
3701 }
3702 }
3703 }
3704
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003705 // Perform overload resolution and return the result.
3706 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3707}
3708
Sebastian Redled2e5322011-12-22 14:44:04 +00003709/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3710/// enumerates the constructors of the initialized entity and performs overload
3711/// resolution to select the best.
Richard Smith410306b2016-12-12 02:53:20 +00003712/// \param DestType The destination class type.
3713/// \param DestArrayType The destination type, which is either DestType or
3714/// a (possibly multidimensional) array of DestType.
NAKAMURA Takumiffcc98a2015-02-05 23:12:13 +00003715/// \param IsListInit Is this list-initialization?
Richard Smithed83ebd2015-02-05 07:02:11 +00003716/// \param IsInitListCopy Is this non-list-initialization resulting from a
3717/// list-initialization from {x} where x is the same
3718/// type as the entity?
Sebastian Redled2e5322011-12-22 14:44:04 +00003719static void TryConstructorInitialization(Sema &S,
3720 const InitializedEntity &Entity,
3721 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003722 MultiExprArg Args, QualType DestType,
Richard Smith410306b2016-12-12 02:53:20 +00003723 QualType DestArrayType,
Sebastian Redled2e5322011-12-22 14:44:04 +00003724 InitializationSequence &Sequence,
Richard Smithed83ebd2015-02-05 07:02:11 +00003725 bool IsListInit = false,
3726 bool IsInitListCopy = false) {
Richard Smith122f88d2016-12-06 23:52:28 +00003727 assert(((!IsListInit && !IsInitListCopy) ||
3728 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3729 "IsListInit/IsInitListCopy must come with a single initializer list "
3730 "argument.");
3731 InitListExpr *ILE =
3732 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
3733 MultiExprArg UnwrappedArgs =
3734 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003735
Sebastian Redled2e5322011-12-22 14:44:04 +00003736 // The type we're constructing needs to be complete.
Richard Smithdb0ac552015-12-18 22:40:25 +00003737 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003738 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003739 return;
Sebastian Redled2e5322011-12-22 14:44:04 +00003740 }
3741
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003742 // C++17 [dcl.init]p17:
Richard Smith122f88d2016-12-06 23:52:28 +00003743 // - If the initializer expression is a prvalue and the cv-unqualified
3744 // version of the source type is the same class as the class of the
3745 // destination, the initializer expression is used to initialize the
3746 // destination object.
3747 // Per DR (no number yet), this does not apply when initializing a base
3748 // class or delegating to another constructor from a mem-initializer.
Alex Lorenzb4791c72017-04-06 12:53:43 +00003749 // ObjC++: Lambda captured by the block in the lambda to block conversion
3750 // should avoid copy elision.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003751 if (S.getLangOpts().CPlusPlus17 &&
Richard Smith122f88d2016-12-06 23:52:28 +00003752 Entity.getKind() != InitializedEntity::EK_Base &&
3753 Entity.getKind() != InitializedEntity::EK_Delegating &&
Alex Lorenzb4791c72017-04-06 12:53:43 +00003754 Entity.getKind() !=
3755 InitializedEntity::EK_LambdaToBlockConversionBlockElement &&
Richard Smith122f88d2016-12-06 23:52:28 +00003756 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isRValue() &&
3757 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
3758 // Convert qualifications if necessary.
Richard Smith16d31502016-12-21 01:31:56 +00003759 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Richard Smith122f88d2016-12-06 23:52:28 +00003760 if (ILE)
3761 Sequence.RewrapReferenceInitList(DestType, ILE);
3762 return;
3763 }
3764
Sebastian Redled2e5322011-12-22 14:44:04 +00003765 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3766 assert(DestRecordType && "Constructor initialization requires record type");
3767 CXXRecordDecl *DestRecordDecl
3768 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3769
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003770 // Build the candidate set directly in the initialization sequence
3771 // structure, so that it will persist if we fail.
3772 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3773
3774 // Determine whether we are allowed to call explicit constructors or
3775 // explicit conversion operators.
Richard Smithed83ebd2015-02-05 07:02:11 +00003776 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003777 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003778
Sebastian Redled2e5322011-12-22 14:44:04 +00003779 // - Otherwise, if T is a class type, constructors are considered. The
3780 // applicable constructors are enumerated, and the best one is chosen
3781 // through overload resolution.
Richard Smith40c78062015-02-21 02:31:57 +00003782 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
Sebastian Redled2e5322011-12-22 14:44:04 +00003783
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003784 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redled2e5322011-12-22 14:44:04 +00003785 OverloadCandidateSet::iterator Best;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003786 bool AsInitializerList = false;
3787
Larisse Voufo19d08672015-01-27 18:47:05 +00003788 // C++11 [over.match.list]p1, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00003789 // When objects of non-aggregate type T are list-initialized, such that
3790 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
3791 // according to the rules in this section, overload resolution selects
3792 // the constructor in two phases:
3793 //
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003794 // - Initially, the candidate functions are the initializer-list
3795 // constructors of the class T and the argument list consists of the
3796 // initializer list as a single argument.
Richard Smithed83ebd2015-02-05 07:02:11 +00003797 if (IsListInit) {
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003798 AsInitializerList = true;
Richard Smithd86812d2012-07-05 08:39:21 +00003799
3800 // If the initializer list has no elements and T has a default constructor,
3801 // the first phase is omitted.
Richard Smith122f88d2016-12-06 23:52:28 +00003802 if (!(UnwrappedArgs.empty() && DestRecordDecl->hasDefaultConstructor()))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003803 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Richard Smith67ef14f2017-09-26 18:37:55 +00003804 CandidateSet, DestType, Ctors, Best,
Richard Smithd86812d2012-07-05 08:39:21 +00003805 CopyInitialization, AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003806 /*OnlyListConstructor=*/true,
3807 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003808 }
3809
3810 // C++11 [over.match.list]p1:
3811 // - If no viable initializer-list constructor is found, overload resolution
3812 // is performed again, where the candidate functions are all the
Richard Smithd86812d2012-07-05 08:39:21 +00003813 // constructors of the class T and the argument list consists of the
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003814 // elements of the initializer list.
3815 if (Result == OR_No_Viable_Function) {
3816 AsInitializerList = false;
Richard Smith122f88d2016-12-06 23:52:28 +00003817 Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs,
Richard Smith67ef14f2017-09-26 18:37:55 +00003818 CandidateSet, DestType, Ctors, Best,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003819 CopyInitialization, AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003820 /*OnlyListConstructors=*/false,
3821 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003822 }
3823 if (Result) {
Richard Smithed83ebd2015-02-05 07:02:11 +00003824 Sequence.SetOverloadFailure(IsListInit ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003825 InitializationSequence::FK_ListConstructorOverloadFailed :
3826 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00003827 Result);
3828 return;
3829 }
3830
Richard Smith67ef14f2017-09-26 18:37:55 +00003831 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3832
3833 // In C++17, ResolveConstructorOverload can select a conversion function
3834 // instead of a constructor.
3835 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
3836 // Add the user-defined conversion step that calls the conversion function.
3837 QualType ConvType = CD->getConversionType();
3838 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
3839 "should not have selected this conversion function");
3840 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
3841 HadMultipleCandidates);
3842 if (!S.Context.hasSameType(ConvType, DestType))
3843 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
3844 if (IsListInit)
3845 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
3846 return;
3847 }
3848
Richard Smithd86812d2012-07-05 08:39:21 +00003849 // C++11 [dcl.init]p6:
Sebastian Redled2e5322011-12-22 14:44:04 +00003850 // If a program calls for the default initialization of an object
3851 // of a const-qualified type T, T shall be a class type with a
3852 // user-provided default constructor.
Nico Weber6a6376b2016-02-19 01:52:46 +00003853 // C++ core issue 253 proposal:
3854 // If the implicit default constructor initializes all subobjects, no
3855 // initializer should be required.
3856 // The 253 proposal is for example needed to process libstdc++ headers in 5.x.
3857 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redled2e5322011-12-22 14:44:04 +00003858 if (Kind.getKind() == InitializationKind::IK_Default &&
Nico Weber6a6376b2016-02-19 01:52:46 +00003859 Entity.getType().isConstQualified()) {
3860 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
3861 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
3862 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3863 return;
3864 }
Sebastian Redled2e5322011-12-22 14:44:04 +00003865 }
3866
Sebastian Redl048a6d72012-04-01 19:54:59 +00003867 // C++11 [over.match.list]p1:
3868 // In copy-list-initialization, if an explicit constructor is chosen, the
3869 // initializer is ill-formed.
Richard Smithed83ebd2015-02-05 07:02:11 +00003870 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
Sebastian Redl048a6d72012-04-01 19:54:59 +00003871 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3872 return;
3873 }
3874
Sebastian Redled2e5322011-12-22 14:44:04 +00003875 // Add the constructor initialization step. Any cv-qualification conversion is
3876 // subsumed by the initialization.
Richard Smithed83ebd2015-02-05 07:02:11 +00003877 Sequence.AddConstructorInitializationStep(
Richard Smith410306b2016-12-12 02:53:20 +00003878 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
Richard Smithed83ebd2015-02-05 07:02:11 +00003879 IsListInit | IsInitListCopy, AsInitializerList);
Sebastian Redled2e5322011-12-22 14:44:04 +00003880}
3881
Sebastian Redl29526f02011-11-27 16:50:07 +00003882static bool
3883ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3884 Expr *Initializer,
3885 QualType &SourceType,
3886 QualType &UnqualifiedSourceType,
3887 QualType UnqualifiedTargetType,
3888 InitializationSequence &Sequence) {
3889 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3890 S.Context.OverloadTy) {
3891 DeclAccessPair Found;
3892 bool HadMultipleCandidates = false;
3893 if (FunctionDecl *Fn
3894 = S.ResolveAddressOfOverloadedFunction(Initializer,
3895 UnqualifiedTargetType,
3896 false, Found,
3897 &HadMultipleCandidates)) {
3898 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3899 HadMultipleCandidates);
3900 SourceType = Fn->getType();
3901 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3902 } else if (!UnqualifiedTargetType->isRecordType()) {
3903 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3904 return true;
3905 }
3906 }
3907 return false;
3908}
3909
3910static void TryReferenceInitializationCore(Sema &S,
3911 const InitializedEntity &Entity,
3912 const InitializationKind &Kind,
3913 Expr *Initializer,
3914 QualType cv1T1, QualType T1,
3915 Qualifiers T1Quals,
3916 QualType cv2T2, QualType T2,
3917 Qualifiers T2Quals,
3918 InitializationSequence &Sequence);
3919
Richard Smithd86812d2012-07-05 08:39:21 +00003920static void TryValueInitialization(Sema &S,
3921 const InitializedEntity &Entity,
3922 const InitializationKind &Kind,
3923 InitializationSequence &Sequence,
Craig Topperc3ec1492014-05-26 06:22:03 +00003924 InitListExpr *InitList = nullptr);
Richard Smithd86812d2012-07-05 08:39:21 +00003925
Sebastian Redl29526f02011-11-27 16:50:07 +00003926/// \brief Attempt list initialization of a reference.
3927static void TryReferenceListInitialization(Sema &S,
3928 const InitializedEntity &Entity,
3929 const InitializationKind &Kind,
3930 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00003931 InitializationSequence &Sequence,
3932 bool TreatUnavailableAsInvalid) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003933 // First, catch C++03 where this isn't possible.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003934 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003935 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3936 return;
3937 }
David Majnemer9370dc22015-04-26 07:35:03 +00003938 // Can't reference initialize a compound literal.
3939 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
3940 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3941 return;
3942 }
Sebastian Redl29526f02011-11-27 16:50:07 +00003943
3944 QualType DestType = Entity.getType();
3945 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3946 Qualifiers T1Quals;
3947 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3948
3949 // Reference initialization via an initializer list works thus:
3950 // If the initializer list consists of a single element that is
3951 // reference-related to the referenced type, bind directly to that element
3952 // (possibly creating temporaries).
3953 // Otherwise, initialize a temporary with the initializer list and
3954 // bind to that.
3955 if (InitList->getNumInits() == 1) {
3956 Expr *Initializer = InitList->getInit(0);
3957 QualType cv2T2 = Initializer->getType();
3958 Qualifiers T2Quals;
3959 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3960
3961 // If this fails, creating a temporary wouldn't work either.
3962 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3963 T1, Sequence))
3964 return;
3965
3966 SourceLocation DeclLoc = Initializer->getLocStart();
3967 bool dummy1, dummy2, dummy3;
3968 Sema::ReferenceCompareResult RefRelationship
3969 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3970 dummy2, dummy3);
3971 if (RefRelationship >= Sema::Ref_Related) {
3972 // Try to bind the reference here.
3973 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3974 T1Quals, cv2T2, T2, T2Quals, Sequence);
3975 if (Sequence)
3976 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3977 return;
3978 }
Richard Smith03d93932013-01-15 07:58:29 +00003979
3980 // Update the initializer if we've resolved an overloaded function.
3981 if (Sequence.step_begin() != Sequence.step_end())
3982 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl29526f02011-11-27 16:50:07 +00003983 }
3984
3985 // Not reference-related. Create a temporary and bind to that.
3986 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3987
Manman Ren073db022016-03-10 18:53:19 +00003988 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
3989 TreatUnavailableAsInvalid);
Sebastian Redl29526f02011-11-27 16:50:07 +00003990 if (Sequence) {
3991 if (DestType->isRValueReferenceType() ||
3992 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3993 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3994 else
3995 Sequence.SetFailed(
3996 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3997 }
3998}
3999
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004000/// \brief Attempt list initialization (C++0x [dcl.init.list])
4001static void TryListInitialization(Sema &S,
4002 const InitializedEntity &Entity,
4003 const InitializationKind &Kind,
4004 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00004005 InitializationSequence &Sequence,
4006 bool TreatUnavailableAsInvalid) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004007 QualType DestType = Entity.getType();
4008
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004009 // C++ doesn't allow scalar initialization with more than one argument.
4010 // But C99 complex numbers are scalars and it makes sense there.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004011 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004012 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4013 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
4014 return;
4015 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004016 if (DestType->isReferenceType()) {
Manman Ren073db022016-03-10 18:53:19 +00004017 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4018 TreatUnavailableAsInvalid);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004019 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004020 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00004021
Larisse Voufod2010992015-01-24 23:09:54 +00004022 if (DestType->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004023 !S.isCompleteType(InitList->getLocStart(), DestType)) {
Larisse Voufod2010992015-01-24 23:09:54 +00004024 Sequence.setIncompleteTypeFailure(DestType);
4025 return;
4026 }
Richard Smithd86812d2012-07-05 08:39:21 +00004027
Larisse Voufo19d08672015-01-27 18:47:05 +00004028 // C++11 [dcl.init.list]p3, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00004029 // - If T is a class type and the initializer list has a single element of
4030 // type cv U, where U is T or a class derived from T, the object is
4031 // initialized from that element (by copy-initialization for
4032 // copy-list-initialization, or by direct-initialization for
4033 // direct-list-initialization).
4034 // - Otherwise, if T is a character array and the initializer list has a
4035 // single element that is an appropriately-typed string literal
4036 // (8.5.2 [dcl.init.string]), initialization is performed as described
4037 // in that section.
Larisse Voufo19d08672015-01-27 18:47:05 +00004038 // - Otherwise, if T is an aggregate, [...] (continue below).
4039 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
Larisse Voufod2010992015-01-24 23:09:54 +00004040 if (DestType->isRecordType()) {
4041 QualType InitType = InitList->getInit(0)->getType();
4042 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004043 S.IsDerivedFrom(InitList->getLocStart(), InitType, DestType)) {
Richard Smith122f88d2016-12-06 23:52:28 +00004044 Expr *InitListAsExpr = InitList;
4045 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smith410306b2016-12-12 02:53:20 +00004046 DestType, Sequence,
4047 /*InitListSyntax*/false,
4048 /*IsInitListCopy*/true);
Larisse Voufod2010992015-01-24 23:09:54 +00004049 return;
4050 }
4051 }
4052 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4053 Expr *SubInit[1] = {InitList->getInit(0)};
4054 if (!isa<VariableArrayType>(DestAT) &&
4055 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4056 InitializationKind SubKind =
4057 Kind.getKind() == InitializationKind::IK_DirectList
4058 ? InitializationKind::CreateDirect(Kind.getLocation(),
4059 InitList->getLBraceLoc(),
4060 InitList->getRBraceLoc())
4061 : Kind;
4062 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
Manman Ren073db022016-03-10 18:53:19 +00004063 /*TopLevelOfInitList*/ true,
4064 TreatUnavailableAsInvalid);
Larisse Voufod2010992015-01-24 23:09:54 +00004065
4066 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4067 // the element is not an appropriately-typed string literal, in which
4068 // case we should proceed as in C++11 (below).
4069 if (Sequence) {
4070 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4071 return;
4072 }
4073 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00004074 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004075 }
Larisse Voufod2010992015-01-24 23:09:54 +00004076
4077 // C++11 [dcl.init.list]p3:
4078 // - If T is an aggregate, aggregate initialization is performed.
Faisal Vali30622bb2015-12-07 02:37:44 +00004079 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4080 (S.getLangOpts().CPlusPlus11 &&
4081 S.isStdInitializerList(DestType, nullptr))) {
Larisse Voufod2010992015-01-24 23:09:54 +00004082 if (S.getLangOpts().CPlusPlus11) {
4083 // - Otherwise, if the initializer list has no elements and T is a
4084 // class type with a default constructor, the object is
4085 // value-initialized.
4086 if (InitList->getNumInits() == 0) {
4087 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4088 if (RD->hasDefaultConstructor()) {
4089 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4090 return;
4091 }
4092 }
4093
4094 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4095 // an initializer_list object constructed [...]
Manman Ren073db022016-03-10 18:53:19 +00004096 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4097 TreatUnavailableAsInvalid))
Larisse Voufod2010992015-01-24 23:09:54 +00004098 return;
4099
4100 // - Otherwise, if T is a class type, constructors are considered.
4101 Expr *InitListAsExpr = InitList;
4102 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smith410306b2016-12-12 02:53:20 +00004103 DestType, Sequence, /*InitListSyntax*/true);
Larisse Voufod2010992015-01-24 23:09:54 +00004104 } else
4105 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
4106 return;
4107 }
4108
Richard Smith089c3162013-09-21 21:55:46 +00004109 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
Richard Smithed638862016-03-28 06:08:37 +00004110 InitList->getNumInits() == 1) {
4111 Expr *E = InitList->getInit(0);
4112
4113 // - Otherwise, if T is an enumeration with a fixed underlying type,
4114 // the initializer-list has a single element v, and the initialization
4115 // is direct-list-initialization, the object is initialized with the
4116 // value T(v); if a narrowing conversion is required to convert v to
4117 // the underlying type of T, the program is ill-formed.
4118 auto *ET = DestType->getAs<EnumType>();
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004119 if (S.getLangOpts().CPlusPlus17 &&
Richard Smithed638862016-03-28 06:08:37 +00004120 Kind.getKind() == InitializationKind::IK_DirectList &&
4121 ET && ET->getDecl()->isFixed() &&
4122 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4123 (E->getType()->isIntegralOrEnumerationType() ||
4124 E->getType()->isFloatingType())) {
4125 // There are two ways that T(v) can work when T is an enumeration type.
4126 // If there is either an implicit conversion sequence from v to T or
4127 // a conversion function that can convert from v to T, then we use that.
4128 // Otherwise, if v is of integral, enumeration, or floating-point type,
4129 // it is converted to the enumeration type via its underlying type.
4130 // There is no overlap possible between these two cases (except when the
4131 // source value is already of the destination type), and the first
4132 // case is handled by the general case for single-element lists below.
4133 ImplicitConversionSequence ICS;
4134 ICS.setStandard();
4135 ICS.Standard.setAsIdentityConversion();
Vedant Kumarf4217f82017-02-16 01:20:00 +00004136 if (!E->isRValue())
4137 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
Richard Smithed638862016-03-28 06:08:37 +00004138 // If E is of a floating-point type, then the conversion is ill-formed
4139 // due to narrowing, but go through the motions in order to produce the
4140 // right diagnostic.
4141 ICS.Standard.Second = E->getType()->isFloatingType()
4142 ? ICK_Floating_Integral
4143 : ICK_Integral_Conversion;
4144 ICS.Standard.setFromType(E->getType());
4145 ICS.Standard.setToType(0, E->getType());
4146 ICS.Standard.setToType(1, DestType);
4147 ICS.Standard.setToType(2, DestType);
4148 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4149 /*TopLevelOfInitList*/true);
4150 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4151 return;
4152 }
4153
Richard Smith089c3162013-09-21 21:55:46 +00004154 // - Otherwise, if the initializer list has a single element of type E
4155 // [...references are handled above...], the object or reference is
Larisse Voufod2010992015-01-24 23:09:54 +00004156 // initialized from that element (by copy-initialization for
4157 // copy-list-initialization, or by direct-initialization for
4158 // direct-list-initialization); if a narrowing conversion is required
4159 // to convert the element to T, the program is ill-formed.
4160 //
Richard Smith089c3162013-09-21 21:55:46 +00004161 // Per core-24034, this is direct-initialization if we were performing
4162 // direct-list-initialization and copy-initialization otherwise.
4163 // We can't use InitListChecker for this, because it always performs
4164 // copy-initialization. This only matters if we might use an 'explicit'
4165 // conversion operator, so we only need to handle the cases where the source
4166 // is of record type.
Richard Smithed638862016-03-28 06:08:37 +00004167 if (InitList->getInit(0)->getType()->isRecordType()) {
4168 InitializationKind SubKind =
4169 Kind.getKind() == InitializationKind::IK_DirectList
4170 ? InitializationKind::CreateDirect(Kind.getLocation(),
4171 InitList->getLBraceLoc(),
4172 InitList->getRBraceLoc())
4173 : Kind;
4174 Expr *SubInit[1] = { InitList->getInit(0) };
4175 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4176 /*TopLevelOfInitList*/true,
4177 TreatUnavailableAsInvalid);
4178 if (Sequence)
4179 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4180 return;
4181 }
Richard Smith089c3162013-09-21 21:55:46 +00004182 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004183
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004184 InitListChecker CheckInitList(S, Entity, InitList,
Manman Ren073db022016-03-10 18:53:19 +00004185 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004186 if (CheckInitList.HadError()) {
4187 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
4188 return;
4189 }
4190
4191 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004192 Sequence.AddListInitializationStep(DestType);
4193}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004194
4195/// \brief Try a reference initialization that involves calling a conversion
4196/// function.
Richard Smithb8c0f552016-12-09 18:49:13 +00004197static OverloadingResult TryRefInitWithConversionFunction(
4198 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4199 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4200 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004201 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004202 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4203 QualType T1 = cv1T1.getUnqualifiedType();
4204 QualType cv2T2 = Initializer->getType();
4205 QualType T2 = cv2T2.getUnqualifiedType();
4206
4207 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004208 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00004209 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004210 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004211 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004212 ObjCConversion,
4213 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004214 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00004215 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004216 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00004217 (void)ObjCLifetimeConversion;
4218
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004219 // Build the candidate set directly in the initialization sequence
4220 // structure, so that it will persist if we fail.
4221 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
Richard Smith67ef14f2017-09-26 18:37:55 +00004222 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004223
4224 // Determine whether we are allowed to call explicit constructors or
4225 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00004226 bool AllowExplicit = Kind.AllowExplicit();
Richard Smith6c6ddab2013-09-21 21:23:47 +00004227 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4228
Craig Topperc3ec1492014-05-26 06:22:03 +00004229 const RecordType *T1RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00004230 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004231 S.isCompleteType(Kind.getLocation(), T1)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004232 // The type we're converting to is a class type. Enumerate its constructors
4233 // to see if there is a suitable conversion.
4234 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00004235
Richard Smith40c78062015-02-21 02:31:57 +00004236 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
Richard Smithc2bebe92016-05-11 20:37:46 +00004237 auto Info = getConstructorInfo(D);
4238 if (!Info.Constructor)
4239 continue;
John McCalla0296f72010-03-19 07:35:19 +00004240
Richard Smithc2bebe92016-05-11 20:37:46 +00004241 if (!Info.Constructor->isInvalidDecl() &&
4242 Info.Constructor->isConvertingConstructor(AllowExplicit)) {
4243 if (Info.ConstructorTmpl)
4244 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004245 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004246 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00004247 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004248 else
Richard Smithc2bebe92016-05-11 20:37:46 +00004249 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004250 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00004251 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004252 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004253 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004254 }
John McCall3696dcb2010-08-17 07:23:57 +00004255 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4256 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004257
Craig Topperc3ec1492014-05-26 06:22:03 +00004258 const RecordType *T2RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00004259 if ((T2RecordType = T2->getAs<RecordType>()) &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004260 S.isCompleteType(Kind.getLocation(), T2)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004261 // The type we're converting from is a class type, enumerate its conversion
4262 // functions.
4263 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4264
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004265 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4266 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004267 NamedDecl *D = *I;
4268 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4269 if (isa<UsingShadowDecl>(D))
4270 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004271
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004272 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4273 CXXConversionDecl *Conv;
4274 if (ConvTemplate)
4275 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4276 else
Sebastian Redld92badf2010-06-30 18:13:39 +00004277 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004278
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004279 // If the conversion function doesn't return a reference type,
4280 // it can't be considered for this conversion unless we're allowed to
4281 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004282 // FIXME: Do we need to make sure that we only consider conversion
4283 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004284 // break recursion.
Douglas Gregor6073dca2012-02-24 23:56:31 +00004285 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004286 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
4287 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004288 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004289 ActingDC, Initializer,
Douglas Gregor68782142013-12-18 21:46:16 +00004290 DestType, CandidateSet,
4291 /*AllowObjCConversionOnExplicit=*/
4292 false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004293 else
John McCalla0296f72010-03-19 07:35:19 +00004294 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004295 Initializer, DestType, CandidateSet,
4296 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004297 }
4298 }
4299 }
John McCall3696dcb2010-08-17 07:23:57 +00004300 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4301 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004302
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004303 SourceLocation DeclLoc = Initializer->getLocStart();
4304
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004305 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004306 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004307 if (OverloadingResult Result
Richard Smith67ef14f2017-09-26 18:37:55 +00004308 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004309 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004310
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004311 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004312 // This is the overload that will be used for this initialization step if we
4313 // use this initialization. Mark it as referenced.
4314 Function->setReferenced();
Chandler Carruth30141632011-02-25 19:41:05 +00004315
Richard Smithb8c0f552016-12-09 18:49:13 +00004316 // Compute the returned type and value kind of the conversion.
4317 QualType cv3T3;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004318 if (isa<CXXConversionDecl>(Function))
Richard Smithb8c0f552016-12-09 18:49:13 +00004319 cv3T3 = Function->getReturnType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004320 else
Richard Smithb8c0f552016-12-09 18:49:13 +00004321 cv3T3 = T1;
4322
4323 ExprValueKind VK = VK_RValue;
4324 if (cv3T3->isLValueReferenceType())
4325 VK = VK_LValue;
4326 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4327 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4328 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004329
4330 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004331 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Richard Smithb8c0f552016-12-09 18:49:13 +00004332 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004333 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004334
Richard Smithb8c0f552016-12-09 18:49:13 +00004335 // Determine whether we'll need to perform derived-to-base adjustments or
4336 // other conversions.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004337 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004338 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004339 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004340 Sema::ReferenceCompareResult NewRefRelationship
Richard Smithb8c0f552016-12-09 18:49:13 +00004341 = S.CompareReferenceRelationship(DeclLoc, T1, cv3T3,
John McCall31168b02011-06-15 23:02:42 +00004342 NewDerivedToBase, NewObjCConversion,
4343 NewObjCLifetimeConversion);
Richard Smithb8c0f552016-12-09 18:49:13 +00004344
4345 // Add the final conversion sequence, if necessary.
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00004346 if (NewRefRelationship == Sema::Ref_Incompatible) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004347 assert(!isa<CXXConstructorDecl>(Function) &&
4348 "should not have conversion after constructor");
4349
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00004350 ImplicitConversionSequence ICS;
4351 ICS.setStandard();
4352 ICS.Standard = Best->FinalConversion;
Richard Smithb8c0f552016-12-09 18:49:13 +00004353 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4354
4355 // Every implicit conversion results in a prvalue, except for a glvalue
4356 // derived-to-base conversion, which we handle below.
4357 cv3T3 = ICS.Standard.getToType(2);
4358 VK = VK_RValue;
4359 }
4360
4361 // If the converted initializer is a prvalue, its type T4 is adjusted to
4362 // type "cv1 T4" and the temporary materialization conversion is applied.
4363 //
4364 // We adjust the cv-qualifications to match the reference regardless of
4365 // whether we have a prvalue so that the AST records the change. In this
4366 // case, T4 is "cv3 T3".
4367 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4368 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4369 Sequence.AddQualificationConversionStep(cv1T4, VK);
4370 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue);
4371 VK = IsLValueRef ? VK_LValue : VK_XValue;
4372
4373 if (NewDerivedToBase)
4374 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004375 else if (NewObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004376 Sequence.AddObjCObjectConversionStep(cv1T1);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004377
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004378 return OR_Success;
4379}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004380
Richard Smithc620f552011-10-19 16:55:56 +00004381static void CheckCXX98CompatAccessibleCopy(Sema &S,
4382 const InitializedEntity &Entity,
4383 Expr *CurInitExpr);
4384
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004385/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
4386static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004387 const InitializedEntity &Entity,
4388 const InitializationKind &Kind,
4389 Expr *Initializer,
4390 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004391 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004392 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00004393 Qualifiers T1Quals;
4394 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004395 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00004396 Qualifiers T2Quals;
4397 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00004398
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004399 // If the initializer is the address of an overloaded function, try
4400 // to resolve the overloaded function. If all goes well, T2 is the
4401 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00004402 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4403 T1, Sequence))
4404 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00004405
Sebastian Redl29526f02011-11-27 16:50:07 +00004406 // Delegate everything else to a subfunction.
4407 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4408 T1Quals, cv2T2, T2, T2Quals, Sequence);
4409}
4410
Richard Smithb8c0f552016-12-09 18:49:13 +00004411/// Determine whether an expression is a non-referenceable glvalue (one to
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004412/// which a reference can never bind). Attempting to bind a reference to
Richard Smithb8c0f552016-12-09 18:49:13 +00004413/// such a glvalue will always create a temporary.
4414static bool isNonReferenceableGLValue(Expr *E) {
4415 return E->refersToBitField() || E->refersToVectorElement();
Jordan Roseb1312a52013-04-11 00:58:58 +00004416}
4417
Sebastian Redl29526f02011-11-27 16:50:07 +00004418/// \brief Reference initialization without resolving overloaded functions.
4419static void TryReferenceInitializationCore(Sema &S,
4420 const InitializedEntity &Entity,
4421 const InitializationKind &Kind,
4422 Expr *Initializer,
4423 QualType cv1T1, QualType T1,
4424 Qualifiers T1Quals,
4425 QualType cv2T2, QualType T2,
4426 Qualifiers T2Quals,
4427 InitializationSequence &Sequence) {
4428 QualType DestType = Entity.getType();
4429 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004430 // Compute some basic properties of the types and the initializer.
4431 bool isLValueRef = DestType->isLValueReferenceType();
4432 bool isRValueRef = !isLValueRef;
4433 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004434 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004435 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004436 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004437 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004438 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004439 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00004440
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004441 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004442 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004443 // "cv2 T2" as follows:
4444 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004445 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004446 // expression
Richard Smith6c6ddab2013-09-21 21:23:47 +00004447 // Note the analogous bullet points for rvalue refs to functions. Because
Sebastian Redld92badf2010-06-30 18:13:39 +00004448 // there are no function rvalues in C++, rvalue refs to functions are treated
4449 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004450 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00004451 bool T1Function = T1->isFunctionType();
4452 if (isLValueRef || T1Function) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004453 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
Richard Smithce766292016-10-21 23:01:55 +00004454 (RefRelationship == Sema::Ref_Compatible ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004455 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004456 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004457 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004458 // reference-compatible with "cv2 T2," or
Richard Smithb8c0f552016-12-09 18:49:13 +00004459 if (T1Quals != T2Quals)
4460 // Convert to cv1 T2. This should only add qualifiers unless this is a
4461 // c-style cast. The removal of qualifiers in that case notionally
4462 // happens after the reference binding, but that doesn't matter.
4463 Sequence.AddQualificationConversionStep(
4464 S.Context.getQualifiedType(T2, T1Quals),
4465 Initializer->getValueKind());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004466 if (DerivedToBase)
Richard Smithb8c0f552016-12-09 18:49:13 +00004467 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004468 else if (ObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004469 Sequence.AddObjCObjectConversionStep(cv1T1);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004470
Richard Smithb8c0f552016-12-09 18:49:13 +00004471 // We only create a temporary here when binding a reference to a
4472 // bit-field or vector element. Those cases are't supposed to be
4473 // handled by this bullet, but the outcome is the same either way.
4474 Sequence.AddReferenceBindingStep(cv1T1, false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004475 return;
4476 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004477
4478 // - has a class type (i.e., T2 is a class type), where T1 is not
4479 // reference-related to T2, and can be implicitly converted to an
4480 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
4481 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004482 // applicable conversion functions (13.3.1.6) and choosing the best
4483 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00004484 // If we have an rvalue ref to function type here, the rhs must be
Richard Smith6c6ddab2013-09-21 21:23:47 +00004485 // an rvalue. DR1287 removed the "implicitly" here.
Sebastian Redld92badf2010-06-30 18:13:39 +00004486 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
4487 (isLValueRef || InitCategory.isRValue())) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00004488 ConvOvlResult = TryRefInitWithConversionFunction(
Richard Smithb8c0f552016-12-09 18:49:13 +00004489 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
4490 /*IsLValueRef*/ isLValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004491 if (ConvOvlResult == OR_Success)
4492 return;
Richard Smith6c6ddab2013-09-21 21:23:47 +00004493 if (ConvOvlResult != OR_No_Viable_Function)
John McCall0d1da222010-01-12 00:44:57 +00004494 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00004495 InitializationSequence::FK_ReferenceInitOverloadFailed,
4496 ConvOvlResult);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004497 }
4498 }
Sebastian Redld92badf2010-06-30 18:13:39 +00004499
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004500 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004501 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00004502 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004503 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00004504 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4505 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4506 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004507 Sequence.SetOverloadFailure(
4508 InitializationSequence::FK_ReferenceInitOverloadFailed,
4509 ConvOvlResult);
Richard Smithb8c0f552016-12-09 18:49:13 +00004510 else if (!InitCategory.isLValue())
4511 Sequence.SetFailed(
4512 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4513 else {
4514 InitializationSequence::FailureKind FK;
4515 switch (RefRelationship) {
4516 case Sema::Ref_Compatible:
4517 if (Initializer->refersToBitField())
4518 FK = InitializationSequence::
4519 FK_NonConstLValueReferenceBindingToBitfield;
4520 else if (Initializer->refersToVectorElement())
4521 FK = InitializationSequence::
4522 FK_NonConstLValueReferenceBindingToVectorElement;
4523 else
4524 llvm_unreachable("unexpected kind of compatible initializer");
4525 break;
4526 case Sema::Ref_Related:
4527 FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
4528 break;
4529 case Sema::Ref_Incompatible:
4530 FK = InitializationSequence::
4531 FK_NonConstLValueReferenceBindingToUnrelated;
4532 break;
4533 }
4534 Sequence.SetFailed(FK);
4535 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004536 return;
4537 }
Sebastian Redld92badf2010-06-30 18:13:39 +00004538
Douglas Gregor92e460e2011-01-20 16:44:54 +00004539 // - If the initializer expression
Richard Smithb8c0f552016-12-09 18:49:13 +00004540 // - is an
4541 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
4542 // [1z] rvalue (but not a bit-field) or
4543 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
4544 //
4545 // Note: functions are handled above and below rather than here...
Douglas Gregor92e460e2011-01-20 16:44:54 +00004546 if (!T1Function &&
Richard Smithce766292016-10-21 23:01:55 +00004547 (RefRelationship == Sema::Ref_Compatible ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004548 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004549 RefRelationship == Sema::Ref_Related)) &&
Richard Smithb8c0f552016-12-09 18:49:13 +00004550 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
Richard Smith122f88d2016-12-06 23:52:28 +00004551 (InitCategory.isPRValue() &&
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004552 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
Richard Smith122f88d2016-12-06 23:52:28 +00004553 T2->isArrayType())))) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004554 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_RValue;
Douglas Gregor92e460e2011-01-20 16:44:54 +00004555 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004556 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
4557 // compiler the freedom to perform a copy here or bind to the
4558 // object, while C++0x requires that we bind directly to the
4559 // object. Hence, we always bind to the object without making an
4560 // extra copy. However, in C++03 requires that we check for the
4561 // presence of a suitable copy constructor:
4562 //
4563 // The constructor that would be used to make the copy shall
4564 // be callable whether or not the copy is actually done.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004565 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004566 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004567 else if (S.getLangOpts().CPlusPlus11)
Richard Smithc620f552011-10-19 16:55:56 +00004568 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004569 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004570
Richard Smithb8c0f552016-12-09 18:49:13 +00004571 // C++1z [dcl.init.ref]/5.2.1.2:
4572 // If the converted initializer is a prvalue, its type T4 is adjusted
4573 // to type "cv1 T4" and the temporary materialization conversion is
4574 // applied.
4575 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1Quals);
4576 if (T1Quals != T2Quals)
4577 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
4578 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue);
4579 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
4580
4581 // In any case, the reference is bound to the resulting glvalue (or to
4582 // an appropriate base class subobject).
Douglas Gregor92e460e2011-01-20 16:44:54 +00004583 if (DerivedToBase)
Richard Smithb8c0f552016-12-09 18:49:13 +00004584 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
Douglas Gregor92e460e2011-01-20 16:44:54 +00004585 else if (ObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004586 Sequence.AddObjCObjectConversionStep(cv1T1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004587 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00004588 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004589
4590 // - has a class type (i.e., T2 is a class type), where T1 is not
4591 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00004592 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
4593 // where "cv1 T1" is reference-compatible with "cv3 T3",
Richard Smith6c6ddab2013-09-21 21:23:47 +00004594 //
4595 // DR1287 removes the "implicitly" here.
Douglas Gregor92e460e2011-01-20 16:44:54 +00004596 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004597 if (RefRelationship == Sema::Ref_Incompatible) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00004598 ConvOvlResult = TryRefInitWithConversionFunction(
Richard Smithb8c0f552016-12-09 18:49:13 +00004599 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
4600 /*IsLValueRef*/ isLValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004601 if (ConvOvlResult)
4602 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00004603 InitializationSequence::FK_ReferenceInitOverloadFailed,
4604 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004605
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004606 return;
4607 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004608
Richard Smithce766292016-10-21 23:01:55 +00004609 if (RefRelationship == Sema::Ref_Compatible &&
Douglas Gregor6fa6ab02013-03-26 23:59:23 +00004610 isRValueRef && InitCategory.isLValue()) {
4611 Sequence.SetFailed(
4612 InitializationSequence::FK_RValueReferenceBindingToLValue);
4613 return;
4614 }
4615
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004616 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4617 return;
4618 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004619
4620 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004621 // from the initializer expression using the rules for a non-reference
Richard Smith2eabf782013-06-13 00:57:57 +00004622 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004623 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00004624
John McCallec6f4e92010-06-04 02:29:22 +00004625 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4626
Richard Smith2eabf782013-06-13 00:57:57 +00004627 // FIXME: Why do we use an implicit conversion here rather than trying
4628 // copy-initialization?
John McCall31168b02011-06-15 23:02:42 +00004629 ImplicitConversionSequence ICS
4630 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith2eabf782013-06-13 00:57:57 +00004631 /*SuppressUserConversions=*/false,
4632 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004633 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004634 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4635 /*AllowObjCWritebackConversion=*/false);
4636
4637 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004638 // FIXME: Use the conversion function set stored in ICS to turn
4639 // this into an overloading ambiguity diagnostic. However, we need
4640 // to keep that set as an OverloadCandidateSet rather than as some
4641 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00004642 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4643 Sequence.SetOverloadFailure(
4644 InitializationSequence::FK_ReferenceInitOverloadFailed,
4645 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00004646 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4647 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00004648 else
4649 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004650 return;
John McCall31168b02011-06-15 23:02:42 +00004651 } else {
4652 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004653 }
4654
4655 // [...] If T1 is reference-related to T2, cv1 must be the
4656 // same cv-qualification as, or greater cv-qualification
4657 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00004658 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4659 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004660 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00004661 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004662 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4663 return;
4664 }
4665
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004666 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004667 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004668 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004669 InitCategory.isLValue()) {
4670 Sequence.SetFailed(
4671 InitializationSequence::FK_RValueReferenceBindingToLValue);
4672 return;
4673 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004674
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004675 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004676}
4677
4678/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004679/// (C++ [dcl.init.string], C99 6.7.8).
4680static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004681 const InitializedEntity &Entity,
4682 const InitializationKind &Kind,
4683 Expr *Initializer,
4684 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004685 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004686}
4687
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004688/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004689static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004690 const InitializedEntity &Entity,
4691 const InitializationKind &Kind,
Richard Smithd86812d2012-07-05 08:39:21 +00004692 InitializationSequence &Sequence,
4693 InitListExpr *InitList) {
4694 assert((!InitList || InitList->getNumInits() == 0) &&
4695 "Shouldn't use value-init for non-empty init lists");
4696
Richard Smith1bfe0682012-02-14 21:14:13 +00004697 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004698 //
4699 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00004700 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004701
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004702 // -- if T is an array type, then each element is value-initialized;
Richard Smith1bfe0682012-02-14 21:14:13 +00004703 T = S.Context.getBaseElementType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004704
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004705 if (const RecordType *RT = T->getAs<RecordType>()) {
4706 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithd86812d2012-07-05 08:39:21 +00004707 bool NeedZeroInitialization = true;
Richard Smith505ef812016-12-21 01:57:02 +00004708 // C++98:
4709 // -- if T is a class type (clause 9) with a user-declared constructor
4710 // (12.1), then the default constructor for T is called (and the
4711 // initialization is ill-formed if T has no accessible default
4712 // constructor);
4713 // C++11:
4714 // -- if T is a class type (clause 9) with either no default constructor
4715 // (12.1 [class.ctor]) or a default constructor that is user-provided
4716 // or deleted, then the object is default-initialized;
4717 //
4718 // Note that the C++11 rule is the same as the C++98 rule if there are no
4719 // defaulted or deleted constructors, so we just use it unconditionally.
4720 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4721 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
4722 NeedZeroInitialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004723
Richard Smith1bfe0682012-02-14 21:14:13 +00004724 // -- if T is a (possibly cv-qualified) non-union class type without a
4725 // user-provided or deleted default constructor, then the object is
4726 // zero-initialized and, if T has a non-trivial default constructor,
4727 // default-initialized;
Richard Smithfb266522012-10-18 00:44:17 +00004728 // The 'non-union' here was removed by DR1502. The 'non-trivial default
4729 // constructor' part was removed by DR1507.
Richard Smithd86812d2012-07-05 08:39:21 +00004730 if (NeedZeroInitialization)
4731 Sequence.AddZeroInitializationStep(Entity.getType());
4732
Richard Smith593f9932012-12-08 02:01:17 +00004733 // C++03:
4734 // -- if T is a non-union class type without a user-declared constructor,
4735 // then every non-static data member and base class component of T is
4736 // value-initialized;
4737 // [...] A program that calls for [...] value-initialization of an
4738 // entity of reference type is ill-formed.
4739 //
4740 // C++11 doesn't need this handling, because value-initialization does not
4741 // occur recursively there, and the implicit default constructor is
4742 // defined as deleted in the problematic cases.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004743 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smith593f9932012-12-08 02:01:17 +00004744 ClassDecl->hasUninitializedReferenceMember()) {
4745 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4746 return;
4747 }
4748
Richard Smithd86812d2012-07-05 08:39:21 +00004749 // If this is list-value-initialization, pass the empty init list on when
4750 // building the constructor call. This affects the semantics of a few
4751 // things (such as whether an explicit default constructor can be called).
4752 Expr *InitListAsExpr = InitList;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004753 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithd86812d2012-07-05 08:39:21 +00004754 bool InitListSyntax = InitList;
4755
Richard Smith81f5ade2016-12-15 02:28:18 +00004756 // FIXME: Instead of creating a CXXConstructExpr of array type here,
Richard Smith410306b2016-12-12 02:53:20 +00004757 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
4758 return TryConstructorInitialization(
4759 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004760 }
4761 }
4762
Douglas Gregor1b303932009-12-22 15:35:07 +00004763 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004764}
4765
Douglas Gregor85dabae2009-12-16 01:38:02 +00004766/// \brief Attempt default initialization (C++ [dcl.init]p6).
4767static void TryDefaultInitialization(Sema &S,
4768 const InitializedEntity &Entity,
4769 const InitializationKind &Kind,
4770 InitializationSequence &Sequence) {
4771 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004772
Douglas Gregor85dabae2009-12-16 01:38:02 +00004773 // C++ [dcl.init]p6:
4774 // To default-initialize an object of type T means:
4775 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00004776 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4777
Douglas Gregor85dabae2009-12-16 01:38:02 +00004778 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4779 // constructor for T is called (and the initialization is ill-formed if
4780 // T has no accessible default constructor);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004781 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Richard Smith410306b2016-12-12 02:53:20 +00004782 TryConstructorInitialization(S, Entity, Kind, None, DestType,
4783 Entity.getType(), Sequence);
Chandler Carruthc9262402010-08-23 07:55:51 +00004784 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004785 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004786
Douglas Gregor85dabae2009-12-16 01:38:02 +00004787 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004788
Douglas Gregor85dabae2009-12-16 01:38:02 +00004789 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004790 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00004791 // default constructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004792 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Nico Weber337d5aa2015-04-17 08:32:38 +00004793 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4794 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00004795 return;
4796 }
4797
4798 // If the destination type has a lifetime property, zero-initialize it.
4799 if (DestType.getQualifiers().hasObjCLifetime()) {
4800 Sequence.AddZeroInitializationStep(Entity.getType());
4801 return;
4802 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004803}
4804
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004805/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4806/// which enumerates all conversion functions and performs overload resolution
4807/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004808static void TryUserDefinedConversion(Sema &S,
Richard Smith77be48a2014-07-31 06:31:19 +00004809 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004810 const InitializationKind &Kind,
4811 Expr *Initializer,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004812 InitializationSequence &Sequence,
4813 bool TopLevelOfInitList) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004814 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4815 QualType SourceType = Initializer->getType();
4816 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4817 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004818
Douglas Gregor540c3b02009-12-14 17:27:33 +00004819 // Build the candidate set directly in the initialization sequence
4820 // structure, so that it will persist if we fail.
4821 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
Richard Smith67ef14f2017-09-26 18:37:55 +00004822 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004823
Douglas Gregor540c3b02009-12-14 17:27:33 +00004824 // Determine whether we are allowed to call explicit constructors or
4825 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00004826 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004827
Douglas Gregor540c3b02009-12-14 17:27:33 +00004828 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4829 // The type we're converting to is a class type. Enumerate its constructors
4830 // to see if there is a suitable conversion.
4831 CXXRecordDecl *DestRecordDecl
4832 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004833
Douglas Gregord9848152010-04-26 14:36:57 +00004834 // Try to complete the type we're converting to.
Richard Smithdb0ac552015-12-18 22:40:25 +00004835 if (S.isCompleteType(Kind.getLocation(), DestType)) {
Richard Smith776e9c32017-02-01 03:28:59 +00004836 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
Richard Smithc2bebe92016-05-11 20:37:46 +00004837 auto Info = getConstructorInfo(D);
4838 if (!Info.Constructor)
4839 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004840
Richard Smithc2bebe92016-05-11 20:37:46 +00004841 if (!Info.Constructor->isInvalidDecl() &&
4842 Info.Constructor->isConvertingConstructor(AllowExplicit)) {
4843 if (Info.ConstructorTmpl)
4844 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004845 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004846 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004847 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004848 else
Richard Smithc2bebe92016-05-11 20:37:46 +00004849 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004850 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004851 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004852 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004853 }
Douglas Gregord9848152010-04-26 14:36:57 +00004854 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004855 }
Eli Friedman78275202009-12-19 08:11:05 +00004856
4857 SourceLocation DeclLoc = Initializer->getLocStart();
4858
Douglas Gregor540c3b02009-12-14 17:27:33 +00004859 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4860 // The type we're converting from is a class type, enumerate its conversion
4861 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00004862
Eli Friedman4afe9a32009-12-20 22:12:03 +00004863 // We can only enumerate the conversion functions for a complete type; if
4864 // the type isn't complete, simply skip this step.
Richard Smithdb0ac552015-12-18 22:40:25 +00004865 if (S.isCompleteType(DeclLoc, SourceType)) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004866 CXXRecordDecl *SourceRecordDecl
4867 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004868
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004869 const auto &Conversions =
4870 SourceRecordDecl->getVisibleConversionFunctions();
4871 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004872 NamedDecl *D = *I;
4873 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4874 if (isa<UsingShadowDecl>(D))
4875 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004876
Eli Friedman4afe9a32009-12-20 22:12:03 +00004877 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4878 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00004879 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00004880 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00004881 else
John McCallda4458e2010-03-31 01:36:47 +00004882 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004883
Eli Friedman4afe9a32009-12-20 22:12:03 +00004884 if (AllowExplicit || !Conv->isExplicit()) {
4885 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004886 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004887 ActingDC, Initializer, DestType,
Douglas Gregor68782142013-12-18 21:46:16 +00004888 CandidateSet, AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004889 else
John McCalla0296f72010-03-19 07:35:19 +00004890 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004891 Initializer, DestType, CandidateSet,
4892 AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004893 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004894 }
4895 }
4896 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004897
4898 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004899 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00004900 if (OverloadingResult Result
Richard Smith67ef14f2017-09-26 18:37:55 +00004901 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004902 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004903 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00004904 Result);
4905 return;
4906 }
John McCall0d1da222010-01-12 00:44:57 +00004907
Douglas Gregor540c3b02009-12-14 17:27:33 +00004908 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004909 Function->setReferenced();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004910 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004911
Douglas Gregor540c3b02009-12-14 17:27:33 +00004912 if (isa<CXXConstructorDecl>(Function)) {
4913 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithb24f0672012-02-11 19:22:50 +00004914 // subsumed by the initialization. Per DR5, the created temporary is of the
4915 // cv-unqualified type of the destination.
4916 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4917 DestType.getUnqualifiedType(),
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004918 HadMultipleCandidates);
Richard Smithb8c0f552016-12-09 18:49:13 +00004919
4920 // C++14 and before:
4921 // - if the function is a constructor, the call initializes a temporary
4922 // of the cv-unqualified version of the destination type. The [...]
4923 // temporary [...] is then used to direct-initialize, according to the
4924 // rules above, the object that is the destination of the
4925 // copy-initialization.
4926 // Note that this just performs a simple object copy from the temporary.
4927 //
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004928 // C++17:
Richard Smithb8c0f552016-12-09 18:49:13 +00004929 // - if the function is a constructor, the call is a prvalue of the
4930 // cv-unqualified version of the destination type whose return object
4931 // is initialized by the constructor. The call is used to
4932 // direct-initialize, according to the rules above, the object that
4933 // is the destination of the copy-initialization.
4934 // Therefore we need to do nothing further.
4935 //
4936 // FIXME: Mark this copy as extraneous.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004937 if (!S.getLangOpts().CPlusPlus17)
Richard Smithb8c0f552016-12-09 18:49:13 +00004938 Sequence.AddFinalCopy(DestType);
Richard Smith16d31502016-12-21 01:31:56 +00004939 else if (DestType.hasQualifiers())
4940 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004941 return;
4942 }
4943
4944 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004945 QualType ConvType = Function->getCallResultType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004946 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4947 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004948
Richard Smithb8c0f552016-12-09 18:49:13 +00004949 if (ConvType->getAs<RecordType>()) {
4950 // The call is used to direct-initialize [...] the object that is the
4951 // destination of the copy-initialization.
4952 //
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004953 // In C++17, this does not call a constructor if we enter /17.6.1:
Richard Smithb8c0f552016-12-09 18:49:13 +00004954 // - If the initializer expression is a prvalue and the cv-unqualified
4955 // version of the source type is the same as the class of the
4956 // destination [... do not make an extra copy]
4957 //
4958 // FIXME: Mark this copy as extraneous.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004959 if (!S.getLangOpts().CPlusPlus17 ||
Richard Smithb8c0f552016-12-09 18:49:13 +00004960 Function->getReturnType()->isReferenceType() ||
4961 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
4962 Sequence.AddFinalCopy(DestType);
Richard Smith16d31502016-12-21 01:31:56 +00004963 else if (!S.Context.hasSameType(ConvType, DestType))
4964 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Richard Smithb8c0f552016-12-09 18:49:13 +00004965 return;
4966 }
4967
Douglas Gregor5ab11652010-04-17 22:01:05 +00004968 // If the conversion following the call to the conversion function
4969 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004970 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4971 Best->FinalConversion.Third) {
4972 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00004973 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00004974 ICS.Standard = Best->FinalConversion;
Richard Smithaaa0ec42013-09-21 21:19:19 +00004975 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004976 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004977}
4978
Richard Smithf032001b2013-06-20 02:18:31 +00004979/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4980/// a function with a pointer return type contains a 'return false;' statement.
4981/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4982/// code using that header.
4983///
4984/// Work around this by treating 'return false;' as zero-initializing the result
4985/// if it's used in a pointer-returning function in a system header.
4986static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4987 const InitializedEntity &Entity,
4988 const Expr *Init) {
4989 return S.getLangOpts().CPlusPlus11 &&
4990 Entity.getKind() == InitializedEntity::EK_Result &&
4991 Entity.getType()->isPointerType() &&
4992 isa<CXXBoolLiteralExpr>(Init) &&
4993 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4994 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4995}
4996
John McCall31168b02011-06-15 23:02:42 +00004997/// The non-zero enum values here are indexes into diagnostic alternatives.
4998enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4999
5000/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00005001static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005002 bool isAddressOf, bool &isWeakAccess) {
John McCall31168b02011-06-15 23:02:42 +00005003 // Skip parens.
5004 e = e->IgnoreParens();
5005
5006 // Skip address-of nodes.
5007 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
5008 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005009 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
5010 isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00005011
5012 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00005013 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
5014 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00005015 case CK_Dependent:
5016 case CK_BitCast:
5017 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00005018 case CK_NoOp:
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005019 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00005020
5021 case CK_ArrayToPointerDecay:
5022 return IIK_nonscalar;
5023
5024 case CK_NullToPointer:
5025 return IIK_okay;
5026
5027 default:
5028 break;
5029 }
5030
5031 // If we have a declaration reference, it had better be a local variable.
John McCall113bee02012-03-10 09:33:50 +00005032 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005033 // set isWeakAccess to true, to mean that there will be an implicit
5034 // load which requires a cleanup.
5035 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
5036 isWeakAccess = true;
5037
John McCall63f84442011-06-27 23:59:58 +00005038 if (!isAddressOf) return IIK_nonlocal;
5039
John McCall113bee02012-03-10 09:33:50 +00005040 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
5041 if (!var) return IIK_nonlocal;
John McCall63f84442011-06-27 23:59:58 +00005042
5043 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00005044
5045 // If we have a conditional operator, check both sides.
5046 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005047 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
5048 isWeakAccess))
John McCall31168b02011-06-15 23:02:42 +00005049 return iik;
5050
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005051 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00005052
5053 // These are never scalar.
5054 } else if (isa<ArraySubscriptExpr>(e)) {
5055 return IIK_nonscalar;
5056
5057 // Otherwise, it needs to be a null pointer constant.
5058 } else {
5059 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
5060 ? IIK_okay : IIK_nonlocal);
5061 }
5062
5063 return IIK_nonlocal;
5064}
5065
5066/// Check whether the given expression is a valid operand for an
5067/// indirect copy/restore.
5068static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
5069 assert(src->isRValue());
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005070 bool isWeakAccess = false;
5071 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
5072 // If isWeakAccess to true, there will be an implicit
5073 // load which requires a cleanup.
5074 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
Tim Shen4a05bb82016-06-21 20:29:17 +00005075 S.Cleanup.setExprNeedsCleanups(true);
5076
John McCall31168b02011-06-15 23:02:42 +00005077 if (iik == IIK_okay) return;
5078
5079 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
5080 << ((unsigned) iik - 1) // shift index into diagnostic explanations
5081 << src->getSourceRange();
5082}
5083
Douglas Gregore2f943b2011-02-22 18:29:51 +00005084/// \brief Determine whether we have compatible array types for the
5085/// purposes of GNU by-copy array initialization.
Larisse Voufod2010992015-01-24 23:09:54 +00005086static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
Douglas Gregore2f943b2011-02-22 18:29:51 +00005087 const ArrayType *Source) {
5088 // If the source and destination array types are equivalent, we're
5089 // done.
5090 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
5091 return true;
5092
5093 // Make sure that the element types are the same.
5094 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
5095 return false;
5096
5097 // The only mismatch we allow is when the destination is an
5098 // incomplete array type and the source is a constant array type.
5099 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
5100}
5101
John McCall31168b02011-06-15 23:02:42 +00005102static bool tryObjCWritebackConversion(Sema &S,
5103 InitializationSequence &Sequence,
5104 const InitializedEntity &Entity,
5105 Expr *Initializer) {
5106 bool ArrayDecay = false;
5107 QualType ArgType = Initializer->getType();
5108 QualType ArgPointee;
5109 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
5110 ArrayDecay = true;
5111 ArgPointee = ArgArrayType->getElementType();
5112 ArgType = S.Context.getPointerType(ArgPointee);
5113 }
5114
5115 // Handle write-back conversion.
5116 QualType ConvertedArgType;
5117 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
5118 ConvertedArgType))
5119 return false;
5120
5121 // We should copy unless we're passing to an argument explicitly
5122 // marked 'out'.
5123 bool ShouldCopy = true;
5124 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5125 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5126
5127 // Do we need an lvalue conversion?
5128 if (ArrayDecay || Initializer->isGLValue()) {
5129 ImplicitConversionSequence ICS;
5130 ICS.setStandard();
5131 ICS.Standard.setAsIdentityConversion();
5132
5133 QualType ResultType;
5134 if (ArrayDecay) {
5135 ICS.Standard.First = ICK_Array_To_Pointer;
5136 ResultType = S.Context.getPointerType(ArgPointee);
5137 } else {
5138 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
5139 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
5140 }
5141
5142 Sequence.AddConversionSequenceStep(ICS, ResultType);
5143 }
5144
5145 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
5146 return true;
5147}
5148
Guy Benyei61054192013-02-07 10:55:47 +00005149static bool TryOCLSamplerInitialization(Sema &S,
5150 InitializationSequence &Sequence,
5151 QualType DestType,
5152 Expr *Initializer) {
5153 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00005154 (!Initializer->isIntegerConstantExpr(S.Context) &&
5155 !Initializer->getType()->isSamplerT()))
Guy Benyei61054192013-02-07 10:55:47 +00005156 return false;
5157
5158 Sequence.AddOCLSamplerInitStep(DestType);
5159 return true;
5160}
5161
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005162//
5163// OpenCL 1.2 spec, s6.12.10
5164//
5165// The event argument can also be used to associate the
5166// async_work_group_copy with a previous async copy allowing
5167// an event to be shared by multiple async copies; otherwise
5168// event should be zero.
5169//
5170static bool TryOCLZeroEventInitialization(Sema &S,
5171 InitializationSequence &Sequence,
5172 QualType DestType,
5173 Expr *Initializer) {
5174 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
5175 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
5176 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
5177 return false;
5178
5179 Sequence.AddOCLZeroEventStep(DestType);
5180 return true;
5181}
5182
Egor Churaev89831422016-12-23 14:55:49 +00005183static bool TryOCLZeroQueueInitialization(Sema &S,
5184 InitializationSequence &Sequence,
5185 QualType DestType,
5186 Expr *Initializer) {
5187 if (!S.getLangOpts().OpenCL || S.getLangOpts().OpenCLVersion < 200 ||
5188 !DestType->isQueueT() ||
5189 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
5190 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
5191 return false;
5192
5193 Sequence.AddOCLZeroQueueStep(DestType);
5194 return true;
5195}
5196
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005197InitializationSequence::InitializationSequence(Sema &S,
5198 const InitializedEntity &Entity,
5199 const InitializationKind &Kind,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005200 MultiExprArg Args,
Manman Ren073db022016-03-10 18:53:19 +00005201 bool TopLevelOfInitList,
5202 bool TreatUnavailableAsInvalid)
Richard Smith100b24a2014-04-17 01:52:14 +00005203 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
Manman Ren073db022016-03-10 18:53:19 +00005204 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
5205 TreatUnavailableAsInvalid);
Richard Smith089c3162013-09-21 21:55:46 +00005206}
5207
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005208/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
5209/// address of that function, this returns true. Otherwise, it returns false.
5210static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
5211 auto *DRE = dyn_cast<DeclRefExpr>(E);
5212 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
5213 return false;
5214
5215 return !S.checkAddressOfFunctionIsAvailable(
5216 cast<FunctionDecl>(DRE->getDecl()));
5217}
5218
Richard Smith410306b2016-12-12 02:53:20 +00005219/// Determine whether we can perform an elementwise array copy for this kind
5220/// of entity.
5221static bool canPerformArrayCopy(const InitializedEntity &Entity) {
5222 switch (Entity.getKind()) {
5223 case InitializedEntity::EK_LambdaCapture:
5224 // C++ [expr.prim.lambda]p24:
5225 // For array members, the array elements are direct-initialized in
5226 // increasing subscript order.
5227 return true;
5228
5229 case InitializedEntity::EK_Variable:
5230 // C++ [dcl.decomp]p1:
5231 // [...] each element is copy-initialized or direct-initialized from the
5232 // corresponding element of the assignment-expression [...]
5233 return isa<DecompositionDecl>(Entity.getDecl());
5234
5235 case InitializedEntity::EK_Member:
5236 // C++ [class.copy.ctor]p14:
5237 // - if the member is an array, each element is direct-initialized with
5238 // the corresponding subobject of x
5239 return Entity.isImplicitMemberInitializer();
5240
5241 case InitializedEntity::EK_ArrayElement:
5242 // All the above cases are intended to apply recursively, even though none
5243 // of them actually say that.
5244 if (auto *E = Entity.getParent())
5245 return canPerformArrayCopy(*E);
5246 break;
5247
5248 default:
5249 break;
5250 }
5251
5252 return false;
5253}
5254
Richard Smith089c3162013-09-21 21:55:46 +00005255void InitializationSequence::InitializeFrom(Sema &S,
5256 const InitializedEntity &Entity,
5257 const InitializationKind &Kind,
5258 MultiExprArg Args,
Manman Ren073db022016-03-10 18:53:19 +00005259 bool TopLevelOfInitList,
5260 bool TreatUnavailableAsInvalid) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005261 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005262
John McCall5e77d762013-04-16 07:28:30 +00005263 // Eliminate non-overload placeholder types in the arguments. We
5264 // need to do this before checking whether types are dependent
5265 // because lowering a pseudo-object expression might well give us
5266 // something of dependent type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005267 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall5e77d762013-04-16 07:28:30 +00005268 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
5269 // FIXME: should we be doing this here?
5270 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
5271 if (result.isInvalid()) {
5272 SetFailed(FK_PlaceholderType);
5273 return;
5274 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005275 Args[I] = result.get();
John McCall5e77d762013-04-16 07:28:30 +00005276 }
5277
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005278 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005279 // The semantics of initializers are as follows. The destination type is
5280 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005281 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005282 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005283 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005284 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005285
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005286 if (DestType->isDependentType() ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005287 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005288 SequenceKind = DependentSequence;
5289 return;
5290 }
5291
Sebastian Redld201edf2011-06-05 13:59:11 +00005292 // Almost everything is a normal sequence.
5293 setSequenceKind(NormalSequence);
5294
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005295 QualType SourceType;
Craig Topperc3ec1492014-05-26 06:22:03 +00005296 Expr *Initializer = nullptr;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005297 if (Args.size() == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005298 Initializer = Args[0];
Fariborz Jahanian283bf892013-12-18 21:04:43 +00005299 if (S.getLangOpts().ObjC1) {
5300 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
5301 DestType, Initializer->getType(),
5302 Initializer) ||
5303 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
5304 Args[0] = Initializer;
Fariborz Jahanian283bf892013-12-18 21:04:43 +00005305 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005306 if (!isa<InitListExpr>(Initializer))
5307 SourceType = Initializer->getType();
5308 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005309
Sebastian Redl0501c632012-02-12 16:37:36 +00005310 // - If the initializer is a (non-parenthesized) braced-init-list, the
5311 // object is list-initialized (8.5.4).
5312 if (Kind.getKind() != InitializationKind::IK_Direct) {
5313 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Manman Ren073db022016-03-10 18:53:19 +00005314 TryListInitialization(S, Entity, Kind, InitList, *this,
5315 TreatUnavailableAsInvalid);
Sebastian Redl0501c632012-02-12 16:37:36 +00005316 return;
5317 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005318 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005319
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005320 // - If the destination type is a reference type, see 8.5.3.
5321 if (DestType->isReferenceType()) {
5322 // C++0x [dcl.init.ref]p1:
5323 // A variable declared to be a T& or T&&, that is, "reference to type T"
5324 // (8.3.2), shall be initialized by an object, or function, of type T or
5325 // by an object that can be converted into a T.
5326 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005327 if (Args.size() != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005328 SetFailed(FK_TooManyInitsForReference);
Richard Smith49a6b6e2017-03-24 01:14:25 +00005329 // C++17 [dcl.init.ref]p5:
5330 // A reference [...] is initialized by an expression [...] as follows:
5331 // If the initializer is not an expression, presumably we should reject,
5332 // but the standard fails to actually say so.
5333 else if (isa<InitListExpr>(Args[0]))
5334 SetFailed(FK_ParenthesizedListInitForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005335 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005336 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005337 return;
5338 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005339
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005340 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00005341 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005342 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005343 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005344 return;
5345 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005346
Douglas Gregor85dabae2009-12-16 01:38:02 +00005347 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00005348 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005349 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005350 return;
5351 }
Douglas Gregore1314a62009-12-18 05:02:21 +00005352
John McCall66884dd2011-02-21 07:22:22 +00005353 // - If the destination type is an array of characters, an array of
5354 // char16_t, an array of char32_t, or an array of wchar_t, and the
5355 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005356 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005357 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00005358 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00005359 if (Initializer && isa<VariableArrayType>(DestAT)) {
5360 SetFailed(FK_VariableLengthArrayHasInitializer);
5361 return;
5362 }
5363
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005364 if (Initializer) {
5365 switch (IsStringInit(Initializer, DestAT, Context)) {
5366 case SIF_None:
5367 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
5368 return;
5369 case SIF_NarrowStringIntoWideChar:
5370 SetFailed(FK_NarrowStringIntoWideCharArray);
5371 return;
5372 case SIF_WideStringIntoChar:
5373 SetFailed(FK_WideStringIntoCharArray);
5374 return;
5375 case SIF_IncompatWideStringIntoWideChar:
5376 SetFailed(FK_IncompatWideStringIntoWideChar);
5377 return;
Richard Smith3a8244d2018-05-01 05:02:45 +00005378 case SIF_PlainStringIntoUTF8Char:
5379 SetFailed(FK_PlainStringIntoUTF8Char);
5380 return;
5381 case SIF_UTF8StringIntoPlainChar:
5382 SetFailed(FK_UTF8StringIntoPlainChar);
5383 return;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005384 case SIF_Other:
5385 break;
5386 }
John McCall66884dd2011-02-21 07:22:22 +00005387 }
5388
Richard Smith410306b2016-12-12 02:53:20 +00005389 // Some kinds of initialization permit an array to be initialized from
5390 // another array of the same type, and perform elementwise initialization.
5391 if (Initializer && isa<ConstantArrayType>(DestAT) &&
5392 S.Context.hasSameUnqualifiedType(Initializer->getType(),
5393 Entity.getType()) &&
5394 canPerformArrayCopy(Entity)) {
5395 // If source is a prvalue, use it directly.
5396 if (Initializer->getValueKind() == VK_RValue) {
Richard Smith378b8c82016-12-14 03:22:16 +00005397 AddArrayInitStep(DestType, /*IsGNUExtension*/false);
Richard Smith410306b2016-12-12 02:53:20 +00005398 return;
5399 }
5400
5401 // Emit element-at-a-time copy loop.
5402 InitializedEntity Element =
5403 InitializedEntity::InitializeElement(S.Context, 0, Entity);
5404 QualType InitEltT =
5405 Context.getAsArrayType(Initializer->getType())->getElementType();
Richard Smith30e304e2016-12-14 00:03:17 +00005406 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
5407 Initializer->getValueKind(),
5408 Initializer->getObjectKind());
Richard Smith410306b2016-12-12 02:53:20 +00005409 Expr *OVEAsExpr = &OVE;
5410 InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
5411 TreatUnavailableAsInvalid);
5412 if (!Failed())
5413 AddArrayInitLoopStep(Entity.getType(), InitEltT);
5414 return;
5415 }
5416
Douglas Gregore2f943b2011-02-22 18:29:51 +00005417 // Note: as an GNU C extension, we allow initialization of an
5418 // array from a compound literal that creates an array of the same
5419 // type, so long as the initializer has no side effects.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005420 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregore2f943b2011-02-22 18:29:51 +00005421 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
5422 Initializer->getType()->isArrayType()) {
5423 const ArrayType *SourceAT
5424 = Context.getAsArrayType(Initializer->getType());
5425 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005426 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005427 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005428 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005429 else {
Richard Smith378b8c82016-12-14 03:22:16 +00005430 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005431 }
Richard Smithebeed412012-02-15 22:38:09 +00005432 }
Richard Smithd86812d2012-07-05 08:39:21 +00005433 // Note: as a GNU C++ extension, we allow list-initialization of a
5434 // class member of array type from a parenthesized initializer list.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005435 else if (S.getLangOpts().CPlusPlus &&
Richard Smithebeed412012-02-15 22:38:09 +00005436 Entity.getKind() == InitializedEntity::EK_Member &&
5437 Initializer && isa<InitListExpr>(Initializer)) {
5438 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
Manman Ren073db022016-03-10 18:53:19 +00005439 *this, TreatUnavailableAsInvalid);
Richard Smithebeed412012-02-15 22:38:09 +00005440 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005441 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005442 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005443 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
5444 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005445 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005446 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005447
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005448 return;
5449 }
Eli Friedman78275202009-12-19 08:11:05 +00005450
Larisse Voufod2010992015-01-24 23:09:54 +00005451 // Determine whether we should consider writeback conversions for
John McCall31168b02011-06-15 23:02:42 +00005452 // Objective-C ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005453 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005454 Entity.isParameterKind();
John McCall31168b02011-06-15 23:02:42 +00005455
5456 // We're at the end of the line for C: it's either a write-back conversion
5457 // or it's a C assignment. There's no need to check anything else.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005458 if (!S.getLangOpts().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00005459 // If allowed, check whether this is an Objective-C writeback conversion.
5460 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005461 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00005462 return;
5463 }
Guy Benyei61054192013-02-07 10:55:47 +00005464
5465 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
5466 return;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005467
5468 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
5469 return;
5470
Egor Churaev89831422016-12-23 14:55:49 +00005471 if (TryOCLZeroQueueInitialization(S, *this, DestType, Initializer))
5472 return;
5473
John McCall31168b02011-06-15 23:02:42 +00005474 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005475 AddCAssignmentStep(DestType);
5476 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00005477 return;
5478 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005479
David Blaikiebbafb8a2012-03-11 07:00:24 +00005480 assert(S.getLangOpts().CPlusPlus);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005481
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005482 // - If the destination type is a (possibly cv-qualified) class type:
5483 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005484 // - If the initialization is direct-initialization, or if it is
5485 // copy-initialization where the cv-unqualified version of the
5486 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005487 // class of the destination, constructors are considered. [...]
5488 if (Kind.getKind() == InitializationKind::IK_Direct ||
5489 (Kind.getKind() == InitializationKind::IK_Copy &&
5490 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005491 S.IsDerivedFrom(Initializer->getLocStart(), SourceType, DestType))))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005492 TryConstructorInitialization(S, Entity, Kind, Args,
Richard Smith410306b2016-12-12 02:53:20 +00005493 DestType, DestType, *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005494 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005495 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005496 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005497 // used) to a derived class thereof are enumerated as described in
5498 // 13.3.1.4, and the best one is chosen through overload resolution
5499 // (13.3).
5500 else
Richard Smith77be48a2014-07-31 06:31:19 +00005501 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005502 TopLevelOfInitList);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005503 return;
5504 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005505
Richard Smith49a6b6e2017-03-24 01:14:25 +00005506 assert(Args.size() >= 1 && "Zero-argument case handled above");
5507
5508 // The remaining cases all need a source type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005509 if (Args.size() > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005510 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005511 return;
Richard Smith49a6b6e2017-03-24 01:14:25 +00005512 } else if (isa<InitListExpr>(Args[0])) {
5513 SetFailed(FK_ParenthesizedListInitForScalar);
5514 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00005515 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005516
5517 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005518 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00005519 if (!SourceType.isNull() && SourceType->isRecordType()) {
Richard Smith77be48a2014-07-31 06:31:19 +00005520 // For a conversion to _Atomic(T) from either T or a class type derived
5521 // from T, initialize the T object then convert to _Atomic type.
5522 bool NeedAtomicConversion = false;
5523 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
5524 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005525 S.IsDerivedFrom(Initializer->getLocStart(), SourceType,
5526 Atomic->getValueType())) {
Richard Smith77be48a2014-07-31 06:31:19 +00005527 DestType = Atomic->getValueType();
5528 NeedAtomicConversion = true;
5529 }
5530 }
5531
5532 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005533 TopLevelOfInitList);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005534 MaybeProduceObjCObject(S, *this, Entity);
Richard Smith77be48a2014-07-31 06:31:19 +00005535 if (!Failed() && NeedAtomicConversion)
5536 AddAtomicConversionStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005537 return;
5538 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005539
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005540 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00005541 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005542 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005543 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005544 // destination type; no user-defined conversions are considered.
Richard Smith77be48a2014-07-31 06:31:19 +00005545
John McCall31168b02011-06-15 23:02:42 +00005546 ImplicitConversionSequence ICS
Richard Smith77be48a2014-07-31 06:31:19 +00005547 = S.TryImplicitConversion(Initializer, DestType,
John McCall31168b02011-06-15 23:02:42 +00005548 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00005549 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00005550 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00005551 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5552 allowObjCWritebackConversion);
Richard Smith77be48a2014-07-31 06:31:19 +00005553
5554 if (ICS.isStandard() &&
John McCall31168b02011-06-15 23:02:42 +00005555 ICS.Standard.Second == ICK_Writeback_Conversion) {
5556 // Objective-C ARC writeback conversion.
5557
5558 // We should copy unless we're passing to an argument explicitly
5559 // marked 'out'.
5560 bool ShouldCopy = true;
5561 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5562 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5563
5564 // If there was an lvalue adjustment, add it as a separate conversion.
5565 if (ICS.Standard.First == ICK_Array_To_Pointer ||
5566 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5567 ImplicitConversionSequence LvalueICS;
5568 LvalueICS.setStandard();
5569 LvalueICS.Standard.setAsIdentityConversion();
5570 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
5571 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005572 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00005573 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005574
Richard Smith77be48a2014-07-31 06:31:19 +00005575 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00005576 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00005577 DeclAccessPair dap;
Richard Smithf032001b2013-06-20 02:18:31 +00005578 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
5579 AddZeroInitializationStep(Entity.getType());
5580 } else if (Initializer->getType() == Context.OverloadTy &&
5581 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
5582 false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005583 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005584 else if (Initializer->getType()->isFunctionType() &&
5585 isExprAnUnaddressableFunction(S, Initializer))
5586 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
Douglas Gregore81f58e2010-11-08 03:40:48 +00005587 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005588 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00005589 } else {
Richard Smith77be48a2014-07-31 06:31:19 +00005590 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
John McCallfa272342011-06-16 23:24:51 +00005591
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005592 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00005593 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005594}
5595
5596InitializationSequence::~InitializationSequence() {
Davide Italiano67bb9f72015-07-01 21:51:58 +00005597 for (auto &S : Steps)
5598 S.Destroy();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005599}
5600
5601//===----------------------------------------------------------------------===//
5602// Perform initialization
5603//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005604static Sema::AssignmentAction
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005605getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005606 switch(Entity.getKind()) {
5607 case InitializedEntity::EK_Variable:
5608 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00005609 case InitializedEntity::EK_Exception:
5610 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005611 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00005612 return Sema::AA_Initializing;
5613
5614 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005615 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00005616 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5617 return Sema::AA_Sending;
5618
Douglas Gregore1314a62009-12-18 05:02:21 +00005619 return Sema::AA_Passing;
5620
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005621 case InitializedEntity::EK_Parameter_CF_Audited:
5622 if (Entity.getDecl() &&
5623 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5624 return Sema::AA_Sending;
5625
5626 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
5627
Douglas Gregore1314a62009-12-18 05:02:21 +00005628 case InitializedEntity::EK_Result:
5629 return Sema::AA_Returning;
5630
Douglas Gregore1314a62009-12-18 05:02:21 +00005631 case InitializedEntity::EK_Temporary:
Fariborz Jahanian14e95412013-07-11 19:13:34 +00005632 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00005633 // FIXME: Can we tell apart casting vs. converting?
5634 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005635
Douglas Gregore1314a62009-12-18 05:02:21 +00005636 case InitializedEntity::EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00005637 case InitializedEntity::EK_Binding:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00005638 case InitializedEntity::EK_ArrayElement:
5639 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005640 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005641 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005642 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005643 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005644 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00005645 return Sema::AA_Initializing;
5646 }
5647
David Blaikie8a40f702012-01-17 06:56:22 +00005648 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00005649}
5650
Richard Smith27874d62013-01-08 00:08:23 +00005651/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor95562572010-04-24 23:45:46 +00005652/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005653static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005654 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00005655 case InitializedEntity::EK_ArrayElement:
5656 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005657 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00005658 case InitializedEntity::EK_New:
5659 case InitializedEntity::EK_Variable:
5660 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005661 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00005662 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005663 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00005664 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005665 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005666 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005667 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005668 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00005669 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005670
Douglas Gregore1314a62009-12-18 05:02:21 +00005671 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005672 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregore1314a62009-12-18 05:02:21 +00005673 case InitializedEntity::EK_Temporary:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005674 case InitializedEntity::EK_RelatedResult:
Richard Smith7873de02016-08-11 22:25:46 +00005675 case InitializedEntity::EK_Binding:
Douglas Gregore1314a62009-12-18 05:02:21 +00005676 return true;
5677 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005678
Douglas Gregore1314a62009-12-18 05:02:21 +00005679 llvm_unreachable("missed an InitializedEntity kind?");
5680}
5681
Douglas Gregor95562572010-04-24 23:45:46 +00005682/// \brief Whether the given entity, when initialized with an object
5683/// created for that initialization, requires destruction.
Richard Smithb8c0f552016-12-09 18:49:13 +00005684static bool shouldDestroyEntity(const InitializedEntity &Entity) {
Douglas Gregor95562572010-04-24 23:45:46 +00005685 switch (Entity.getKind()) {
Douglas Gregor95562572010-04-24 23:45:46 +00005686 case InitializedEntity::EK_Result:
5687 case InitializedEntity::EK_New:
5688 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005689 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00005690 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005691 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005692 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005693 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005694 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor95562572010-04-24 23:45:46 +00005695 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005696
Richard Smith27874d62013-01-08 00:08:23 +00005697 case InitializedEntity::EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00005698 case InitializedEntity::EK_Binding:
Douglas Gregor95562572010-04-24 23:45:46 +00005699 case InitializedEntity::EK_Variable:
5700 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005701 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor95562572010-04-24 23:45:46 +00005702 case InitializedEntity::EK_Temporary:
5703 case InitializedEntity::EK_ArrayElement:
5704 case InitializedEntity::EK_Exception:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005705 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005706 case InitializedEntity::EK_RelatedResult:
Douglas Gregor95562572010-04-24 23:45:46 +00005707 return true;
5708 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005709
5710 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00005711}
5712
Richard Smithc620f552011-10-19 16:55:56 +00005713/// \brief Get the location at which initialization diagnostics should appear.
5714static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
5715 Expr *Initializer) {
5716 switch (Entity.getKind()) {
5717 case InitializedEntity::EK_Result:
5718 return Entity.getReturnLoc();
5719
5720 case InitializedEntity::EK_Exception:
5721 return Entity.getThrowLoc();
5722
5723 case InitializedEntity::EK_Variable:
Richard Smith7873de02016-08-11 22:25:46 +00005724 case InitializedEntity::EK_Binding:
Richard Smithc620f552011-10-19 16:55:56 +00005725 return Entity.getDecl()->getLocation();
5726
Douglas Gregor19666fb2012-02-15 16:57:26 +00005727 case InitializedEntity::EK_LambdaCapture:
5728 return Entity.getCaptureLoc();
5729
Richard Smithc620f552011-10-19 16:55:56 +00005730 case InitializedEntity::EK_ArrayElement:
5731 case InitializedEntity::EK_Member:
5732 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005733 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithc620f552011-10-19 16:55:56 +00005734 case InitializedEntity::EK_Temporary:
5735 case InitializedEntity::EK_New:
5736 case InitializedEntity::EK_Base:
5737 case InitializedEntity::EK_Delegating:
5738 case InitializedEntity::EK_VectorElement:
5739 case InitializedEntity::EK_ComplexElement:
5740 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005741 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005742 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005743 case InitializedEntity::EK_RelatedResult:
Richard Smithc620f552011-10-19 16:55:56 +00005744 return Initializer->getLocStart();
5745 }
5746 llvm_unreachable("missed an InitializedEntity kind?");
5747}
5748
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005749/// \brief Make a (potentially elidable) temporary copy of the object
5750/// provided by the given initializer by calling the appropriate copy
5751/// constructor.
5752///
5753/// \param S The Sema object used for type-checking.
5754///
Abramo Bagnara92141d22011-01-27 19:55:10 +00005755/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005756/// the type of the initializer expression or a superclass thereof.
5757///
James Dennett634962f2012-06-14 21:40:34 +00005758/// \param Entity The entity being initialized.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005759///
5760/// \param CurInit The initializer expression.
5761///
5762/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5763/// is permitted in C++03 (but not C++0x) when binding a reference to
5764/// an rvalue.
5765///
5766/// \returns An expression that copies the initializer expression into
5767/// a temporary object, or an error expression if a copy could not be
5768/// created.
John McCalldadc5752010-08-24 06:29:42 +00005769static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005770 QualType T,
5771 const InitializedEntity &Entity,
5772 ExprResult CurInit,
5773 bool IsExtraneousCopy) {
Fariborz Jahanian36f7f132015-01-28 22:08:10 +00005774 if (CurInit.isInvalid())
5775 return CurInit;
Douglas Gregor5ab11652010-04-17 22:01:05 +00005776 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00005777 Expr *CurInitExpr = (Expr *)CurInit.get();
Craig Topperc3ec1492014-05-26 06:22:03 +00005778 CXXRecordDecl *Class = nullptr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005779 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005780 Class = cast<CXXRecordDecl>(Record->getDecl());
5781 if (!Class)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005782 return CurInit;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005783
Richard Smithc620f552011-10-19 16:55:56 +00005784 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00005785
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005786 // Make sure that the type we are copying is complete.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005787 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005788 return CurInit;
Douglas Gregord5c231e2010-04-24 21:09:25 +00005789
Richard Smith7c2bcc92016-09-07 02:14:33 +00005790 // Perform overload resolution using the class's constructors. Per
5791 // C++11 [dcl.init]p16, second bullet for class types, this initialization
Richard Smithc620f552011-10-19 16:55:56 +00005792 // is direct-initialization.
Richard Smith100b24a2014-04-17 01:52:14 +00005793 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smith7c2bcc92016-09-07 02:14:33 +00005794 DeclContext::lookup_result Ctors = S.LookupConstructors(Class);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005795
Douglas Gregore1314a62009-12-18 05:02:21 +00005796 OverloadCandidateSet::iterator Best;
Richard Smith7c2bcc92016-09-07 02:14:33 +00005797 switch (ResolveConstructorOverload(
Richard Smith67ef14f2017-09-26 18:37:55 +00005798 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
Richard Smith7c2bcc92016-09-07 02:14:33 +00005799 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
5800 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
5801 /*SecondStepOfCopyInit=*/true)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005802 case OR_Success:
5803 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005804
Douglas Gregore1314a62009-12-18 05:02:21 +00005805 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005806 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
5807 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
5808 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005809 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005810 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005811 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005812 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00005813 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005814 return CurInit;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005815
Douglas Gregore1314a62009-12-18 05:02:21 +00005816 case OR_Ambiguous:
5817 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005818 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005819 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005820 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallfaf5fb42010-08-26 23:41:50 +00005821 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005822
Douglas Gregore1314a62009-12-18 05:02:21 +00005823 case OR_Deleted:
5824 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005825 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005826 << CurInitExpr->getSourceRange();
Richard Smith852265f2012-03-30 20:53:28 +00005827 S.NoteDeletedFunction(Best->Function);
John McCallfaf5fb42010-08-26 23:41:50 +00005828 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005829 }
5830
Richard Smith7c2bcc92016-09-07 02:14:33 +00005831 bool HadMultipleCandidates = CandidateSet.size() > 1;
5832
Douglas Gregor5ab11652010-04-17 22:01:05 +00005833 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramerf0623432012-08-23 22:51:59 +00005834 SmallVector<Expr*, 8> ConstructorArgs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005835 CurInit.get(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005836
Richard Smith5179eb72016-06-28 19:03:57 +00005837 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
5838 IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005839
5840 if (IsExtraneousCopy) {
5841 // If this is a totally extraneous copy for C++03 reference
5842 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00005843 // expression. We don't generate an (elided) copy operation here
5844 // because doing so would require us to pass down a flag to avoid
5845 // infinite recursion, where each step adds another extraneous,
5846 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005847
Douglas Gregor30b52772010-04-18 07:57:34 +00005848 // Instantiate the default arguments of any extra parameters in
5849 // the selected copy constructor, as if we were going to create a
5850 // proper call to the copy constructor.
5851 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5852 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5853 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005854 diag::err_call_incomplete_argument))
Douglas Gregor30b52772010-04-18 07:57:34 +00005855 break;
5856
5857 // Build the default argument expression; we don't actually care
5858 // if this succeeds or not, because this routine will complain
5859 // if there was a problem.
5860 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5861 }
5862
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005863 return CurInitExpr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005864 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005865
Douglas Gregor5ab11652010-04-17 22:01:05 +00005866 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005867 // constructor call (we might have derived-to-base conversions, or
5868 // the copy constructor may have default arguments).
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005869 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005870 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005871
Richard Smith7c2bcc92016-09-07 02:14:33 +00005872 // C++0x [class.copy]p32:
5873 // When certain criteria are met, an implementation is allowed to
5874 // omit the copy/move construction of a class object, even if the
5875 // copy/move constructor and/or destructor for the object have
5876 // side effects. [...]
5877 // - when a temporary class object that has not been bound to a
5878 // reference (12.2) would be copied/moved to a class object
5879 // with the same cv-unqualified type, the copy/move operation
5880 // can be omitted by constructing the temporary object
5881 // directly into the target of the omitted copy/move
5882 //
5883 // Note that the other three bullets are handled elsewhere. Copy
5884 // elision for return statements and throw expressions are handled as part
5885 // of constructor initialization, while copy elision for exception handlers
5886 // is handled by the run-time.
5887 //
5888 // FIXME: If the function parameter is not the same type as the temporary, we
5889 // should still be able to elide the copy, but we don't have a way to
5890 // represent in the AST how much should be elided in this case.
5891 bool Elidable =
5892 CurInitExpr->isTemporaryObject(S.Context, Class) &&
5893 S.Context.hasSameUnqualifiedType(
5894 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
5895 CurInitExpr->getType());
5896
Douglas Gregord0ace022010-04-25 00:55:24 +00005897 // Actually perform the constructor call.
Richard Smithc2bebe92016-05-11 20:37:46 +00005898 CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor,
5899 Elidable,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005900 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005901 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005902 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005903 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005904 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005905 CXXConstructExpr::CK_Complete,
5906 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005907
Douglas Gregord0ace022010-04-25 00:55:24 +00005908 // If we're supposed to bind temporaries, do so.
5909 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005910 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005911 return CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00005912}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005913
Richard Smithc620f552011-10-19 16:55:56 +00005914/// \brief Check whether elidable copy construction for binding a reference to
5915/// a temporary would have succeeded if we were building in C++98 mode, for
5916/// -Wc++98-compat.
5917static void CheckCXX98CompatAccessibleCopy(Sema &S,
5918 const InitializedEntity &Entity,
5919 Expr *CurInitExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005920 assert(S.getLangOpts().CPlusPlus11);
Richard Smithc620f552011-10-19 16:55:56 +00005921
5922 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5923 if (!Record)
5924 return;
5925
5926 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005927 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
Richard Smithc620f552011-10-19 16:55:56 +00005928 return;
5929
5930 // Find constructors which would have been considered.
Richard Smith100b24a2014-04-17 01:52:14 +00005931 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smith7c2bcc92016-09-07 02:14:33 +00005932 DeclContext::lookup_result Ctors =
5933 S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
Richard Smithc620f552011-10-19 16:55:56 +00005934
5935 // Perform overload resolution.
5936 OverloadCandidateSet::iterator Best;
Richard Smith7c2bcc92016-09-07 02:14:33 +00005937 OverloadingResult OR = ResolveConstructorOverload(
Richard Smith67ef14f2017-09-26 18:37:55 +00005938 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
Richard Smith7c2bcc92016-09-07 02:14:33 +00005939 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
5940 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
5941 /*SecondStepOfCopyInit=*/true);
Richard Smithc620f552011-10-19 16:55:56 +00005942
5943 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5944 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5945 << CurInitExpr->getSourceRange();
5946
5947 switch (OR) {
5948 case OR_Success:
5949 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
Richard Smith5179eb72016-06-28 19:03:57 +00005950 Best->FoundDecl, Entity, Diag);
Richard Smithc620f552011-10-19 16:55:56 +00005951 // FIXME: Check default arguments as far as that's possible.
5952 break;
5953
5954 case OR_No_Viable_Function:
5955 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005956 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005957 break;
5958
5959 case OR_Ambiguous:
5960 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005961 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005962 break;
5963
5964 case OR_Deleted:
5965 S.Diag(Loc, Diag);
Richard Smith852265f2012-03-30 20:53:28 +00005966 S.NoteDeletedFunction(Best->Function);
Richard Smithc620f552011-10-19 16:55:56 +00005967 break;
5968 }
5969}
5970
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005971void InitializationSequence::PrintInitLocationNote(Sema &S,
5972 const InitializedEntity &Entity) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005973 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005974 if (Entity.getDecl()->getLocation().isInvalid())
5975 return;
5976
5977 if (Entity.getDecl()->getDeclName())
5978 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5979 << Entity.getDecl()->getDeclName();
5980 else
5981 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5982 }
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005983 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5984 Entity.getMethodDecl())
5985 S.Diag(Entity.getMethodDecl()->getLocation(),
5986 diag::note_method_return_type_change)
5987 << Entity.getMethodDecl()->getDeclName();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005988}
5989
Jordan Rose6c0505e2013-05-06 16:48:12 +00005990/// Returns true if the parameters describe a constructor initialization of
5991/// an explicit temporary object, e.g. "Point(x, y)".
5992static bool isExplicitTemporary(const InitializedEntity &Entity,
5993 const InitializationKind &Kind,
5994 unsigned NumArgs) {
5995 switch (Entity.getKind()) {
5996 case InitializedEntity::EK_Temporary:
5997 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005998 case InitializedEntity::EK_RelatedResult:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005999 break;
6000 default:
6001 return false;
6002 }
6003
6004 switch (Kind.getKind()) {
6005 case InitializationKind::IK_DirectList:
6006 return true;
6007 // FIXME: Hack to work around cast weirdness.
6008 case InitializationKind::IK_Direct:
6009 case InitializationKind::IK_Value:
6010 return NumArgs != 1;
6011 default:
6012 return false;
6013 }
6014}
6015
Sebastian Redled2e5322011-12-22 14:44:04 +00006016static ExprResult
6017PerformConstructorInitialization(Sema &S,
6018 const InitializedEntity &Entity,
6019 const InitializationKind &Kind,
6020 MultiExprArg Args,
6021 const InitializationSequence::Step& Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006022 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006023 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006024 bool IsStdInitListInitialization,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006025 SourceLocation LBraceLoc,
6026 SourceLocation RBraceLoc) {
Sebastian Redled2e5322011-12-22 14:44:04 +00006027 unsigned NumArgs = Args.size();
6028 CXXConstructorDecl *Constructor
6029 = cast<CXXConstructorDecl>(Step.Function.Function);
6030 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
6031
6032 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00006033 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redled2e5322011-12-22 14:44:04 +00006034 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
6035 ? Kind.getEqualLoc()
6036 : Kind.getLocation();
6037
6038 if (Kind.getKind() == InitializationKind::IK_Default) {
6039 // Force even a trivial, implicit default constructor to be
6040 // semantically checked. We do this explicitly because we don't build
6041 // the definition for completely trivial constructors.
Matt Beaumont-Gay47ff1222012-02-24 08:37:56 +00006042 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redled2e5322011-12-22 14:44:04 +00006043 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregorf704ade2012-02-24 07:48:37 +00006044 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redled2e5322011-12-22 14:44:04 +00006045 S.DefineImplicitDefaultConstructor(Loc, Constructor);
6046 }
6047
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006048 ExprResult CurInit((Expr *)nullptr);
Sebastian Redled2e5322011-12-22 14:44:04 +00006049
Douglas Gregor6073dca2012-02-24 23:56:31 +00006050 // C++ [over.match.copy]p1:
6051 // - When initializing a temporary to be bound to the first parameter
6052 // of a constructor that takes a reference to possibly cv-qualified
6053 // T as its first argument, called with a single argument in the
6054 // context of direct-initialization, explicit conversion functions
6055 // are also considered.
Richard Smith7c2bcc92016-09-07 02:14:33 +00006056 bool AllowExplicitConv =
6057 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
6058 hasCopyOrMoveCtorParam(S.Context,
6059 getConstructorInfo(Step.Function.FoundDecl));
Douglas Gregor6073dca2012-02-24 23:56:31 +00006060
Sebastian Redled2e5322011-12-22 14:44:04 +00006061 // Determine the arguments required to actually perform the constructor
6062 // call.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006063 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregor6073dca2012-02-24 23:56:31 +00006064 Loc, ConstructorArgs,
Richard Smith6b216962013-02-05 05:52:24 +00006065 AllowExplicitConv,
6066 IsListInitialization))
Sebastian Redled2e5322011-12-22 14:44:04 +00006067 return ExprError();
6068
6069
Jordan Rose6c0505e2013-05-06 16:48:12 +00006070 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redled2e5322011-12-22 14:44:04 +00006071 // An explicitly-constructed temporary, e.g., X(1, 2).
Richard Smith22262ab2013-05-04 06:44:46 +00006072 if (S.DiagnoseUseOfDecl(Constructor, Loc))
6073 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00006074
6075 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6076 if (!TSInfo)
6077 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Vedant Kumara14a1f92018-01-17 18:53:51 +00006078 SourceRange ParenOrBraceRange = Kind.getParenOrBraceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006079
Richard Smith5179eb72016-06-28 19:03:57 +00006080 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
Richard Smith80a47022016-06-29 01:10:27 +00006081 Step.Function.FoundDecl.getDecl())) {
Richard Smith5179eb72016-06-28 19:03:57 +00006082 Constructor = S.findInheritingConstructor(Loc, Constructor, Shadow);
Richard Smith80a47022016-06-29 01:10:27 +00006083 if (S.DiagnoseUseOfDecl(Constructor, Loc))
6084 return ExprError();
6085 }
Richard Smith5179eb72016-06-28 19:03:57 +00006086 S.MarkFunctionReferenced(Loc, Constructor);
6087
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006088 CurInit = new (S.Context) CXXTemporaryObjectExpr(
Richard Smith60437622017-02-09 19:17:44 +00006089 S.Context, Constructor,
6090 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
Richard Smithc2bebe92016-05-11 20:37:46 +00006091 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
6092 IsListInitialization, IsStdInitListInitialization,
6093 ConstructorInitRequiresZeroInit);
Sebastian Redled2e5322011-12-22 14:44:04 +00006094 } else {
6095 CXXConstructExpr::ConstructionKind ConstructKind =
6096 CXXConstructExpr::CK_Complete;
6097
6098 if (Entity.getKind() == InitializedEntity::EK_Base) {
6099 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
6100 CXXConstructExpr::CK_VirtualBase :
6101 CXXConstructExpr::CK_NonVirtualBase;
6102 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
6103 ConstructKind = CXXConstructExpr::CK_Delegating;
6104 }
6105
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006106 // Only get the parenthesis or brace range if it is a list initialization or
6107 // direct construction.
6108 SourceRange ParenOrBraceRange;
6109 if (IsListInitialization)
6110 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
6111 else if (Kind.getKind() == InitializationKind::IK_Direct)
Vedant Kumara14a1f92018-01-17 18:53:51 +00006112 ParenOrBraceRange = Kind.getParenOrBraceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006113
6114 // If the entity allows NRVO, mark the construction as elidable
6115 // unconditionally.
6116 if (Entity.allowsNRVO())
Richard Smith410306b2016-12-12 02:53:20 +00006117 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
Richard Smithc2bebe92016-05-11 20:37:46 +00006118 Step.Function.FoundDecl,
Sebastian Redled2e5322011-12-22 14:44:04 +00006119 Constructor, /*Elidable=*/true,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006120 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00006121 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006122 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006123 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00006124 ConstructorInitRequiresZeroInit,
6125 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006126 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00006127 else
Richard Smith410306b2016-12-12 02:53:20 +00006128 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
Richard Smithc2bebe92016-05-11 20:37:46 +00006129 Step.Function.FoundDecl,
Sebastian Redled2e5322011-12-22 14:44:04 +00006130 Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006131 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00006132 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006133 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006134 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00006135 ConstructorInitRequiresZeroInit,
6136 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006137 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00006138 }
6139 if (CurInit.isInvalid())
6140 return ExprError();
6141
6142 // Only check access if all of that succeeded.
Richard Smith5179eb72016-06-28 19:03:57 +00006143 S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
Richard Smith22262ab2013-05-04 06:44:46 +00006144 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
6145 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00006146
6147 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006148 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redled2e5322011-12-22 14:44:04 +00006149
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006150 return CurInit;
Sebastian Redled2e5322011-12-22 14:44:04 +00006151}
6152
Richard Smitheb3cad52012-06-04 22:27:30 +00006153/// Determine whether the specified InitializedEntity definitely has a lifetime
6154/// longer than the current full-expression. Conservatively returns false if
6155/// it's unclear.
6156static bool
6157InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
6158 const InitializedEntity *Top = &Entity;
6159 while (Top->getParent())
6160 Top = Top->getParent();
6161
6162 switch (Top->getKind()) {
6163 case InitializedEntity::EK_Variable:
6164 case InitializedEntity::EK_Result:
6165 case InitializedEntity::EK_Exception:
6166 case InitializedEntity::EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00006167 case InitializedEntity::EK_Binding:
Richard Smitheb3cad52012-06-04 22:27:30 +00006168 case InitializedEntity::EK_New:
6169 case InitializedEntity::EK_Base:
6170 case InitializedEntity::EK_Delegating:
6171 return true;
6172
6173 case InitializedEntity::EK_ArrayElement:
6174 case InitializedEntity::EK_VectorElement:
6175 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00006176 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Richard Smitheb3cad52012-06-04 22:27:30 +00006177 case InitializedEntity::EK_ComplexElement:
6178 // Could not determine what the full initialization is. Assume it might not
6179 // outlive the full-expression.
6180 return false;
6181
6182 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006183 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smitheb3cad52012-06-04 22:27:30 +00006184 case InitializedEntity::EK_Temporary:
6185 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00006186 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00006187 case InitializedEntity::EK_RelatedResult:
Richard Smitheb3cad52012-06-04 22:27:30 +00006188 // The entity being initialized might not outlive the full-expression.
6189 return false;
6190 }
6191
6192 llvm_unreachable("unknown entity kind");
6193}
6194
Richard Smithe6c01442013-06-05 00:46:14 +00006195/// Determine the declaration which an initialized entity ultimately refers to,
6196/// for the purpose of lifetime-extending a temporary bound to a reference in
6197/// the initialization of \p Entity.
David Majnemerdaff3702014-05-01 17:50:17 +00006198static const InitializedEntity *getEntityForTemporaryLifetimeExtension(
6199 const InitializedEntity *Entity,
Craig Topperc3ec1492014-05-26 06:22:03 +00006200 const InitializedEntity *FallbackDecl = nullptr) {
Richard Smithe6c01442013-06-05 00:46:14 +00006201 // C++11 [class.temporary]p5:
David Majnemerdaff3702014-05-01 17:50:17 +00006202 switch (Entity->getKind()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006203 case InitializedEntity::EK_Variable:
6204 // The temporary [...] persists for the lifetime of the reference
David Majnemerdaff3702014-05-01 17:50:17 +00006205 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00006206
6207 case InitializedEntity::EK_Member:
6208 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00006209 if (Entity->getParent())
6210 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
6211 Entity);
Richard Smithe6c01442013-06-05 00:46:14 +00006212
6213 // except:
6214 // -- A temporary bound to a reference member in a constructor's
6215 // ctor-initializer persists until the constructor exits.
David Majnemerdaff3702014-05-01 17:50:17 +00006216 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00006217
Richard Smith7873de02016-08-11 22:25:46 +00006218 case InitializedEntity::EK_Binding:
Richard Smith3997b1b2016-08-12 01:55:21 +00006219 // Per [dcl.decomp]p3, the binding is treated as a variable of reference
6220 // type.
6221 return Entity;
Richard Smith7873de02016-08-11 22:25:46 +00006222
Richard Smithe6c01442013-06-05 00:46:14 +00006223 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006224 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithe6c01442013-06-05 00:46:14 +00006225 // -- A temporary bound to a reference parameter in a function call
6226 // persists until the completion of the full-expression containing
6227 // the call.
6228 case InitializedEntity::EK_Result:
6229 // -- The lifetime of a temporary bound to the returned value in a
6230 // function return statement is not extended; the temporary is
6231 // destroyed at the end of the full-expression in the return statement.
6232 case InitializedEntity::EK_New:
6233 // -- A temporary bound to a reference in a new-initializer persists
6234 // until the completion of the full-expression containing the
6235 // new-initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00006236 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00006237
6238 case InitializedEntity::EK_Temporary:
6239 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00006240 case InitializedEntity::EK_RelatedResult:
Richard Smithe6c01442013-06-05 00:46:14 +00006241 // We don't yet know the storage duration of the surrounding temporary.
6242 // Assume it's got full-expression duration for now, it will patch up our
6243 // storage duration if that's not correct.
David Majnemerdaff3702014-05-01 17:50:17 +00006244 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00006245
6246 case InitializedEntity::EK_ArrayElement:
6247 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00006248 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
6249 FallbackDecl);
Richard Smithe6c01442013-06-05 00:46:14 +00006250
6251 case InitializedEntity::EK_Base:
Richard Smith872307e2016-03-08 22:17:41 +00006252 // For subobjects, we look at the complete object.
6253 if (Entity->getParent())
6254 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
6255 Entity);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006256 LLVM_FALLTHROUGH;
Richard Smithe6c01442013-06-05 00:46:14 +00006257 case InitializedEntity::EK_Delegating:
6258 // We can reach this case for aggregate initialization in a constructor:
6259 // struct A { int &&r; };
6260 // struct B : A { B() : A{0} {} };
6261 // In this case, use the innermost field decl as the context.
6262 return FallbackDecl;
6263
6264 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00006265 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Richard Smithe6c01442013-06-05 00:46:14 +00006266 case InitializedEntity::EK_LambdaCapture:
6267 case InitializedEntity::EK_Exception:
6268 case InitializedEntity::EK_VectorElement:
6269 case InitializedEntity::EK_ComplexElement:
David Majnemerdaff3702014-05-01 17:50:17 +00006270 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00006271 }
Benjamin Kramercabc8822013-06-05 15:37:50 +00006272 llvm_unreachable("unknown entity kind");
Richard Smithe6c01442013-06-05 00:46:14 +00006273}
6274
David Majnemerdaff3702014-05-01 17:50:17 +00006275static void performLifetimeExtension(Expr *Init,
6276 const InitializedEntity *ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00006277
6278/// Update a glvalue expression that is used as the initializer of a reference
6279/// to note that its lifetime is extended.
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006280/// \return \c true if any temporary had its lifetime extended.
David Majnemerdaff3702014-05-01 17:50:17 +00006281static bool
6282performReferenceExtension(Expr *Init,
6283 const InitializedEntity *ExtendingEntity) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006284 // Walk past any constructs which we can lifetime-extend across.
6285 Expr *Old;
6286 do {
6287 Old = Init;
6288
Richard Smithdbc82492015-01-10 01:28:13 +00006289 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
6290 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
6291 // This is just redundant braces around an initializer. Step over it.
6292 Init = ILE->getInit(0);
6293 }
6294 }
6295
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006296 // Step over any subobject adjustments; we may have a materialized
6297 // temporary inside them.
Richard Smith4baaa5a2016-12-03 01:14:32 +00006298 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006299
6300 // Per current approach for DR1376, look through casts to reference type
6301 // when performing lifetime extension.
6302 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
6303 if (CE->getSubExpr()->isGLValue())
6304 Init = CE->getSubExpr();
6305
Richard Smithb3189a12016-12-05 07:49:14 +00006306 // Per the current approach for DR1299, look through array element access
6307 // when performing lifetime extension.
6308 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init))
6309 Init = ASE->getBase();
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006310 } while (Init != Old);
6311
Richard Smithe6c01442013-06-05 00:46:14 +00006312 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
6313 // Update the storage duration of the materialized temporary.
6314 // FIXME: Rebuild the expression instead of mutating it.
David Majnemerdaff3702014-05-01 17:50:17 +00006315 ME->setExtendingDecl(ExtendingEntity->getDecl(),
6316 ExtendingEntity->allocateManglingNumber());
6317 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006318 return true;
Richard Smithe6c01442013-06-05 00:46:14 +00006319 }
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006320
6321 return false;
Richard Smithe6c01442013-06-05 00:46:14 +00006322}
6323
6324/// Update a prvalue expression that is going to be materialized as a
6325/// lifetime-extended temporary.
David Majnemerdaff3702014-05-01 17:50:17 +00006326static void performLifetimeExtension(Expr *Init,
6327 const InitializedEntity *ExtendingEntity) {
Richard Smithe6c01442013-06-05 00:46:14 +00006328 // Dig out the expression which constructs the extended temporary.
Richard Smith4baaa5a2016-12-03 01:14:32 +00006329 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
Richard Smithe6c01442013-06-05 00:46:14 +00006330
Richard Smith736a9472013-06-12 20:42:33 +00006331 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
6332 Init = BTE->getSubExpr();
6333
Richard Smithcc1b96d2013-06-12 22:31:48 +00006334 if (CXXStdInitializerListExpr *ILE =
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006335 dyn_cast<CXXStdInitializerListExpr>(Init)) {
David Majnemerdaff3702014-05-01 17:50:17 +00006336 performReferenceExtension(ILE->getSubExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006337 return;
6338 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00006339
Richard Smithe6c01442013-06-05 00:46:14 +00006340 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00006341 if (ILE->getType()->isArrayType()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006342 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
David Majnemerdaff3702014-05-01 17:50:17 +00006343 performLifetimeExtension(ILE->getInit(I), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00006344 return;
6345 }
6346
Richard Smithcc1b96d2013-06-12 22:31:48 +00006347 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006348 assert(RD->isAggregate() && "aggregate init on non-aggregate");
6349
6350 // If we lifetime-extend a braced initializer which is initializing an
6351 // aggregate, and that aggregate contains reference members which are
6352 // bound to temporaries, those temporaries are also lifetime-extended.
6353 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
6354 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00006355 performReferenceExtension(ILE->getInit(0), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00006356 else {
6357 unsigned Index = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006358 for (const auto *I : RD->fields()) {
Richard Smith0bca59d2013-07-01 06:08:20 +00006359 if (Index >= ILE->getNumInits())
6360 break;
Richard Smithe6c01442013-06-05 00:46:14 +00006361 if (I->isUnnamedBitfield())
6362 continue;
Richard Smith8d7f11d2013-06-27 22:54:33 +00006363 Expr *SubInit = ILE->getInit(Index);
Richard Smithe6c01442013-06-05 00:46:14 +00006364 if (I->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00006365 performReferenceExtension(SubInit, ExtendingEntity);
Richard Smith8d7f11d2013-06-27 22:54:33 +00006366 else if (isa<InitListExpr>(SubInit) ||
6367 isa<CXXStdInitializerListExpr>(SubInit))
Richard Smithe6c01442013-06-05 00:46:14 +00006368 // This may be either aggregate-initialization of a member or
6369 // initialization of a std::initializer_list object. Either way,
6370 // we should recursively lifetime-extend that initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00006371 performLifetimeExtension(SubInit, ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00006372 ++Index;
6373 }
6374 }
6375 }
6376 }
6377}
6378
Richard Smithcc1b96d2013-06-12 22:31:48 +00006379static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
6380 const Expr *Init, bool IsInitializerList,
6381 const ValueDecl *ExtendingDecl) {
6382 // Warn if a field lifetime-extends a temporary.
6383 if (isa<FieldDecl>(ExtendingDecl)) {
6384 if (IsInitializerList) {
6385 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
6386 << /*at end of constructor*/true;
6387 return;
6388 }
6389
6390 bool IsSubobjectMember = false;
6391 for (const InitializedEntity *Ent = Entity.getParent(); Ent;
6392 Ent = Ent->getParent()) {
6393 if (Ent->getKind() != InitializedEntity::EK_Base) {
6394 IsSubobjectMember = true;
6395 break;
6396 }
6397 }
6398 S.Diag(Init->getExprLoc(),
6399 diag::warn_bind_ref_member_to_temporary)
6400 << ExtendingDecl << Init->getSourceRange()
6401 << IsSubobjectMember << IsInitializerList;
6402 if (IsSubobjectMember)
6403 S.Diag(ExtendingDecl->getLocation(),
6404 diag::note_ref_subobject_of_member_declared_here);
6405 else
6406 S.Diag(ExtendingDecl->getLocation(),
6407 diag::note_ref_or_ptr_member_declared_here)
6408 << /*is pointer*/false;
6409 }
6410}
6411
Richard Smithaaa0ec42013-09-21 21:19:19 +00006412static void DiagnoseNarrowingInInitList(Sema &S,
6413 const ImplicitConversionSequence &ICS,
6414 QualType PreNarrowingType,
6415 QualType EntityType,
6416 const Expr *PostInit);
6417
Richard Trieuac3eca52015-04-29 01:52:17 +00006418/// Provide warnings when std::move is used on construction.
6419static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
6420 bool IsReturnStmt) {
6421 if (!InitExpr)
6422 return;
6423
Richard Smith51ec0cf2017-02-21 01:17:38 +00006424 if (S.inTemplateInstantiation())
Richard Trieu6093d142015-07-29 17:03:34 +00006425 return;
6426
Richard Trieuac3eca52015-04-29 01:52:17 +00006427 QualType DestType = InitExpr->getType();
6428 if (!DestType->isRecordType())
6429 return;
6430
6431 unsigned DiagID = 0;
6432 if (IsReturnStmt) {
6433 const CXXConstructExpr *CCE =
6434 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
6435 if (!CCE || CCE->getNumArgs() != 1)
6436 return;
6437
6438 if (!CCE->getConstructor()->isCopyOrMoveConstructor())
6439 return;
6440
6441 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
Richard Trieuac3eca52015-04-29 01:52:17 +00006442 }
6443
6444 // Find the std::move call and get the argument.
6445 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
6446 if (!CE || CE->getNumArgs() != 1)
6447 return;
6448
6449 const FunctionDecl *MoveFunction = CE->getDirectCallee();
6450 if (!MoveFunction || !MoveFunction->isInStdNamespace() ||
6451 !MoveFunction->getIdentifier() ||
6452 !MoveFunction->getIdentifier()->isStr("move"))
6453 return;
6454
6455 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
6456
6457 if (IsReturnStmt) {
6458 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
6459 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
6460 return;
6461
6462 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
6463 if (!VD || !VD->hasLocalStorage())
6464 return;
6465
Alex Lorenzbbe51d82017-11-07 21:40:11 +00006466 // __block variables are not moved implicitly.
6467 if (VD->hasAttr<BlocksAttr>())
6468 return;
6469
Richard Trieu8d4006a2015-07-28 19:06:16 +00006470 QualType SourceType = VD->getType();
6471 if (!SourceType->isRecordType())
Richard Trieu1d4911bc2015-05-18 19:54:08 +00006472 return;
6473
Richard Trieu8d4006a2015-07-28 19:06:16 +00006474 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
Richard Trieu1993dc82015-07-29 23:47:19 +00006475 return;
Richard Trieu8d4006a2015-07-28 19:06:16 +00006476 }
6477
Davide Italiano7842c3f2015-07-18 01:15:19 +00006478 // If we're returning a function parameter, copy elision
6479 // is not possible.
6480 if (isa<ParmVarDecl>(VD))
6481 DiagID = diag::warn_redundant_move_on_return;
Richard Trieu1993dc82015-07-29 23:47:19 +00006482 else
6483 DiagID = diag::warn_pessimizing_move_on_return;
Richard Trieuac3eca52015-04-29 01:52:17 +00006484 } else {
6485 DiagID = diag::warn_pessimizing_move_on_initialization;
6486 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
6487 if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType())
6488 return;
6489 }
6490
6491 S.Diag(CE->getLocStart(), DiagID);
6492
6493 // Get all the locations for a fix-it. Don't emit the fix-it if any location
6494 // is within a macro.
6495 SourceLocation CallBegin = CE->getCallee()->getLocStart();
6496 if (CallBegin.isMacroID())
6497 return;
6498 SourceLocation RParen = CE->getRParenLoc();
6499 if (RParen.isMacroID())
6500 return;
6501 SourceLocation LParen;
6502 SourceLocation ArgLoc = Arg->getLocStart();
6503
6504 // Special testing for the argument location. Since the fix-it needs the
6505 // location right before the argument, the argument location can be in a
6506 // macro only if it is at the beginning of the macro.
6507 while (ArgLoc.isMacroID() &&
6508 S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
Richard Smithb5f81712018-04-30 05:25:48 +00006509 ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).getBegin();
Richard Trieuac3eca52015-04-29 01:52:17 +00006510 }
6511
6512 if (LParen.isMacroID())
6513 return;
6514
6515 LParen = ArgLoc.getLocWithOffset(-1);
6516
6517 S.Diag(CE->getLocStart(), diag::note_remove_move)
6518 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
6519 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
6520}
6521
Nick Lewycky2eeddfb2016-05-14 17:44:14 +00006522static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
6523 // Check to see if we are dereferencing a null pointer. If so, this is
6524 // undefined behavior, so warn about it. This only handles the pattern
6525 // "*null", which is a very syntactic check.
6526 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
6527 if (UO->getOpcode() == UO_Deref &&
6528 UO->getSubExpr()->IgnoreParenCasts()->
6529 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
6530 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
6531 S.PDiag(diag::warn_binding_null_to_reference)
6532 << UO->getSubExpr()->getSourceRange());
6533 }
6534}
6535
Tim Shen4a05bb82016-06-21 20:29:17 +00006536MaterializeTemporaryExpr *
6537Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
6538 bool BoundToLvalueReference) {
6539 auto MTE = new (Context)
6540 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
6541
6542 // Order an ExprWithCleanups for lifetime marks.
6543 //
6544 // TODO: It'll be good to have a single place to check the access of the
6545 // destructor and generate ExprWithCleanups for various uses. Currently these
6546 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
6547 // but there may be a chance to merge them.
6548 Cleanup.setExprNeedsCleanups(false);
6549 return MTE;
6550}
6551
Richard Smith4baaa5a2016-12-03 01:14:32 +00006552ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {
6553 // In C++98, we don't want to implicitly create an xvalue.
6554 // FIXME: This means that AST consumers need to deal with "prvalues" that
6555 // denote materialized temporaries. Maybe we should add another ValueKind
6556 // for "xvalue pretending to be a prvalue" for C++98 support.
6557 if (!E->isRValue() || !getLangOpts().CPlusPlus11)
6558 return E;
6559
6560 // C++1z [conv.rval]/1: T shall be a complete type.
Richard Smith81f5ade2016-12-15 02:28:18 +00006561 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
6562 // If so, we should check for a non-abstract class type here too.
Richard Smith4baaa5a2016-12-03 01:14:32 +00006563 QualType T = E->getType();
6564 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
6565 return ExprError();
6566
6567 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
6568}
6569
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006570ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006571InitializationSequence::Perform(Sema &S,
6572 const InitializedEntity &Entity,
6573 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00006574 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00006575 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00006576 if (Failed()) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006577 Diagnose(S, Entity, Kind, Args);
John McCallfaf5fb42010-08-26 23:41:50 +00006578 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006579 }
Nico Weber337d5aa2015-04-17 08:32:38 +00006580 if (!ZeroInitializationFixit.empty()) {
6581 unsigned DiagID = diag::err_default_init_const;
6582 if (Decl *D = Entity.getDecl())
6583 if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>())
6584 DiagID = diag::ext_default_init_const;
6585
6586 // The initialization would have succeeded with this fixit. Since the fixit
6587 // is on the error, we need to build a valid AST in this case, so this isn't
6588 // handled in the Failed() branch above.
6589 QualType DestType = Entity.getType();
6590 S.Diag(Kind.getLocation(), DiagID)
6591 << DestType << (bool)DestType->getAs<RecordType>()
6592 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
6593 ZeroInitializationFixit);
6594 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006595
Sebastian Redld201edf2011-06-05 13:59:11 +00006596 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00006597 // If the declaration is a non-dependent, incomplete array type
6598 // that has an initializer, then its type will be completed once
6599 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00006600 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00006601 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00006602 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00006603 if (const IncompleteArrayType *ArrayT
6604 = S.Context.getAsIncompleteArrayType(DeclType)) {
6605 // FIXME: We don't currently have the ability to accurately
6606 // compute the length of an initializer list without
6607 // performing full type-checking of the initializer list
6608 // (since we have to determine where braces are implicitly
6609 // introduced and such). So, we fall back to making the array
6610 // type a dependently-sized array type with no specified
6611 // bound.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006612 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00006613 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00006614
Douglas Gregor51e77d52009-12-10 17:56:55 +00006615 // Scavange the location of the brackets from the entity, if we can.
Richard Smith7873de02016-08-11 22:25:46 +00006616 if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
Douglas Gregor1b303932009-12-22 15:35:07 +00006617 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
6618 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00006619 if (IncompleteArrayTypeLoc ArrayLoc =
6620 TL.getAs<IncompleteArrayTypeLoc>())
6621 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregor1b303932009-12-22 15:35:07 +00006622 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00006623 }
6624
6625 *ResultType
6626 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006627 /*NumElts=*/nullptr,
Douglas Gregor51e77d52009-12-10 17:56:55 +00006628 ArrayT->getSizeModifier(),
6629 ArrayT->getIndexTypeCVRQualifiers(),
6630 Brackets);
6631 }
6632
6633 }
6634 }
Sebastian Redla9351792012-02-11 23:51:47 +00006635 if (Kind.getKind() == InitializationKind::IK_Direct &&
6636 !Kind.isExplicitCast()) {
6637 // Rebuild the ParenListExpr.
Vedant Kumara14a1f92018-01-17 18:53:51 +00006638 SourceRange ParenRange = Kind.getParenOrBraceRange();
Sebastian Redla9351792012-02-11 23:51:47 +00006639 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006640 Args);
Sebastian Redla9351792012-02-11 23:51:47 +00006641 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00006642 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregorbf138952012-04-04 04:06:51 +00006643 Kind.isExplicitCast() ||
6644 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006645 return ExprResult(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006646 }
6647
Sebastian Redld201edf2011-06-05 13:59:11 +00006648 // No steps means no initialization.
6649 if (Steps.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006650 return ExprResult((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006651
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006652 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006653 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006654 !Entity.isParameterKind()) {
Richard Smith2b349ae2012-04-19 06:58:00 +00006655 // Produce a C++98 compatibility warning if we are initializing a reference
6656 // from an initializer list. For parameters, we produce a better warning
6657 // elsewhere.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006658 Expr *Init = Args[0];
Richard Smith2b349ae2012-04-19 06:58:00 +00006659 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
6660 << Init->getSourceRange();
6661 }
6662
Egor Churaev3bccec52017-04-05 12:47:10 +00006663 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
6664 QualType ETy = Entity.getType();
6665 Qualifiers TyQualifiers = ETy.getQualifiers();
6666 bool HasGlobalAS = TyQualifiers.hasAddressSpace() &&
6667 TyQualifiers.getAddressSpace() == LangAS::opencl_global;
6668
6669 if (S.getLangOpts().OpenCLVersion >= 200 &&
6670 ETy->isAtomicType() && !HasGlobalAS &&
6671 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
6672 S.Diag(Args[0]->getLocStart(), diag::err_opencl_atomic_init) << 1 <<
6673 SourceRange(Entity.getDecl()->getLocStart(), Args[0]->getLocEnd());
6674 return ExprError();
6675 }
6676
Richard Smitheb3cad52012-06-04 22:27:30 +00006677 // Diagnose cases where we initialize a pointer to an array temporary, and the
6678 // pointer obviously outlives the temporary.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006679 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smitheb3cad52012-06-04 22:27:30 +00006680 Entity.getType()->isPointerType() &&
6681 InitializedEntityOutlivesFullExpression(Entity)) {
Richard Smith4baaa5a2016-12-03 01:14:32 +00006682 const Expr *Init = Args[0]->skipRValueSubobjectAdjustments();
6683 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
6684 Init = MTE->GetTemporaryExpr();
Richard Smitheb3cad52012-06-04 22:27:30 +00006685 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
6686 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
6687 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
6688 << Init->getSourceRange();
6689 }
6690
Douglas Gregor1b303932009-12-22 15:35:07 +00006691 QualType DestType = Entity.getType().getNonReferenceType();
6692 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00006693 // the same as Entity.getDecl()->getType() in cases involving type merging,
6694 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00006695 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00006696 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00006697 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006698
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006699 ExprResult CurInit((Expr *)nullptr);
Richard Smith410306b2016-12-12 02:53:20 +00006700 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006701
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006702 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00006703 // grab the only argument out the Args and place it into the "current"
6704 // initializer.
6705 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00006706 case SK_ResolveAddressOfOverloadedFunction:
6707 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006708 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00006709 case SK_CastDerivedToBaseLValue:
6710 case SK_BindReference:
6711 case SK_BindReferenceToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00006712 case SK_FinalCopy:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006713 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00006714 case SK_UserConversion:
6715 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006716 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00006717 case SK_QualificationConversionRValue:
Richard Smith77be48a2014-07-31 06:31:19 +00006718 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00006719 case SK_LValueToRValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00006720 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00006721 case SK_ConversionSequenceNoNarrowing:
Douglas Gregore1314a62009-12-18 05:02:21 +00006722 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00006723 case SK_UnwrapInitList:
6724 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00006725 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00006726 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00006727 case SK_ObjCObjectConversion:
Richard Smith410306b2016-12-12 02:53:20 +00006728 case SK_ArrayLoopIndex:
6729 case SK_ArrayLoopInit:
John McCall31168b02011-06-15 23:02:42 +00006730 case SK_ArrayInit:
Richard Smith378b8c82016-12-14 03:22:16 +00006731 case SK_GNUArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00006732 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00006733 case SK_PassByIndirectCopyRestore:
6734 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00006735 case SK_ProduceObjCObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006736 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00006737 case SK_OCLSamplerInit:
Egor Churaev89831422016-12-23 14:55:49 +00006738 case SK_OCLZeroEvent:
6739 case SK_OCLZeroQueue: {
Douglas Gregore1314a62009-12-18 05:02:21 +00006740 assert(Args.size() == 1);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006741 CurInit = Args[0];
John Wiegley01296292011-04-08 18:41:53 +00006742 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00006743 break;
John McCall34376a62010-12-04 03:47:34 +00006744 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006745
Douglas Gregore1314a62009-12-18 05:02:21 +00006746 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00006747 case SK_ConstructorInitializationFromList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00006748 case SK_StdInitializerListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00006749 case SK_ZeroInitialization:
6750 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006751 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006752
Richard Smithd6a15082017-01-07 00:48:55 +00006753 // Promote from an unevaluated context to an unevaluated list context in
6754 // C++11 list-initialization; we need to instantiate entities usable in
6755 // constant expressions here in order to perform narrowing checks =(
6756 EnterExpressionEvaluationContext Evaluated(
6757 S, EnterExpressionEvaluationContext::InitList,
6758 CurInit.get() && isa<InitListExpr>(CurInit.get()));
6759
Richard Smith81f5ade2016-12-15 02:28:18 +00006760 // C++ [class.abstract]p2:
6761 // no objects of an abstract class can be created except as subobjects
6762 // of a class derived from it
6763 auto checkAbstractType = [&](QualType T) -> bool {
6764 if (Entity.getKind() == InitializedEntity::EK_Base ||
6765 Entity.getKind() == InitializedEntity::EK_Delegating)
6766 return false;
6767 return S.RequireNonAbstractType(Kind.getLocation(), T,
6768 diag::err_allocation_of_abstract_type);
6769 };
6770
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006771 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006772 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006773 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006774 for (step_iterator Step = step_begin(), StepEnd = step_end();
6775 Step != StepEnd; ++Step) {
6776 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006777 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006778
John Wiegley01296292011-04-08 18:41:53 +00006779 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006780
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006781 switch (Step->Kind) {
6782 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006783 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006784 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00006785 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +00006786 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
6787 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006788 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall16df1e52010-03-30 21:47:33 +00006789 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00006790 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006791 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006792
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006793 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006794 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006795 case SK_CastDerivedToBaseLValue: {
6796 // We have a derived-to-base cast that produces either an rvalue or an
6797 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006798
John McCallcf142162010-08-07 06:22:56 +00006799 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00006800
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006801 // Casts to inaccessible base classes are allowed with C-style casts.
6802 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
6803 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00006804 CurInit.get()->getLocStart(),
6805 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00006806 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00006807 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006808
John McCall2536c6d2010-08-25 10:28:54 +00006809 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006810 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006811 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006812 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006813 VK_XValue :
6814 VK_RValue);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006815 CurInit =
6816 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
6817 CurInit.get(), &BasePath, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006818 break;
6819 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006820
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006821 case SK_BindReference:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006822 // Reference binding does not have any corresponding ASTs.
6823
6824 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00006825 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00006826 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00006827
George Burgess IVcfd48d92017-04-13 23:47:08 +00006828 // We don't check for e.g. function pointers here, since address
6829 // availability checks should only occur when the function first decays
6830 // into a pointer or reference.
6831 if (CurInit.get()->getType()->isFunctionProtoType()) {
6832 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
6833 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
6834 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
6835 DRE->getLocStart()))
6836 return ExprError();
6837 }
6838 }
6839 }
6840
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006841 // Even though we didn't materialize a temporary, the binding may still
6842 // extend the lifetime of a temporary. This happens if we bind a reference
6843 // to the result of a cast to reference type.
David Majnemerdaff3702014-05-01 17:50:17 +00006844 if (const InitializedEntity *ExtendingEntity =
6845 getEntityForTemporaryLifetimeExtension(&Entity))
6846 if (performReferenceExtension(CurInit.get(), ExtendingEntity))
6847 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6848 /*IsInitializerList=*/false,
6849 ExtendingEntity->getDecl());
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006850
Nick Lewycky2eeddfb2016-05-14 17:44:14 +00006851 CheckForNullPointerDereference(S, CurInit.get());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006852 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00006853
Richard Smithe6c01442013-06-05 00:46:14 +00006854 case SK_BindReferenceToTemporary: {
Jordan Roseb1312a52013-04-11 00:58:58 +00006855 // Make sure the "temporary" is actually an rvalue.
6856 assert(CurInit.get()->isRValue() && "not a temporary");
6857
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006858 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00006859 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00006860 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006861
Douglas Gregorfe314812011-06-21 17:03:29 +00006862 // Materialize the temporary into memory.
Tim Shen4a05bb82016-06-21 20:29:17 +00006863 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
Richard Smithb8c0f552016-12-09 18:49:13 +00006864 Step->Type, CurInit.get(), Entity.getType()->isLValueReferenceType());
David Majnemerdaff3702014-05-01 17:50:17 +00006865
6866 // Maybe lifetime-extend the temporary's subobjects to match the
6867 // entity's lifetime.
6868 if (const InitializedEntity *ExtendingEntity =
6869 getEntityForTemporaryLifetimeExtension(&Entity))
6870 if (performReferenceExtension(MTE, ExtendingEntity))
Richard Smithb8c0f552016-12-09 18:49:13 +00006871 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6872 /*IsInitializerList=*/false,
David Majnemerdaff3702014-05-01 17:50:17 +00006873 ExtendingEntity->getDecl());
Douglas Gregor58df5092011-06-22 16:12:01 +00006874
Brian Kelley762f9282017-03-29 18:16:38 +00006875 // If we're extending this temporary to automatic storage duration -- we
6876 // need to register its cleanup during the full-expression's cleanups.
6877 if (MTE->getStorageDuration() == SD_Automatic &&
6878 MTE->getType().isDestructedType())
Tim Shen4a05bb82016-06-21 20:29:17 +00006879 S.Cleanup.setExprNeedsCleanups(true);
Richard Smith736a9472013-06-12 20:42:33 +00006880
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006881 CurInit = MTE;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006882 break;
Richard Smithe6c01442013-06-05 00:46:14 +00006883 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006884
Richard Smithb8c0f552016-12-09 18:49:13 +00006885 case SK_FinalCopy:
Richard Smith81f5ade2016-12-15 02:28:18 +00006886 if (checkAbstractType(Step->Type))
6887 return ExprError();
6888
Richard Smithb8c0f552016-12-09 18:49:13 +00006889 // If the overall initialization is initializing a temporary, we already
6890 // bound our argument if it was necessary to do so. If not (if we're
6891 // ultimately initializing a non-temporary), our argument needs to be
6892 // bound since it's initializing a function parameter.
6893 // FIXME: This is a mess. Rationalize temporary destruction.
6894 if (!shouldBindAsTemporary(Entity))
6895 CurInit = S.MaybeBindToTemporary(CurInit.get());
6896 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
6897 /*IsExtraneousCopy=*/false);
6898 break;
6899
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006900 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006901 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006902 /*IsExtraneousCopy=*/true);
6903 break;
6904
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006905 case SK_UserConversion: {
6906 // We have a user-defined conversion that invokes either a constructor
6907 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00006908 CastKind CastKind;
John McCalla0296f72010-03-19 07:35:19 +00006909 FunctionDecl *Fn = Step->Function.Function;
6910 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006911 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00006912 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00006913 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006914 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00006915 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley01296292011-04-08 18:41:53 +00006916 SourceLocation Loc = CurInit.get()->getLocStart();
John McCall760af172010-02-01 03:16:54 +00006917
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006918 // Determine the arguments required to actually perform the constructor
6919 // call.
John Wiegley01296292011-04-08 18:41:53 +00006920 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006921 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00006922 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006923 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00006924 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006925
Richard Smithb24f0672012-02-11 19:22:50 +00006926 // Build an expression that constructs a temporary.
Richard Smithc2bebe92016-05-11 20:37:46 +00006927 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type,
6928 FoundFn, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006929 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006930 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006931 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006932 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00006933 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00006934 CXXConstructExpr::CK_Complete,
6935 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006936 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006937 return ExprError();
John McCall760af172010-02-01 03:16:54 +00006938
Richard Smith5179eb72016-06-28 19:03:57 +00006939 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
6940 Entity);
Richard Smith22262ab2013-05-04 06:44:46 +00006941 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6942 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006943
John McCalle3027922010-08-25 11:45:40 +00006944 CastKind = CK_ConstructorConversion;
Douglas Gregor95562572010-04-24 23:45:46 +00006945 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006946 } else {
6947 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00006948 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Craig Topperc3ec1492014-05-26 06:22:03 +00006949 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
John McCalla0296f72010-03-19 07:35:19 +00006950 FoundFn);
Richard Smith22262ab2013-05-04 06:44:46 +00006951 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6952 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006953
6954 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006955 // derived-to-base conversion? I believe the answer is "no", because
6956 // we don't want to turn off access control here for c-style casts.
Richard Smithb8c0f552016-12-09 18:49:13 +00006957 CurInit = S.PerformObjectArgumentInitialization(CurInit.get(),
6958 /*Qualifier=*/nullptr,
6959 FoundFn, Conversion);
6960 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006961 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006962
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006963 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006964 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
6965 HadMultipleCandidates);
Richard Smithb8c0f552016-12-09 18:49:13 +00006966 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006967 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006968
John McCalle3027922010-08-25 11:45:40 +00006969 CastKind = CK_UserDefinedConversion;
Alp Toker314cc812014-01-25 16:55:45 +00006970 CreatedObject = Conversion->getReturnType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006971 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006972
Richard Smith81f5ade2016-12-15 02:28:18 +00006973 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
6974 return ExprError();
6975
Richard Smithb8c0f552016-12-09 18:49:13 +00006976 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
6977 CastKind, CurInit.get(), nullptr,
6978 CurInit.get()->getValueKind());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00006979
Richard Smithb8c0f552016-12-09 18:49:13 +00006980 if (shouldBindAsTemporary(Entity))
6981 // The overall entity is temporary, so this expression should be
6982 // destroyed at the end of its full-expression.
6983 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
6984 else if (CreatedObject && shouldDestroyEntity(Entity)) {
6985 // The object outlasts the full-expression, but we need to prepare for
6986 // a destructor being run on it.
6987 // FIXME: It makes no sense to do this here. This should happen
6988 // regardless of how we initialized the entity.
John Wiegley01296292011-04-08 18:41:53 +00006989 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00006990 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006991 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00006992 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00006993 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00006994 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00006995 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith22262ab2013-05-04 06:44:46 +00006996 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
6997 return ExprError();
Douglas Gregor95562572010-04-24 23:45:46 +00006998 }
6999 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007000 break;
7001 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007002
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007003 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007004 case SK_QualificationConversionXValue:
7005 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007006 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00007007 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007008 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00007009 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007010 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00007011 VK_XValue :
7012 VK_RValue);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007013 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007014 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007015 }
7016
Richard Smith77be48a2014-07-31 06:31:19 +00007017 case SK_AtomicConversion: {
7018 assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
7019 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7020 CK_NonAtomicToAtomic, VK_RValue);
7021 break;
7022 }
7023
Jordan Roseb1312a52013-04-11 00:58:58 +00007024 case SK_LValueToRValue: {
7025 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007026 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
7027 CK_LValueToRValue, CurInit.get(),
7028 /*BasePath=*/nullptr, VK_RValue);
Jordan Roseb1312a52013-04-11 00:58:58 +00007029 break;
7030 }
7031
Richard Smithaaa0ec42013-09-21 21:19:19 +00007032 case SK_ConversionSequence:
7033 case SK_ConversionSequenceNoNarrowing: {
7034 Sema::CheckedConversionKind CCK
John McCall31168b02011-06-15 23:02:42 +00007035 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
7036 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00007037 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00007038 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00007039 ExprResult CurInitExprRes =
7040 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00007041 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00007042 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007043 return ExprError();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00007044
7045 S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get());
7046
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007047 CurInit = CurInitExprRes;
Richard Smithaaa0ec42013-09-21 21:19:19 +00007048
7049 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
Richard Smith52e624f2016-12-21 21:42:57 +00007050 S.getLangOpts().CPlusPlus)
Richard Smithaaa0ec42013-09-21 21:19:19 +00007051 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
7052 CurInit.get());
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00007053
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007054 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00007055 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007056
Douglas Gregor51e77d52009-12-10 17:56:55 +00007057 case SK_ListInitialization: {
Richard Smith81f5ade2016-12-15 02:28:18 +00007058 if (checkAbstractType(Step->Type))
7059 return ExprError();
7060
John Wiegley01296292011-04-08 18:41:53 +00007061 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smithcc1b96d2013-06-12 22:31:48 +00007062 // If we're not initializing the top-level entity, we need to create an
7063 // InitializeTemporary entity for our target type.
7064 QualType Ty = Step->Type;
7065 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl29526f02011-11-27 16:50:07 +00007066 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smithd712d0d2013-02-02 01:13:06 +00007067 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
7068 InitListChecker PerformInitList(S, InitEntity,
Manman Ren073db022016-03-10 18:53:19 +00007069 InitList, Ty, /*VerifyOnly=*/false,
7070 /*TreatUnavailableAsInvalid=*/false);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007071 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00007072 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00007073
Richard Smithcc1b96d2013-06-12 22:31:48 +00007074 // Hack: We must update *ResultType if available in order to set the
7075 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
7076 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
7077 if (ResultType &&
7078 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00007079 if ((*ResultType)->isRValueReferenceType())
7080 Ty = S.Context.getRValueReferenceType(Ty);
7081 else if ((*ResultType)->isLValueReferenceType())
7082 Ty = S.Context.getLValueReferenceType(Ty,
7083 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
7084 *ResultType = Ty;
7085 }
7086
7087 InitListExpr *StructuredInitList =
7088 PerformInitList.getFullyStructuredList();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007089 CurInit.get();
Richard Smithd712d0d2013-02-02 01:13:06 +00007090 CurInit = shouldBindAsTemporary(InitEntity)
7091 ? S.MaybeBindToTemporary(StructuredInitList)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007092 : StructuredInitList;
Douglas Gregor51e77d52009-12-10 17:56:55 +00007093 break;
7094 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007095
Richard Smith53324112014-07-16 21:33:43 +00007096 case SK_ConstructorInitializationFromList: {
Richard Smith81f5ade2016-12-15 02:28:18 +00007097 if (checkAbstractType(Step->Type))
7098 return ExprError();
7099
Sebastian Redl5a41f682012-02-12 16:37:24 +00007100 // When an initializer list is passed for a parameter of type "reference
7101 // to object", we don't get an EK_Temporary entity, but instead an
7102 // EK_Parameter entity with reference type.
Sebastian Redl99f66162012-02-19 12:27:56 +00007103 // FIXME: This is a hack. What we really should do is create a user
7104 // conversion step for this case, but this makes it considerably more
7105 // complicated. For now, this will do.
Sebastian Redl5a41f682012-02-12 16:37:24 +00007106 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
7107 Entity.getType().getNonReferenceType());
7108 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithd86812d2012-07-05 08:39:21 +00007109 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007110 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith2b349ae2012-04-19 06:58:00 +00007111 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
7112 << InitList->getSourceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00007113 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl5a41f682012-02-12 16:37:24 +00007114 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
7115 Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007116 Kind, Arg, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00007117 ConstructorInitRequiresZeroInit,
Richard Smith53324112014-07-16 21:33:43 +00007118 /*IsListInitialization*/true,
Richard Smithf8adcdc2014-07-17 05:12:35 +00007119 /*IsStdInitListInit*/false,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00007120 InitList->getLBraceLoc(),
7121 InitList->getRBraceLoc());
Sebastian Redled2e5322011-12-22 14:44:04 +00007122 break;
7123 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007124
Sebastian Redl29526f02011-11-27 16:50:07 +00007125 case SK_UnwrapInitList:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007126 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
Sebastian Redl29526f02011-11-27 16:50:07 +00007127 break;
7128
7129 case SK_RewrapInitList: {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007130 Expr *E = CurInit.get();
Sebastian Redl29526f02011-11-27 16:50:07 +00007131 InitListExpr *Syntactic = Step->WrappingSyntacticList;
7132 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramerc215e762012-08-24 11:54:20 +00007133 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl29526f02011-11-27 16:50:07 +00007134 ILE->setSyntacticForm(Syntactic);
7135 ILE->setType(E->getType());
7136 ILE->setValueKind(E->getValueKind());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007137 CurInit = ILE;
Sebastian Redl29526f02011-11-27 16:50:07 +00007138 break;
7139 }
7140
Richard Smith53324112014-07-16 21:33:43 +00007141 case SK_ConstructorInitialization:
Richard Smithf8adcdc2014-07-17 05:12:35 +00007142 case SK_StdInitializerListConstructorCall: {
Richard Smith81f5ade2016-12-15 02:28:18 +00007143 if (checkAbstractType(Step->Type))
7144 return ExprError();
7145
Sebastian Redl99f66162012-02-19 12:27:56 +00007146 // When an initializer list is passed for a parameter of type "reference
7147 // to object", we don't get an EK_Temporary entity, but instead an
7148 // EK_Parameter entity with reference type.
7149 // FIXME: This is a hack. What we really should do is create a user
7150 // conversion step for this case, but this makes it considerably more
7151 // complicated. For now, this will do.
7152 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
7153 Entity.getType().getNonReferenceType());
7154 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf8adcdc2014-07-17 05:12:35 +00007155 bool IsStdInitListInit =
7156 Step->Kind == SK_StdInitializerListConstructorCall;
Richard Smith410306b2016-12-12 02:53:20 +00007157 Expr *Source = CurInit.get();
Vedant Kumara14a1f92018-01-17 18:53:51 +00007158 SourceRange Range = Kind.hasParenOrBraceRange()
7159 ? Kind.getParenOrBraceRange()
7160 : SourceRange();
Richard Smith53324112014-07-16 21:33:43 +00007161 CurInit = PerformConstructorInitialization(
Richard Smith410306b2016-12-12 02:53:20 +00007162 S, UseTemporary ? TempEntity : Entity, Kind,
7163 Source ? MultiExprArg(Source) : Args, *Step,
Richard Smith53324112014-07-16 21:33:43 +00007164 ConstructorInitRequiresZeroInit,
Richard Smith410306b2016-12-12 02:53:20 +00007165 /*IsListInitialization*/ IsStdInitListInit,
7166 /*IsStdInitListInitialization*/ IsStdInitListInit,
Vedant Kumara14a1f92018-01-17 18:53:51 +00007167 /*LBraceLoc*/ Range.getBegin(),
7168 /*RBraceLoc*/ Range.getEnd());
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007169 break;
Sebastian Redl99f66162012-02-19 12:27:56 +00007170 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007171
Douglas Gregor7dc42e52009-12-15 00:01:57 +00007172 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007173 step_iterator NextStep = Step;
7174 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007175 if (NextStep != StepEnd &&
Richard Smithd86812d2012-07-05 08:39:21 +00007176 (NextStep->Kind == SK_ConstructorInitialization ||
Richard Smith53324112014-07-16 21:33:43 +00007177 NextStep->Kind == SK_ConstructorInitializationFromList)) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007178 // The need for zero-initialization is recorded directly into
7179 // the call to the object's constructor within the next step.
7180 ConstructorInitRequiresZeroInit = true;
7181 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007182 S.getLangOpts().CPlusPlus &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007183 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00007184 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7185 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007186 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00007187 Kind.getRange().getBegin());
7188
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007189 CurInit = new (S.Context) CXXScalarValueInitExpr(
Richard Smith60437622017-02-09 19:17:44 +00007190 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007191 Kind.getRange().getEnd());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007192 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007193 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007194 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00007195 break;
7196 }
Douglas Gregore1314a62009-12-18 05:02:21 +00007197
7198 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00007199 QualType SourceType = CurInit.get()->getType();
George Burgess IV5f21c712015-10-12 19:57:04 +00007200 // Save off the initial CurInit in case we need to emit a diagnostic
7201 ExprResult InitialCurInit = CurInit;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007202 ExprResult Result = CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00007203 Sema::AssignConvertType ConvTy =
Fariborz Jahanian25eef192013-07-31 21:40:51 +00007204 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
7205 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley01296292011-04-08 18:41:53 +00007206 if (Result.isInvalid())
7207 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007208 CurInit = Result;
Douglas Gregor96596c92009-12-22 07:24:36 +00007209
7210 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007211 ExprResult CurInitExprRes = CurInit;
Douglas Gregor96596c92009-12-22 07:24:36 +00007212 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00007213 Entity.isParameterKind() &&
John Wiegley01296292011-04-08 18:41:53 +00007214 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00007215 == Sema::Compatible)
7216 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00007217 if (CurInitExprRes.isInvalid())
7218 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007219 CurInit = CurInitExprRes;
Douglas Gregor96596c92009-12-22 07:24:36 +00007220
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007221 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00007222 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
7223 Step->Type, SourceType,
George Burgess IV5f21c712015-10-12 19:57:04 +00007224 InitialCurInit.get(),
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00007225 getAssignmentAction(Entity, true),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007226 &Complained)) {
7227 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00007228 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007229 } else if (Complained)
7230 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00007231 break;
7232 }
Eli Friedman78275202009-12-19 08:11:05 +00007233
7234 case SK_StringInit: {
7235 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00007236 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00007237 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00007238 break;
7239 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007240
7241 case SK_ObjCObjectConversion:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007242 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00007243 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00007244 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007245 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007246
Richard Smith410306b2016-12-12 02:53:20 +00007247 case SK_ArrayLoopIndex: {
7248 Expr *Cur = CurInit.get();
7249 Expr *BaseExpr = new (S.Context)
7250 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
7251 Cur->getValueKind(), Cur->getObjectKind(), Cur);
7252 Expr *IndexExpr =
7253 new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());
7254 CurInit = S.CreateBuiltinArraySubscriptExpr(
7255 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
7256 ArrayLoopCommonExprs.push_back(BaseExpr);
7257 break;
7258 }
7259
7260 case SK_ArrayLoopInit: {
7261 assert(!ArrayLoopCommonExprs.empty() &&
7262 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
7263 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
7264 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
7265 CurInit.get());
7266 break;
7267 }
7268
Richard Smith378b8c82016-12-14 03:22:16 +00007269 case SK_GNUArrayInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00007270 // Okay: we checked everything before creating this step. Note that
7271 // this is a GNU extension.
7272 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00007273 << Step->Type << CurInit.get()->getType()
7274 << CurInit.get()->getSourceRange();
Richard Smith378b8c82016-12-14 03:22:16 +00007275 LLVM_FALLTHROUGH;
7276 case SK_ArrayInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00007277 // If the destination type is an incomplete array type, update the
7278 // type accordingly.
7279 if (ResultType) {
7280 if (const IncompleteArrayType *IncompleteDest
7281 = S.Context.getAsIncompleteArrayType(Step->Type)) {
7282 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00007283 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00007284 *ResultType = S.Context.getConstantArrayType(
7285 IncompleteDest->getElementType(),
7286 ConstantSource->getSize(),
7287 ArrayType::Normal, 0);
7288 }
7289 }
7290 }
John McCall31168b02011-06-15 23:02:42 +00007291 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007292
Richard Smithebeed412012-02-15 22:38:09 +00007293 case SK_ParenthesizedArrayInit:
7294 // Okay: we checked everything before creating this step. Note that
7295 // this is a GNU extension.
7296 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
7297 << CurInit.get()->getSourceRange();
7298 break;
7299
John McCall31168b02011-06-15 23:02:42 +00007300 case SK_PassByIndirectCopyRestore:
7301 case SK_PassByIndirectRestore:
7302 checkIndirectCopyRestoreSource(S, CurInit.get());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007303 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
7304 CurInit.get(), Step->Type,
7305 Step->Kind == SK_PassByIndirectCopyRestore);
John McCall31168b02011-06-15 23:02:42 +00007306 break;
7307
7308 case SK_ProduceObjCObject:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007309 CurInit =
7310 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
7311 CurInit.get(), nullptr, VK_RValue);
Douglas Gregore2f943b2011-02-22 18:29:51 +00007312 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00007313
7314 case SK_StdInitializerList: {
Richard Smithcc1b96d2013-06-12 22:31:48 +00007315 S.Diag(CurInit.get()->getExprLoc(),
7316 diag::warn_cxx98_compat_initializer_list_init)
7317 << CurInit.get()->getSourceRange();
Sebastian Redl249dee52012-03-05 19:35:43 +00007318
Richard Smithcc1b96d2013-06-12 22:31:48 +00007319 // Materialize the temporary into memory.
Tim Shen4a05bb82016-06-21 20:29:17 +00007320 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
7321 CurInit.get()->getType(), CurInit.get(),
7322 /*BoundToLvalueReference=*/false);
David Majnemerdaff3702014-05-01 17:50:17 +00007323
7324 // Maybe lifetime-extend the array temporary's subobjects to match the
7325 // entity's lifetime.
7326 if (const InitializedEntity *ExtendingEntity =
7327 getEntityForTemporaryLifetimeExtension(&Entity))
7328 if (performReferenceExtension(MTE, ExtendingEntity))
7329 warnOnLifetimeExtension(S, Entity, CurInit.get(),
7330 /*IsInitializerList=*/true,
7331 ExtendingEntity->getDecl());
Richard Smithcc1b96d2013-06-12 22:31:48 +00007332
7333 // Wrap it in a construction of a std::initializer_list<T>.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007334 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
Richard Smithcc1b96d2013-06-12 22:31:48 +00007335
7336 // Bind the result, in case the library has given initializer_list a
7337 // non-trivial destructor.
7338 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007339 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redlc1839b12012-01-17 22:49:42 +00007340 break;
7341 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00007342
Guy Benyei61054192013-02-07 10:55:47 +00007343 case SK_OCLSamplerInit: {
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007344 // Sampler initialzation have 5 cases:
7345 // 1. function argument passing
7346 // 1a. argument is a file-scope variable
7347 // 1b. argument is a function-scope variable
7348 // 1c. argument is one of caller function's parameters
7349 // 2. variable initialization
7350 // 2a. initializing a file-scope variable
7351 // 2b. initializing a function-scope variable
7352 //
7353 // For file-scope variables, since they cannot be initialized by function
7354 // call of __translate_sampler_initializer in LLVM IR, their references
7355 // need to be replaced by a cast from their literal initializers to
7356 // sampler type. Since sampler variables can only be used in function
7357 // calls as arguments, we only need to replace them when handling the
7358 // argument passing.
7359 assert(Step->Type->isSamplerT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00007360 "Sampler initialization on non-sampler type.");
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007361 Expr *Init = CurInit.get();
7362 QualType SourceType = Init->getType();
7363 // Case 1
Fariborz Jahanian131996b2013-07-31 18:21:45 +00007364 if (Entity.isParameterKind()) {
Egor Churaeva8d24512017-04-05 09:02:56 +00007365 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
Guy Benyei61054192013-02-07 10:55:47 +00007366 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
7367 << SourceType;
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007368 break;
7369 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
7370 auto Var = cast<VarDecl>(DRE->getDecl());
7371 // Case 1b and 1c
7372 // No cast from integer to sampler is needed.
7373 if (!Var->hasGlobalStorage()) {
7374 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
7375 CK_LValueToRValue, Init,
7376 /*BasePath=*/nullptr, VK_RValue);
7377 break;
7378 }
7379 // Case 1a
7380 // For function call with a file-scope sampler variable as argument,
7381 // get the integer literal.
7382 // Do not diagnose if the file-scope variable does not have initializer
7383 // since this has already been diagnosed when parsing the variable
7384 // declaration.
7385 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
7386 break;
7387 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
7388 Var->getInit()))->getSubExpr();
7389 SourceType = Init->getType();
7390 }
7391 } else {
7392 // Case 2
7393 // Check initializer is 32 bit integer constant.
7394 // If the initializer is taken from global variable, do not diagnose since
7395 // this has already been done when parsing the variable declaration.
7396 if (!Init->isConstantInitializer(S.Context, false))
7397 break;
7398
7399 if (!SourceType->isIntegerType() ||
7400 32 != S.Context.getIntWidth(SourceType)) {
7401 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
7402 << SourceType;
7403 break;
7404 }
7405
7406 llvm::APSInt Result;
7407 Init->EvaluateAsInt(Result, S.Context);
7408 const uint64_t SamplerValue = Result.getLimitedValue();
7409 // 32-bit value of sampler's initializer is interpreted as
7410 // bit-field with the following structure:
7411 // |unspecified|Filter|Addressing Mode| Normalized Coords|
7412 // |31 6|5 4|3 1| 0|
7413 // This structure corresponds to enum values of sampler properties
7414 // defined in SPIR spec v1.2 and also opencl-c.h
7415 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
7416 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
7417 if (FilterMode != 1 && FilterMode != 2)
7418 S.Diag(Kind.getLocation(),
7419 diag::warn_sampler_initializer_invalid_bits)
7420 << "Filter Mode";
7421 if (AddressingMode > 4)
7422 S.Diag(Kind.getLocation(),
7423 diag::warn_sampler_initializer_invalid_bits)
7424 << "Addressing Mode";
Guy Benyei61054192013-02-07 10:55:47 +00007425 }
7426
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007427 // Cases 1a, 2a and 2b
7428 // Insert cast from integer to sampler.
7429 CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy,
7430 CK_IntToOCLSampler);
Guy Benyei61054192013-02-07 10:55:47 +00007431 break;
7432 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007433 case SK_OCLZeroEvent: {
7434 assert(Step->Type->isEventT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00007435 "Event initialization on non-event type.");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007436
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007437 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007438 CK_ZeroToOCLEvent,
7439 CurInit.get()->getValueKind());
7440 break;
7441 }
Egor Churaev89831422016-12-23 14:55:49 +00007442 case SK_OCLZeroQueue: {
7443 assert(Step->Type->isQueueT() &&
7444 "Event initialization on non queue type.");
7445
7446 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7447 CK_ZeroToOCLQueue,
7448 CurInit.get()->getValueKind());
7449 break;
7450 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007451 }
7452 }
John McCall1f425642010-11-11 03:21:53 +00007453
7454 // Diagnose non-fatal problems with the completed initialization.
7455 if (Entity.getKind() == InitializedEntity::EK_Member &&
7456 cast<FieldDecl>(Entity.getDecl())->isBitField())
7457 S.CheckBitFieldInitialization(Kind.getLocation(),
7458 cast<FieldDecl>(Entity.getDecl()),
7459 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007460
Richard Trieuac3eca52015-04-29 01:52:17 +00007461 // Check for std::move on construction.
7462 if (const Expr *E = CurInit.get()) {
7463 CheckMoveOnConstruction(S, E,
7464 Entity.getKind() == InitializedEntity::EK_Result);
7465 }
7466
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007467 return CurInit;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007468}
7469
Richard Smith593f9932012-12-08 02:01:17 +00007470/// Somewhere within T there is an uninitialized reference subobject.
7471/// Dig it out and diagnose it.
Benjamin Kramer3e350262013-02-15 12:30:38 +00007472static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
7473 QualType T) {
Richard Smith593f9932012-12-08 02:01:17 +00007474 if (T->isReferenceType()) {
7475 S.Diag(Loc, diag::err_reference_without_init)
7476 << T.getNonReferenceType();
7477 return true;
7478 }
7479
7480 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7481 if (!RD || !RD->hasUninitializedReferenceMember())
7482 return false;
7483
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007484 for (const auto *FI : RD->fields()) {
Richard Smith593f9932012-12-08 02:01:17 +00007485 if (FI->isUnnamedBitfield())
7486 continue;
7487
7488 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
7489 S.Diag(Loc, diag::note_value_initialization_here) << RD;
7490 return true;
7491 }
7492 }
7493
Aaron Ballman574705e2014-03-13 15:41:46 +00007494 for (const auto &BI : RD->bases()) {
7495 if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
Richard Smith593f9932012-12-08 02:01:17 +00007496 S.Diag(Loc, diag::note_value_initialization_here) << RD;
7497 return true;
7498 }
7499 }
7500
7501 return false;
7502}
7503
7504
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007505//===----------------------------------------------------------------------===//
7506// Diagnose initialization failures
7507//===----------------------------------------------------------------------===//
John McCall5ec7e7d2013-03-19 07:04:25 +00007508
7509/// Emit notes associated with an initialization that failed due to a
7510/// "simple" conversion failure.
7511static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
7512 Expr *op) {
7513 QualType destType = entity.getType();
7514 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
7515 op->getType()->isObjCObjectPointerType()) {
7516
7517 // Emit a possible note about the conversion failing because the
7518 // operand is a message send with a related result type.
7519 S.EmitRelatedResultTypeNote(op);
7520
7521 // Emit a possible note about a return failing because we're
7522 // expecting a related result type.
7523 if (entity.getKind() == InitializedEntity::EK_Result)
7524 S.EmitRelatedResultTypeNoteForReturn(destType);
7525 }
7526}
7527
Richard Smith0449aaf2013-11-21 23:30:57 +00007528static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
7529 InitListExpr *InitList) {
7530 QualType DestType = Entity.getType();
7531
7532 QualType E;
7533 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
7534 QualType ArrayType = S.Context.getConstantArrayType(
7535 E.withConst(),
7536 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
7537 InitList->getNumInits()),
7538 clang::ArrayType::Normal, 0);
7539 InitializedEntity HiddenArray =
7540 InitializedEntity::InitializeTemporary(ArrayType);
7541 return diagnoseListInit(S, HiddenArray, InitList);
7542 }
7543
Richard Smith8d082d12014-09-04 22:13:39 +00007544 if (DestType->isReferenceType()) {
7545 // A list-initialization failure for a reference means that we tried to
7546 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
7547 // inner initialization failed.
7548 QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
7549 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
7550 SourceLocation Loc = InitList->getLocStart();
7551 if (auto *D = Entity.getDecl())
7552 Loc = D->getLocation();
7553 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
7554 return;
7555 }
7556
Richard Smith0449aaf2013-11-21 23:30:57 +00007557 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
Manman Ren073db022016-03-10 18:53:19 +00007558 /*VerifyOnly=*/false,
7559 /*TreatUnavailableAsInvalid=*/false);
Richard Smith0449aaf2013-11-21 23:30:57 +00007560 assert(DiagnoseInitList.HadError() &&
7561 "Inconsistent init list check result.");
7562}
7563
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007564bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007565 const InitializedEntity &Entity,
7566 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007567 ArrayRef<Expr *> Args) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00007568 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007569 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007570
Douglas Gregor1b303932009-12-22 15:35:07 +00007571 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007572 switch (Failure) {
7573 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007574 // FIXME: Customize for the initialized entity?
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007575 if (Args.empty()) {
Richard Smith593f9932012-12-08 02:01:17 +00007576 // Dig out the reference subobject which is uninitialized and diagnose it.
7577 // If this is value-initialization, this could be nested some way within
7578 // the target type.
7579 assert(Kind.getKind() == InitializationKind::IK_Value ||
7580 DestType->isReferenceType());
7581 bool Diagnosed =
7582 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
7583 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
7584 (void)Diagnosed;
7585 } else // FIXME: diagnostic below could be better!
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007586 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007587 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007588 break;
Richard Smith49a6b6e2017-03-24 01:14:25 +00007589 case FK_ParenthesizedListInitForReference:
7590 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
7591 << 1 << Entity.getType() << Args[0]->getSourceRange();
7592 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007593
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007594 case FK_ArrayNeedsInitList:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00007595 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007596 break;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00007597 case FK_ArrayNeedsInitListOrStringLiteral:
7598 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
7599 break;
7600 case FK_ArrayNeedsInitListOrWideStringLiteral:
7601 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
7602 break;
7603 case FK_NarrowStringIntoWideCharArray:
7604 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
7605 break;
7606 case FK_WideStringIntoCharArray:
7607 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
7608 break;
7609 case FK_IncompatWideStringIntoWideChar:
7610 S.Diag(Kind.getLocation(),
7611 diag::err_array_init_incompat_wide_string_into_wchar);
7612 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00007613 case FK_PlainStringIntoUTF8Char:
7614 S.Diag(Kind.getLocation(),
7615 diag::err_array_init_plain_string_into_char8_t);
7616 S.Diag(Args.front()->getLocStart(),
7617 diag::note_array_init_plain_string_into_char8_t)
7618 << FixItHint::CreateInsertion(Args.front()->getLocStart(), "u8");
7619 break;
7620 case FK_UTF8StringIntoPlainChar:
7621 S.Diag(Kind.getLocation(),
7622 diag::err_array_init_utf8_string_into_char);
7623 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007624 case FK_ArrayTypeMismatch:
7625 case FK_NonConstantArrayInit:
Richard Smith0449aaf2013-11-21 23:30:57 +00007626 S.Diag(Kind.getLocation(),
Douglas Gregore2f943b2011-02-22 18:29:51 +00007627 (Failure == FK_ArrayTypeMismatch
7628 ? diag::err_array_init_different_type
7629 : diag::err_array_init_non_constant_array))
7630 << DestType.getNonReferenceType()
7631 << Args[0]->getType()
7632 << Args[0]->getSourceRange();
7633 break;
7634
John McCalla59dc2f2012-01-05 00:13:19 +00007635 case FK_VariableLengthArrayHasInitializer:
7636 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
7637 << Args[0]->getSourceRange();
7638 break;
7639
John McCall16df1e52010-03-30 21:47:33 +00007640 case FK_AddressOfOverloadFailed: {
7641 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007642 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007643 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00007644 true,
7645 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007646 break;
John McCall16df1e52010-03-30 21:47:33 +00007647 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007648
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007649 case FK_AddressOfUnaddressableFunction: {
7650 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(Args[0])->getDecl());
7651 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
7652 Args[0]->getLocStart());
7653 break;
7654 }
7655
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007656 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00007657 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007658 switch (FailedOverloadResult) {
7659 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00007660 if (Failure == FK_UserConversionOverloadFailed)
7661 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
7662 << Args[0]->getType() << DestType
7663 << Args[0]->getSourceRange();
7664 else
7665 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
7666 << DestType << Args[0]->getType()
7667 << Args[0]->getSourceRange();
7668
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007669 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007670 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007671
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007672 case OR_No_Viable_Function:
Larisse Voufo70bb43a2013-06-27 03:36:30 +00007673 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00007674 DestType.getNonReferenceType(),
7675 diag::err_typecheck_nonviable_condition_incomplete,
7676 Args[0]->getType(), Args[0]->getSourceRange()))
7677 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00007678 << (Entity.getKind() == InitializedEntity::EK_Result)
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00007679 << Args[0]->getType() << Args[0]->getSourceRange()
7680 << DestType.getNonReferenceType();
7681
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007682 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007683 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007684
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007685 case OR_Deleted: {
7686 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
7687 << Args[0]->getType() << DestType.getNonReferenceType()
7688 << Args[0]->getSourceRange();
7689 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007690 OverloadingResult Ovl
Richard Smith67ef14f2017-09-26 18:37:55 +00007691 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007692 if (Ovl == OR_Deleted) {
Richard Smith852265f2012-03-30 20:53:28 +00007693 S.NoteDeletedFunction(Best->Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007694 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00007695 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007696 }
7697 break;
7698 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007699
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007700 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00007701 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007702 }
7703 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007704
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007705 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00007706 if (isa<InitListExpr>(Args[0])) {
7707 S.Diag(Kind.getLocation(),
7708 diag::err_lvalue_reference_bind_to_initlist)
7709 << DestType.getNonReferenceType().isVolatileQualified()
7710 << DestType.getNonReferenceType()
7711 << Args[0]->getSourceRange();
7712 break;
7713 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007714 LLVM_FALLTHROUGH;
Sebastian Redl29526f02011-11-27 16:50:07 +00007715
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007716 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007717 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007718 Failure == FK_NonConstLValueReferenceBindingToTemporary
7719 ? diag::err_lvalue_reference_bind_to_temporary
7720 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00007721 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007722 << DestType.getNonReferenceType()
7723 << Args[0]->getType()
7724 << Args[0]->getSourceRange();
7725 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007726
Richard Smithb8c0f552016-12-09 18:49:13 +00007727 case FK_NonConstLValueReferenceBindingToBitfield: {
7728 // We don't necessarily have an unambiguous source bit-field.
7729 FieldDecl *BitField = Args[0]->getSourceBitField();
7730 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
7731 << DestType.isVolatileQualified()
7732 << (BitField ? BitField->getDeclName() : DeclarationName())
7733 << (BitField != nullptr)
7734 << Args[0]->getSourceRange();
7735 if (BitField)
7736 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
7737 break;
7738 }
7739
7740 case FK_NonConstLValueReferenceBindingToVectorElement:
7741 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
7742 << DestType.isVolatileQualified()
7743 << Args[0]->getSourceRange();
7744 break;
7745
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007746 case FK_RValueReferenceBindingToLValue:
7747 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00007748 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007749 << Args[0]->getSourceRange();
7750 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007751
Richard Trieuf956a492015-05-16 01:27:03 +00007752 case FK_ReferenceInitDropsQualifiers: {
7753 QualType SourceType = Args[0]->getType();
7754 QualType NonRefType = DestType.getNonReferenceType();
7755 Qualifiers DroppedQualifiers =
7756 SourceType.getQualifiers() - NonRefType.getQualifiers();
7757
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007758 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
Richard Trieuf956a492015-05-16 01:27:03 +00007759 << SourceType
7760 << NonRefType
7761 << DroppedQualifiers.getCVRQualifiers()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007762 << Args[0]->getSourceRange();
7763 break;
Richard Trieuf956a492015-05-16 01:27:03 +00007764 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007765
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007766 case FK_ReferenceInitFailed:
7767 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
7768 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00007769 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007770 << Args[0]->getType()
7771 << Args[0]->getSourceRange();
John McCall5ec7e7d2013-03-19 07:04:25 +00007772 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007773 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007774
Douglas Gregorb491ed32011-02-19 21:32:49 +00007775 case FK_ConversionFailed: {
7776 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00007777 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00007778 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007779 << DestType
John McCall086a4642010-11-24 05:12:34 +00007780 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00007781 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007782 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00007783 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
7784 S.Diag(Kind.getLocation(), PDiag);
John McCall5ec7e7d2013-03-19 07:04:25 +00007785 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00007786 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007787 }
John Wiegley01296292011-04-08 18:41:53 +00007788
7789 case FK_ConversionFromPropertyFailed:
7790 // No-op. This error has already been reported.
7791 break;
7792
Douglas Gregor51e77d52009-12-10 17:56:55 +00007793 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00007794 SourceRange R;
7795
David Majnemerbd385442015-04-10 04:52:06 +00007796 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
Benjamin Kramerc4284e32015-09-23 16:03:53 +00007797 if (InitList && InitList->getNumInits() >= 1) {
David Majnemerbd385442015-04-10 04:52:06 +00007798 R = SourceRange(InitList->getInit(0)->getLocEnd(), InitList->getLocEnd());
Benjamin Kramerc4284e32015-09-23 16:03:53 +00007799 } else {
7800 assert(Args.size() > 1 && "Expected multiple initializers!");
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007801 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Benjamin Kramerc4284e32015-09-23 16:03:53 +00007802 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00007803
Alp Tokerb6cc5922014-05-03 03:45:55 +00007804 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
Douglas Gregor8ec51732010-09-08 21:40:08 +00007805 if (Kind.isCStyleOrFunctionalCast())
7806 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
7807 << R;
7808 else
7809 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
7810 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00007811 break;
7812 }
7813
Richard Smith49a6b6e2017-03-24 01:14:25 +00007814 case FK_ParenthesizedListInitForScalar:
7815 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
7816 << 0 << Entity.getType() << Args[0]->getSourceRange();
7817 break;
7818
Douglas Gregor51e77d52009-12-10 17:56:55 +00007819 case FK_ReferenceBindingToInitList:
7820 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
7821 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
7822 break;
7823
7824 case FK_InitListBadDestinationType:
7825 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
7826 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
7827 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007828
Sebastian Redl6901c0d2011-12-22 18:58:38 +00007829 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007830 case FK_ConstructorOverloadFailed: {
7831 SourceRange ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007832 if (Args.size())
7833 ArgsRange = SourceRange(Args.front()->getLocStart(),
7834 Args.back()->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007835
Sebastian Redl6901c0d2011-12-22 18:58:38 +00007836 if (Failure == FK_ListConstructorOverloadFailed) {
Nico Weber9709ebf2014-07-08 23:54:25 +00007837 assert(Args.size() == 1 &&
7838 "List construction from other than 1 argument.");
Sebastian Redl6901c0d2011-12-22 18:58:38 +00007839 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007840 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00007841 }
7842
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007843 // FIXME: Using "DestType" for the entity we're printing is probably
7844 // bad.
7845 switch (FailedOverloadResult) {
7846 case OR_Ambiguous:
7847 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
7848 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007849 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007850 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007851
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007852 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007853 if (Kind.getKind() == InitializationKind::IK_Default &&
7854 (Entity.getKind() == InitializedEntity::EK_Base ||
7855 Entity.getKind() == InitializedEntity::EK_Member) &&
7856 isa<CXXConstructorDecl>(S.CurContext)) {
7857 // This is implicit default initialization of a member or
7858 // base within a constructor. If no viable function was
Nico Webera6916892016-06-10 18:53:04 +00007859 // found, notify the user that they need to explicitly
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007860 // initialize this base/member.
7861 CXXConstructorDecl *Constructor
7862 = cast<CXXConstructorDecl>(S.CurContext);
Richard Smith5179eb72016-06-28 19:03:57 +00007863 const CXXRecordDecl *InheritedFrom = nullptr;
7864 if (auto Inherited = Constructor->getInheritedConstructor())
7865 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007866 if (Entity.getKind() == InitializedEntity::EK_Base) {
7867 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith5179eb72016-06-28 19:03:57 +00007868 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007869 << S.Context.getTypeDeclType(Constructor->getParent())
7870 << /*base=*/0
Richard Smith5179eb72016-06-28 19:03:57 +00007871 << Entity.getType()
7872 << InheritedFrom;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007873
7874 RecordDecl *BaseDecl
7875 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
7876 ->getDecl();
7877 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
7878 << S.Context.getTagDeclType(BaseDecl);
7879 } else {
7880 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith5179eb72016-06-28 19:03:57 +00007881 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007882 << S.Context.getTypeDeclType(Constructor->getParent())
7883 << /*member=*/1
Richard Smith5179eb72016-06-28 19:03:57 +00007884 << Entity.getName()
7885 << InheritedFrom;
Alp Toker2afa8782014-05-28 12:20:14 +00007886 S.Diag(Entity.getDecl()->getLocation(),
7887 diag::note_member_declared_at);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007888
7889 if (const RecordType *Record
7890 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007891 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007892 diag::note_previous_decl)
7893 << S.Context.getTagDeclType(Record->getDecl());
7894 }
7895 break;
7896 }
7897
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007898 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
7899 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007900 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007901 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007902
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007903 case OR_Deleted: {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007904 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007905 OverloadingResult Ovl
7906 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor74f7d502012-02-15 19:33:52 +00007907 if (Ovl != OR_Deleted) {
7908 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
7909 << true << DestType << ArgsRange;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007910 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor74f7d502012-02-15 19:33:52 +00007911 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007912 }
Douglas Gregor74f7d502012-02-15 19:33:52 +00007913
7914 // If this is a defaulted or implicitly-declared function, then
7915 // it was implicitly deleted. Make it clear that the deletion was
7916 // implicit.
Richard Smith852265f2012-03-30 20:53:28 +00007917 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00007918 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith852265f2012-03-30 20:53:28 +00007919 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00007920 << DestType << ArgsRange;
Richard Smith852265f2012-03-30 20:53:28 +00007921 else
7922 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
7923 << true << DestType << ArgsRange;
7924
7925 S.NoteDeletedFunction(Best->Function);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007926 break;
7927 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007928
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007929 case OR_Success:
7930 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007931 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007932 }
David Blaikie60deeee2012-01-17 08:24:58 +00007933 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007934
Douglas Gregor85dabae2009-12-16 01:38:02 +00007935 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007936 if (Entity.getKind() == InitializedEntity::EK_Member &&
7937 isa<CXXConstructorDecl>(S.CurContext)) {
7938 // This is implicit default-initialization of a const member in
7939 // a constructor. Complain that it needs to be explicitly
7940 // initialized.
7941 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
7942 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00007943 << (Constructor->getInheritedConstructor() ? 2 :
7944 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007945 << S.Context.getTypeDeclType(Constructor->getParent())
7946 << /*const=*/1
7947 << Entity.getName();
7948 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
7949 << Entity.getName();
7950 } else {
7951 S.Diag(Kind.getLocation(), diag::err_default_init_const)
Nico Weber9386c822014-07-23 05:16:10 +00007952 << DestType << (bool)DestType->getAs<RecordType>();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007953 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00007954 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007955
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007956 case FK_Incomplete:
Douglas Gregor85f34232012-04-10 20:43:46 +00007957 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007958 diag::err_init_incomplete_type);
7959 break;
7960
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007961 case FK_ListInitializationFailed: {
7962 // Run the init list checker again to emit diagnostics.
Richard Smith0449aaf2013-11-21 23:30:57 +00007963 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
7964 diagnoseListInit(S, Entity, InitList);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007965 break;
7966 }
John McCall4124c492011-10-17 18:40:02 +00007967
7968 case FK_PlaceholderType: {
7969 // FIXME: Already diagnosed!
7970 break;
7971 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00007972
Sebastian Redl048a6d72012-04-01 19:54:59 +00007973 case FK_ExplicitConstructor: {
7974 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
7975 << Args[0]->getSourceRange();
7976 OverloadCandidateSet::iterator Best;
7977 OverloadingResult Ovl
7978 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gay5dcce092012-04-02 19:05:35 +00007979 (void)Ovl;
Sebastian Redl048a6d72012-04-01 19:54:59 +00007980 assert(Ovl == OR_Success && "Inconsistent overload resolution");
7981 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
Richard Smith60437622017-02-09 19:17:44 +00007982 S.Diag(CtorDecl->getLocation(),
7983 diag::note_explicit_ctor_deduction_guide_here) << false;
Sebastian Redl048a6d72012-04-01 19:54:59 +00007984 break;
7985 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007986 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007987
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007988 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007989 return true;
7990}
Douglas Gregore1314a62009-12-18 05:02:21 +00007991
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007992void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007993 switch (SequenceKind) {
7994 case FailedSequence: {
7995 OS << "Failed sequence: ";
7996 switch (Failure) {
7997 case FK_TooManyInitsForReference:
7998 OS << "too many initializers for reference";
7999 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008000
Richard Smith49a6b6e2017-03-24 01:14:25 +00008001 case FK_ParenthesizedListInitForReference:
8002 OS << "parenthesized list init for reference";
8003 break;
8004
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008005 case FK_ArrayNeedsInitList:
8006 OS << "array requires initializer list";
8007 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008008
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008009 case FK_AddressOfUnaddressableFunction:
8010 OS << "address of unaddressable function was taken";
8011 break;
8012
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008013 case FK_ArrayNeedsInitListOrStringLiteral:
8014 OS << "array requires initializer list or string literal";
8015 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008016
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00008017 case FK_ArrayNeedsInitListOrWideStringLiteral:
8018 OS << "array requires initializer list or wide string literal";
8019 break;
8020
8021 case FK_NarrowStringIntoWideCharArray:
8022 OS << "narrow string into wide char array";
8023 break;
8024
8025 case FK_WideStringIntoCharArray:
8026 OS << "wide string into char array";
8027 break;
8028
8029 case FK_IncompatWideStringIntoWideChar:
8030 OS << "incompatible wide string into wide char array";
8031 break;
8032
Richard Smith3a8244d2018-05-01 05:02:45 +00008033 case FK_PlainStringIntoUTF8Char:
8034 OS << "plain string literal into char8_t array";
8035 break;
8036
8037 case FK_UTF8StringIntoPlainChar:
8038 OS << "u8 string literal into char array";
8039 break;
8040
Douglas Gregore2f943b2011-02-22 18:29:51 +00008041 case FK_ArrayTypeMismatch:
8042 OS << "array type mismatch";
8043 break;
8044
8045 case FK_NonConstantArrayInit:
8046 OS << "non-constant array initializer";
8047 break;
8048
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008049 case FK_AddressOfOverloadFailed:
8050 OS << "address of overloaded function failed";
8051 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008052
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008053 case FK_ReferenceInitOverloadFailed:
8054 OS << "overload resolution for reference initialization failed";
8055 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008056
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008057 case FK_NonConstLValueReferenceBindingToTemporary:
8058 OS << "non-const lvalue reference bound to temporary";
8059 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008060
Richard Smithb8c0f552016-12-09 18:49:13 +00008061 case FK_NonConstLValueReferenceBindingToBitfield:
8062 OS << "non-const lvalue reference bound to bit-field";
8063 break;
8064
8065 case FK_NonConstLValueReferenceBindingToVectorElement:
8066 OS << "non-const lvalue reference bound to vector element";
8067 break;
8068
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008069 case FK_NonConstLValueReferenceBindingToUnrelated:
8070 OS << "non-const lvalue reference bound to unrelated type";
8071 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008072
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008073 case FK_RValueReferenceBindingToLValue:
8074 OS << "rvalue reference bound to an lvalue";
8075 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008076
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008077 case FK_ReferenceInitDropsQualifiers:
8078 OS << "reference initialization drops qualifiers";
8079 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008080
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008081 case FK_ReferenceInitFailed:
8082 OS << "reference initialization failed";
8083 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008084
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008085 case FK_ConversionFailed:
8086 OS << "conversion failed";
8087 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008088
John Wiegley01296292011-04-08 18:41:53 +00008089 case FK_ConversionFromPropertyFailed:
8090 OS << "conversion from property failed";
8091 break;
8092
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008093 case FK_TooManyInitsForScalar:
8094 OS << "too many initializers for scalar";
8095 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008096
Richard Smith49a6b6e2017-03-24 01:14:25 +00008097 case FK_ParenthesizedListInitForScalar:
8098 OS << "parenthesized list init for reference";
8099 break;
8100
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008101 case FK_ReferenceBindingToInitList:
8102 OS << "referencing binding to initializer list";
8103 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008104
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008105 case FK_InitListBadDestinationType:
8106 OS << "initializer list for non-aggregate, non-scalar type";
8107 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008108
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008109 case FK_UserConversionOverloadFailed:
8110 OS << "overloading failed for user-defined conversion";
8111 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008112
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008113 case FK_ConstructorOverloadFailed:
8114 OS << "constructor overloading failed";
8115 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008116
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008117 case FK_DefaultInitOfConst:
8118 OS << "default initialization of a const variable";
8119 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008120
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00008121 case FK_Incomplete:
8122 OS << "initialization of incomplete type";
8123 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008124
8125 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008126 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00008127 break;
8128
John McCalla59dc2f2012-01-05 00:13:19 +00008129 case FK_VariableLengthArrayHasInitializer:
8130 OS << "variable length array has an initializer";
8131 break;
8132
John McCall4124c492011-10-17 18:40:02 +00008133 case FK_PlaceholderType:
8134 OS << "initializer expression isn't contextually valid";
8135 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00008136
8137 case FK_ListConstructorOverloadFailed:
8138 OS << "list constructor overloading failed";
8139 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00008140
Sebastian Redl048a6d72012-04-01 19:54:59 +00008141 case FK_ExplicitConstructor:
8142 OS << "list copy initialization chose explicit constructor";
8143 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008144 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008145 OS << '\n';
8146 return;
8147 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008148
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008149 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00008150 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008151 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008152
Sebastian Redld201edf2011-06-05 13:59:11 +00008153 case NormalSequence:
8154 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008155 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008156 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008157
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008158 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
8159 if (S != step_begin()) {
8160 OS << " -> ";
8161 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008162
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008163 switch (S->Kind) {
8164 case SK_ResolveAddressOfOverloadedFunction:
8165 OS << "resolve address of overloaded function";
8166 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008167
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008168 case SK_CastDerivedToBaseRValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00008169 OS << "derived-to-base (rvalue)";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008170 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008171
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008172 case SK_CastDerivedToBaseXValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00008173 OS << "derived-to-base (xvalue)";
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008174 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008175
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008176 case SK_CastDerivedToBaseLValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00008177 OS << "derived-to-base (lvalue)";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008178 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008179
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008180 case SK_BindReference:
8181 OS << "bind reference to lvalue";
8182 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008183
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008184 case SK_BindReferenceToTemporary:
8185 OS << "bind reference to a temporary";
8186 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008187
Richard Smithb8c0f552016-12-09 18:49:13 +00008188 case SK_FinalCopy:
8189 OS << "final copy in class direct-initialization";
8190 break;
8191
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00008192 case SK_ExtraneousCopyToTemporary:
8193 OS << "extraneous C++03 copy to temporary";
8194 break;
8195
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008196 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00008197 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008198 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008199
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008200 case SK_QualificationConversionRValue:
8201 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00008202 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008203
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008204 case SK_QualificationConversionXValue:
8205 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00008206 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008207
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008208 case SK_QualificationConversionLValue:
8209 OS << "qualification conversion (lvalue)";
8210 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008211
Richard Smith77be48a2014-07-31 06:31:19 +00008212 case SK_AtomicConversion:
8213 OS << "non-atomic-to-atomic conversion";
8214 break;
8215
Jordan Roseb1312a52013-04-11 00:58:58 +00008216 case SK_LValueToRValue:
8217 OS << "load (lvalue to rvalue)";
8218 break;
8219
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008220 case SK_ConversionSequence:
8221 OS << "implicit conversion sequence (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00008222 S->ICS->dump(); // FIXME: use OS
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008223 OS << ")";
8224 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008225
Richard Smithaaa0ec42013-09-21 21:19:19 +00008226 case SK_ConversionSequenceNoNarrowing:
8227 OS << "implicit conversion sequence with narrowing prohibited (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00008228 S->ICS->dump(); // FIXME: use OS
Richard Smithaaa0ec42013-09-21 21:19:19 +00008229 OS << ")";
8230 break;
8231
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008232 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008233 OS << "list aggregate initialization";
8234 break;
8235
Sebastian Redl29526f02011-11-27 16:50:07 +00008236 case SK_UnwrapInitList:
8237 OS << "unwrap reference initializer list";
8238 break;
8239
8240 case SK_RewrapInitList:
8241 OS << "rewrap reference initializer list";
8242 break;
8243
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008244 case SK_ConstructorInitialization:
8245 OS << "constructor initialization";
8246 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008247
Richard Smith53324112014-07-16 21:33:43 +00008248 case SK_ConstructorInitializationFromList:
8249 OS << "list initialization via constructor";
8250 break;
8251
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008252 case SK_ZeroInitialization:
8253 OS << "zero initialization";
8254 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008255
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008256 case SK_CAssignment:
8257 OS << "C assignment";
8258 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008259
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008260 case SK_StringInit:
8261 OS << "string initialization";
8262 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008263
8264 case SK_ObjCObjectConversion:
8265 OS << "Objective-C object conversion";
8266 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00008267
Richard Smith410306b2016-12-12 02:53:20 +00008268 case SK_ArrayLoopIndex:
8269 OS << "indexing for array initialization loop";
8270 break;
8271
8272 case SK_ArrayLoopInit:
8273 OS << "array initialization loop";
8274 break;
8275
Douglas Gregore2f943b2011-02-22 18:29:51 +00008276 case SK_ArrayInit:
8277 OS << "array initialization";
8278 break;
John McCall31168b02011-06-15 23:02:42 +00008279
Richard Smith378b8c82016-12-14 03:22:16 +00008280 case SK_GNUArrayInit:
8281 OS << "array initialization (GNU extension)";
8282 break;
8283
Richard Smithebeed412012-02-15 22:38:09 +00008284 case SK_ParenthesizedArrayInit:
8285 OS << "parenthesized array initialization";
8286 break;
8287
John McCall31168b02011-06-15 23:02:42 +00008288 case SK_PassByIndirectCopyRestore:
8289 OS << "pass by indirect copy and restore";
8290 break;
8291
8292 case SK_PassByIndirectRestore:
8293 OS << "pass by indirect restore";
8294 break;
8295
8296 case SK_ProduceObjCObject:
8297 OS << "Objective-C object retension";
8298 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00008299
8300 case SK_StdInitializerList:
8301 OS << "std::initializer_list from initializer list";
8302 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008303
Richard Smithf8adcdc2014-07-17 05:12:35 +00008304 case SK_StdInitializerListConstructorCall:
8305 OS << "list initialization from std::initializer_list";
8306 break;
8307
Guy Benyei61054192013-02-07 10:55:47 +00008308 case SK_OCLSamplerInit:
8309 OS << "OpenCL sampler_t from integer constant";
8310 break;
8311
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008312 case SK_OCLZeroEvent:
8313 OS << "OpenCL event_t from zero";
8314 break;
Egor Churaev89831422016-12-23 14:55:49 +00008315
8316 case SK_OCLZeroQueue:
8317 OS << "OpenCL queue_t from zero";
8318 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008319 }
Richard Smith6b216962013-02-05 05:52:24 +00008320
8321 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008322 }
Richard Smith6b216962013-02-05 05:52:24 +00008323
8324 OS << '\n';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008325}
8326
8327void InitializationSequence::dump() const {
8328 dump(llvm::errs());
8329}
8330
Richard Smithaaa0ec42013-09-21 21:19:19 +00008331static void DiagnoseNarrowingInInitList(Sema &S,
8332 const ImplicitConversionSequence &ICS,
8333 QualType PreNarrowingType,
Richard Smith66e05fe2012-01-18 05:21:49 +00008334 QualType EntityType,
Richard Smith66e05fe2012-01-18 05:21:49 +00008335 const Expr *PostInit) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008336 const StandardConversionSequence *SCS = nullptr;
Richard Smith66e05fe2012-01-18 05:21:49 +00008337 switch (ICS.getKind()) {
8338 case ImplicitConversionSequence::StandardConversion:
8339 SCS = &ICS.Standard;
8340 break;
8341 case ImplicitConversionSequence::UserDefinedConversion:
8342 SCS = &ICS.UserDefined.After;
8343 break;
8344 case ImplicitConversionSequence::AmbiguousConversion:
8345 case ImplicitConversionSequence::EllipsisConversion:
8346 case ImplicitConversionSequence::BadConversion:
8347 return;
8348 }
8349
Richard Smith66e05fe2012-01-18 05:21:49 +00008350 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
8351 APValue ConstantValue;
Richard Smith5614ca72012-03-23 23:55:39 +00008352 QualType ConstantType;
8353 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
8354 ConstantType)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00008355 case NK_Not_Narrowing:
Richard Smith52e624f2016-12-21 21:42:57 +00008356 case NK_Dependent_Narrowing:
Richard Smith66e05fe2012-01-18 05:21:49 +00008357 // No narrowing occurred.
8358 return;
8359
8360 case NK_Type_Narrowing:
8361 // This was a floating-to-integer conversion, which is always considered a
8362 // narrowing conversion even if the value is a constant and can be
8363 // represented exactly as an integer.
8364 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00008365 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
8366 ? diag::warn_init_list_type_narrowing
8367 : diag::ext_init_list_type_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00008368 << PostInit->getSourceRange()
8369 << PreNarrowingType.getLocalUnqualifiedType()
8370 << EntityType.getLocalUnqualifiedType();
8371 break;
8372
8373 case NK_Constant_Narrowing:
8374 // A constant value was narrowed.
8375 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00008376 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
8377 ? diag::warn_init_list_constant_narrowing
8378 : diag::ext_init_list_constant_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00008379 << PostInit->getSourceRange()
Richard Smith5614ca72012-03-23 23:55:39 +00008380 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00008381 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00008382 break;
8383
8384 case NK_Variable_Narrowing:
8385 // A variable's value may have been narrowed.
8386 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00008387 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
8388 ? diag::warn_init_list_variable_narrowing
8389 : diag::ext_init_list_variable_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00008390 << PostInit->getSourceRange()
8391 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00008392 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00008393 break;
8394 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008395
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008396 SmallString<128> StaticCast;
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008397 llvm::raw_svector_ostream OS(StaticCast);
8398 OS << "static_cast<";
8399 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
8400 // It's important to use the typedef's name if there is one so that the
8401 // fixit doesn't break code using types like int64_t.
8402 //
8403 // FIXME: This will break if the typedef requires qualification. But
8404 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00008405 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008406 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikiebbafb8a2012-03-11 07:00:24 +00008407 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008408 else {
8409 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
8410 // with a broken cast.
8411 return;
8412 }
8413 OS << ">(";
Alp Tokerb0869032014-05-17 01:13:18 +00008414 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence)
Alp Tokerb6cc5922014-05-03 03:45:55 +00008415 << PostInit->getSourceRange()
8416 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
8417 << FixItHint::CreateInsertion(
8418 S.getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008419}
8420
Douglas Gregore1314a62009-12-18 05:02:21 +00008421//===----------------------------------------------------------------------===//
8422// Initialization helper functions
8423//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00008424bool
8425Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
8426 ExprResult Init) {
8427 if (Init.isInvalid())
8428 return false;
8429
8430 Expr *InitE = Init.get();
8431 assert(InitE && "No initialization expression");
8432
Douglas Gregorf4cc61d2012-07-31 22:15:04 +00008433 InitializationKind Kind
8434 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008435 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00008436 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00008437}
8438
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008439ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00008440Sema::PerformCopyInitialization(const InitializedEntity &Entity,
8441 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008442 ExprResult Init,
Douglas Gregor6073dca2012-02-24 23:56:31 +00008443 bool TopLevelOfInitList,
8444 bool AllowExplicit) {
Douglas Gregore1314a62009-12-18 05:02:21 +00008445 if (Init.isInvalid())
8446 return ExprError();
8447
John McCall1f425642010-11-11 03:21:53 +00008448 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00008449 assert(InitE && "No initialization expression?");
8450
8451 if (EqualLoc.isInvalid())
8452 EqualLoc = InitE->getLocStart();
8453
8454 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00008455 EqualLoc,
8456 AllowExplicit);
Richard Smithaaa0ec42013-09-21 21:19:19 +00008457 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008458
Alex Lorenzde69ff92017-05-16 10:23:58 +00008459 // Prevent infinite recursion when performing parameter copy-initialization.
8460 const bool ShouldTrackCopy =
8461 Entity.isParameterKind() && Seq.isConstructorInitialization();
8462 if (ShouldTrackCopy) {
8463 if (llvm::find(CurrentParameterCopyTypes, Entity.getType()) !=
8464 CurrentParameterCopyTypes.end()) {
8465 Seq.SetOverloadFailure(
8466 InitializationSequence::FK_ConstructorOverloadFailed,
8467 OR_No_Viable_Function);
8468
8469 // Try to give a meaningful diagnostic note for the problematic
8470 // constructor.
8471 const auto LastStep = Seq.step_end() - 1;
8472 assert(LastStep->Kind ==
8473 InitializationSequence::SK_ConstructorInitialization);
8474 const FunctionDecl *Function = LastStep->Function.Function;
8475 auto Candidate =
8476 llvm::find_if(Seq.getFailedCandidateSet(),
8477 [Function](const OverloadCandidate &Candidate) -> bool {
8478 return Candidate.Viable &&
8479 Candidate.Function == Function &&
8480 Candidate.Conversions.size() > 0;
8481 });
8482 if (Candidate != Seq.getFailedCandidateSet().end() &&
8483 Function->getNumParams() > 0) {
8484 Candidate->Viable = false;
8485 Candidate->FailureKind = ovl_fail_bad_conversion;
8486 Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion,
8487 InitE,
8488 Function->getParamDecl(0)->getType());
8489 }
8490 }
8491 CurrentParameterCopyTypes.push_back(Entity.getType());
8492 }
8493
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008494 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith66e05fe2012-01-18 05:21:49 +00008495
Alex Lorenzde69ff92017-05-16 10:23:58 +00008496 if (ShouldTrackCopy)
8497 CurrentParameterCopyTypes.pop_back();
8498
Richard Smith66e05fe2012-01-18 05:21:49 +00008499 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00008500}
Richard Smith60437622017-02-09 19:17:44 +00008501
Richard Smith1363e8f2017-09-07 07:22:36 +00008502/// Determine whether RD is, or is derived from, a specialization of CTD.
8503static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD,
8504 ClassTemplateDecl *CTD) {
8505 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
8506 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
8507 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
8508 };
8509 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
8510}
8511
Richard Smith60437622017-02-09 19:17:44 +00008512QualType Sema::DeduceTemplateSpecializationFromInitializer(
8513 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
8514 const InitializationKind &Kind, MultiExprArg Inits) {
8515 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
8516 TSInfo->getType()->getContainedDeducedType());
8517 assert(DeducedTST && "not a deduced template specialization type");
8518
8519 // We can only perform deduction for class templates.
8520 auto TemplateName = DeducedTST->getTemplateName();
8521 auto *Template =
8522 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
8523 if (!Template) {
8524 Diag(Kind.getLocation(),
8525 diag::err_deduced_non_class_template_specialization_type)
8526 << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName;
8527 if (auto *TD = TemplateName.getAsTemplateDecl())
8528 Diag(TD->getLocation(), diag::note_template_decl_here);
8529 return QualType();
8530 }
8531
Richard Smith32918772017-02-14 00:25:28 +00008532 // Can't deduce from dependent arguments.
8533 if (Expr::hasAnyTypeDependentArguments(Inits))
8534 return Context.DependentTy;
8535
Richard Smith60437622017-02-09 19:17:44 +00008536 // FIXME: Perform "exact type" matching first, per CWG discussion?
8537 // Or implement this via an implied 'T(T) -> T' deduction guide?
8538
8539 // FIXME: Do we need/want a std::initializer_list<T> special case?
8540
Richard Smith32918772017-02-14 00:25:28 +00008541 // Look up deduction guides, including those synthesized from constructors.
8542 //
Richard Smith60437622017-02-09 19:17:44 +00008543 // C++1z [over.match.class.deduct]p1:
8544 // A set of functions and function templates is formed comprising:
Richard Smith32918772017-02-14 00:25:28 +00008545 // - For each constructor of the class template designated by the
8546 // template-name, a function template [...]
Richard Smith60437622017-02-09 19:17:44 +00008547 // - For each deduction-guide, a function or function template [...]
8548 DeclarationNameInfo NameInfo(
8549 Context.DeclarationNames.getCXXDeductionGuideName(Template),
8550 TSInfo->getTypeLoc().getEndLoc());
8551 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
8552 LookupQualifiedName(Guides, Template->getDeclContext());
Richard Smith60437622017-02-09 19:17:44 +00008553
8554 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
8555 // clear on this, but they're not found by name so access does not apply.
8556 Guides.suppressDiagnostics();
8557
8558 // Figure out if this is list-initialization.
8559 InitListExpr *ListInit =
8560 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
8561 ? dyn_cast<InitListExpr>(Inits[0])
8562 : nullptr;
8563
8564 // C++1z [over.match.class.deduct]p1:
8565 // Initialization and overload resolution are performed as described in
8566 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
8567 // (as appropriate for the type of initialization performed) for an object
8568 // of a hypothetical class type, where the selected functions and function
8569 // templates are considered to be the constructors of that class type
8570 //
8571 // Since we know we're initializing a class type of a type unrelated to that
8572 // of the initializer, this reduces to something fairly reasonable.
8573 OverloadCandidateSet Candidates(Kind.getLocation(),
8574 OverloadCandidateSet::CSK_Normal);
8575 OverloadCandidateSet::iterator Best;
8576 auto tryToResolveOverload =
8577 [&](bool OnlyListConstructors) -> OverloadingResult {
Richard Smith67ef14f2017-09-26 18:37:55 +00008578 Candidates.clear(OverloadCandidateSet::CSK_Normal);
Richard Smith32918772017-02-14 00:25:28 +00008579 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
8580 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smith60437622017-02-09 19:17:44 +00008581 if (D->isInvalidDecl())
8582 continue;
8583
Richard Smithbc491202017-02-17 20:05:37 +00008584 auto *TD = dyn_cast<FunctionTemplateDecl>(D);
8585 auto *GD = dyn_cast_or_null<CXXDeductionGuideDecl>(
8586 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
8587 if (!GD)
Richard Smith60437622017-02-09 19:17:44 +00008588 continue;
8589
8590 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
8591 // For copy-initialization, the candidate functions are all the
8592 // converting constructors (12.3.1) of that class.
8593 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
8594 // The converting constructors of T are candidate functions.
8595 if (Kind.isCopyInit() && !ListInit) {
Richard Smithafe4aa82017-02-10 02:19:05 +00008596 // Only consider converting constructors.
Richard Smithbc491202017-02-17 20:05:37 +00008597 if (GD->isExplicit())
Richard Smithafe4aa82017-02-10 02:19:05 +00008598 continue;
Richard Smith60437622017-02-09 19:17:44 +00008599
8600 // When looking for a converting constructor, deduction guides that
Richard Smithafe4aa82017-02-10 02:19:05 +00008601 // could never be called with one argument are not interesting to
8602 // check or note.
Richard Smithbc491202017-02-17 20:05:37 +00008603 if (GD->getMinRequiredArguments() > 1 ||
8604 (GD->getNumParams() == 0 && !GD->isVariadic()))
Richard Smith60437622017-02-09 19:17:44 +00008605 continue;
8606 }
8607
8608 // C++ [over.match.list]p1.1: (first phase list initialization)
8609 // Initially, the candidate functions are the initializer-list
8610 // constructors of the class T
Richard Smithbc491202017-02-17 20:05:37 +00008611 if (OnlyListConstructors && !isInitListConstructor(GD))
Richard Smith60437622017-02-09 19:17:44 +00008612 continue;
8613
8614 // C++ [over.match.list]p1.2: (second phase list initialization)
8615 // the candidate functions are all the constructors of the class T
8616 // C++ [over.match.ctor]p1: (all other cases)
8617 // the candidate functions are all the constructors of the class of
8618 // the object being initialized
8619
8620 // C++ [over.best.ics]p4:
8621 // When [...] the constructor [...] is a candidate by
8622 // - [over.match.copy] (in all cases)
8623 // FIXME: The "second phase of [over.match.list] case can also
8624 // theoretically happen here, but it's not clear whether we can
8625 // ever have a parameter of the right type.
8626 bool SuppressUserConversions = Kind.isCopyInit();
8627
Richard Smith60437622017-02-09 19:17:44 +00008628 if (TD)
Richard Smith32918772017-02-14 00:25:28 +00008629 AddTemplateOverloadCandidate(TD, I.getPair(), /*ExplicitArgs*/ nullptr,
8630 Inits, Candidates,
8631 SuppressUserConversions);
Richard Smith60437622017-02-09 19:17:44 +00008632 else
Richard Smithbc491202017-02-17 20:05:37 +00008633 AddOverloadCandidate(GD, I.getPair(), Inits, Candidates,
Richard Smith60437622017-02-09 19:17:44 +00008634 SuppressUserConversions);
8635 }
8636 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
8637 };
8638
8639 OverloadingResult Result = OR_No_Viable_Function;
8640
8641 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
8642 // try initializer-list constructors.
8643 if (ListInit) {
Richard Smith32918772017-02-14 00:25:28 +00008644 bool TryListConstructors = true;
8645
8646 // Try list constructors unless the list is empty and the class has one or
8647 // more default constructors, in which case those constructors win.
8648 if (!ListInit->getNumInits()) {
8649 for (NamedDecl *D : Guides) {
8650 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
8651 if (FD && FD->getMinRequiredArguments() == 0) {
8652 TryListConstructors = false;
8653 break;
8654 }
8655 }
Richard Smith1363e8f2017-09-07 07:22:36 +00008656 } else if (ListInit->getNumInits() == 1) {
8657 // C++ [over.match.class.deduct]:
8658 // As an exception, the first phase in [over.match.list] (considering
8659 // initializer-list constructors) is omitted if the initializer list
8660 // consists of a single expression of type cv U, where U is a
8661 // specialization of C or a class derived from a specialization of C.
8662 Expr *E = ListInit->getInit(0);
8663 auto *RD = E->getType()->getAsCXXRecordDecl();
8664 if (!isa<InitListExpr>(E) && RD &&
8665 isOrIsDerivedFromSpecializationOf(RD, Template))
8666 TryListConstructors = false;
Richard Smith32918772017-02-14 00:25:28 +00008667 }
8668
8669 if (TryListConstructors)
Richard Smith60437622017-02-09 19:17:44 +00008670 Result = tryToResolveOverload(/*OnlyListConstructor*/true);
8671 // Then unwrap the initializer list and try again considering all
8672 // constructors.
8673 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
8674 }
8675
8676 // If list-initialization fails, or if we're doing any other kind of
8677 // initialization, we (eventually) consider constructors.
8678 if (Result == OR_No_Viable_Function)
8679 Result = tryToResolveOverload(/*OnlyListConstructor*/false);
8680
8681 switch (Result) {
8682 case OR_Ambiguous:
8683 Diag(Kind.getLocation(), diag::err_deduced_class_template_ctor_ambiguous)
8684 << TemplateName;
8685 // FIXME: For list-initialization candidates, it'd usually be better to
8686 // list why they were not viable when given the initializer list itself as
8687 // an argument.
8688 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Inits);
8689 return QualType();
8690
Richard Smith32918772017-02-14 00:25:28 +00008691 case OR_No_Viable_Function: {
8692 CXXRecordDecl *Primary =
8693 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
8694 bool Complete =
8695 isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
Richard Smith60437622017-02-09 19:17:44 +00008696 Diag(Kind.getLocation(),
8697 Complete ? diag::err_deduced_class_template_ctor_no_viable
8698 : diag::err_deduced_class_template_incomplete)
Richard Smith32918772017-02-14 00:25:28 +00008699 << TemplateName << !Guides.empty();
Richard Smith60437622017-02-09 19:17:44 +00008700 Candidates.NoteCandidates(*this, OCD_AllCandidates, Inits);
8701 return QualType();
Richard Smith32918772017-02-14 00:25:28 +00008702 }
Richard Smith60437622017-02-09 19:17:44 +00008703
8704 case OR_Deleted: {
8705 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
8706 << TemplateName;
8707 NoteDeletedFunction(Best->Function);
8708 return QualType();
8709 }
8710
8711 case OR_Success:
8712 // C++ [over.match.list]p1:
8713 // In copy-list-initialization, if an explicit constructor is chosen, the
8714 // initialization is ill-formed.
Richard Smithbc491202017-02-17 20:05:37 +00008715 if (Kind.isCopyInit() && ListInit &&
8716 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
Richard Smith60437622017-02-09 19:17:44 +00008717 bool IsDeductionGuide = !Best->Function->isImplicit();
8718 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
8719 << TemplateName << IsDeductionGuide;
8720 Diag(Best->Function->getLocation(),
8721 diag::note_explicit_ctor_deduction_guide_here)
8722 << IsDeductionGuide;
8723 return QualType();
8724 }
8725
8726 // Make sure we didn't select an unusable deduction guide, and mark it
8727 // as referenced.
8728 DiagnoseUseOfDecl(Best->Function, Kind.getLocation());
8729 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
8730 break;
8731 }
8732
8733 // C++ [dcl.type.class.deduct]p1:
8734 // The placeholder is replaced by the return type of the function selected
8735 // by overload resolution for class template deduction.
8736 return SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());
8737}