blob: 0dddbdc36fdc4620235e27de0d221f1bd3136e73 [file] [log] [blame]
Steve Narofff8ecff22008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Sebastian Redl26bcc942011-09-24 17:47:39 +000010// This file implements semantic analysis for initializers.
Chris Lattner0cb78032009-02-24 22:27:37 +000011//
Steve Narofff8ecff22008-05-01 22:18:59 +000012//===----------------------------------------------------------------------===//
13
Steve Narofff8ecff22008-05-01 22:18:59 +000014#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000015#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000016#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000017#include "clang/AST/ExprObjC.h"
Richard Smithafe48f92018-07-23 21:21:22 +000018#include "clang/AST/ExprOpenMP.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000019#include "clang/AST/TypeLoc.h"
James Molloy9eef2652014-06-20 14:35:13 +000020#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Sema/Designator.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000022#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Sema/Lookup.h"
24#include "clang/Sema/SemaInternal.h"
Sebastian Redlc1839b12012-01-17 22:49:42 +000025#include "llvm/ADT/APInt.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000026#include "llvm/ADT/SmallString.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000027#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskina6667812011-07-26 23:20:30 +000028#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000029
Douglas Gregore4a0bb72009-01-22 00:58:24 +000030using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000031
Chris Lattner0cb78032009-02-24 22:27:37 +000032//===----------------------------------------------------------------------===//
33// Sema Initialization Checking
34//===----------------------------------------------------------------------===//
35
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000036/// Check whether T is compatible with a wide character type (wchar_t,
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000037/// char16_t or char32_t).
38static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
39 if (Context.typesAreCompatible(Context.getWideCharType(), T))
40 return true;
41 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
42 return Context.typesAreCompatible(Context.Char16Ty, T) ||
43 Context.typesAreCompatible(Context.Char32Ty, T);
44 }
45 return false;
46}
47
48enum StringInitFailureKind {
49 SIF_None,
50 SIF_NarrowStringIntoWideChar,
51 SIF_WideStringIntoChar,
52 SIF_IncompatWideStringIntoWideChar,
Richard Smith3a8244d2018-05-01 05:02:45 +000053 SIF_UTF8StringIntoPlainChar,
54 SIF_PlainStringIntoUTF8Char,
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000055 SIF_Other
56};
57
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000058/// Check whether the array of type AT can be initialized by the Init
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000059/// expression by means of string initialization. Returns SIF_None if so,
60/// otherwise returns a StringInitFailureKind that describes why the
61/// initialization would not work.
62static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
63 ASTContext &Context) {
Eli Friedman893abe42009-05-29 18:22:49 +000064 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000065 return SIF_Other;
Eli Friedman893abe42009-05-29 18:22:49 +000066
Chris Lattnera9196812009-02-26 23:26:43 +000067 // See if this is a string literal or @encode.
68 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000069
Chris Lattnera9196812009-02-26 23:26:43 +000070 // Handle @encode, which is a narrow string.
71 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000072 return SIF_None;
Chris Lattnera9196812009-02-26 23:26:43 +000073
74 // Otherwise we can only handle string literals.
75 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Craig Topperc3ec1492014-05-26 06:22:03 +000076 if (!SL)
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000077 return SIF_Other;
Eli Friedman42a84652009-05-31 10:54:53 +000078
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000079 const QualType ElemTy =
80 Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
Douglas Gregorfb65e592011-07-27 05:40:30 +000081
82 switch (SL->getKind()) {
Douglas Gregorfb65e592011-07-27 05:40:30 +000083 case StringLiteral::UTF8:
Richard Smith3a8244d2018-05-01 05:02:45 +000084 // char8_t array can be initialized with a UTF-8 string.
85 if (ElemTy->isChar8Type())
86 return SIF_None;
87 LLVM_FALLTHROUGH;
88 case StringLiteral::Ascii:
Douglas Gregorfb65e592011-07-27 05:40:30 +000089 // char array can be initialized with a narrow string.
90 // Only allow char x[] = "foo"; not char x[] = L"foo";
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000091 if (ElemTy->isCharType())
Richard Smith3a8244d2018-05-01 05:02:45 +000092 return (SL->getKind() == StringLiteral::UTF8 &&
93 Context.getLangOpts().Char8)
94 ? SIF_UTF8StringIntoPlainChar
95 : SIF_None;
96 if (ElemTy->isChar8Type())
97 return SIF_PlainStringIntoUTF8Char;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000098 if (IsWideCharCompatible(ElemTy, Context))
99 return SIF_NarrowStringIntoWideChar;
100 return SIF_Other;
101 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
102 // "An array with element type compatible with a qualified or unqualified
103 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
104 // string literal with the corresponding encoding prefix (L, u, or U,
105 // respectively), optionally enclosed in braces.
Douglas Gregorfb65e592011-07-27 05:40:30 +0000106 case StringLiteral::UTF16:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000107 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
108 return SIF_None;
Richard Smith3a8244d2018-05-01 05:02:45 +0000109 if (ElemTy->isCharType() || ElemTy->isChar8Type())
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000110 return SIF_WideStringIntoChar;
111 if (IsWideCharCompatible(ElemTy, Context))
112 return SIF_IncompatWideStringIntoWideChar;
113 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000114 case StringLiteral::UTF32:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000115 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
116 return SIF_None;
Richard Smith3a8244d2018-05-01 05:02:45 +0000117 if (ElemTy->isCharType() || ElemTy->isChar8Type())
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000118 return SIF_WideStringIntoChar;
119 if (IsWideCharCompatible(ElemTy, Context))
120 return SIF_IncompatWideStringIntoWideChar;
121 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000122 case StringLiteral::Wide:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000123 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
124 return SIF_None;
Richard Smith3a8244d2018-05-01 05:02:45 +0000125 if (ElemTy->isCharType() || ElemTy->isChar8Type())
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000126 return SIF_WideStringIntoChar;
127 if (IsWideCharCompatible(ElemTy, Context))
128 return SIF_IncompatWideStringIntoWideChar;
129 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000130 }
Mike Stump11289f42009-09-09 15:08:12 +0000131
Douglas Gregorfb65e592011-07-27 05:40:30 +0000132 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattner0cb78032009-02-24 22:27:37 +0000133}
134
Hans Wennborg950f3182013-05-16 09:22:40 +0000135static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
136 ASTContext &Context) {
John McCall66884dd2011-02-21 07:22:22 +0000137 const ArrayType *arrayType = Context.getAsArrayType(declType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000138 if (!arrayType)
Hans Wennborg950f3182013-05-16 09:22:40 +0000139 return SIF_Other;
140 return IsStringInit(init, arrayType, Context);
John McCall66884dd2011-02-21 07:22:22 +0000141}
142
Richard Smith430c23b2013-05-05 16:40:13 +0000143/// Update the type of a string literal, including any surrounding parentheses,
144/// to match the type of the object which it is initializing.
145static void updateStringLiteralType(Expr *E, QualType Ty) {
Richard Smithd74b16062013-05-06 00:35:47 +0000146 while (true) {
Richard Smith430c23b2013-05-05 16:40:13 +0000147 E->setType(Ty);
Richard Smithd74b16062013-05-06 00:35:47 +0000148 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
149 break;
150 else if (ParenExpr *PE = dyn_cast<ParenExpr>(E))
151 E = PE->getSubExpr();
152 else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
153 E = UO->getSubExpr();
154 else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E))
155 E = GSE->getResultExpr();
156 else
157 llvm_unreachable("unexpected expr in string literal init");
Richard Smith430c23b2013-05-05 16:40:13 +0000158 }
Richard Smith430c23b2013-05-05 16:40:13 +0000159}
160
John McCall5decec92011-02-21 07:57:55 +0000161static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
162 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000163 // Get the length of the string as parsed.
Ben Langmuir577b3932015-01-26 19:04:10 +0000164 auto *ConstantArrayTy =
Ben Langmuir7b30f532015-01-26 20:01:17 +0000165 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
Ben Langmuir577b3932015-01-26 19:04:10 +0000166 uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
Mike Stump11289f42009-09-09 15:08:12 +0000167
Chris Lattner0cb78032009-02-24 22:27:37 +0000168 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +0000169 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +0000170 // being initialized to a string literal.
Benjamin Kramere0731772012-08-04 17:00:46 +0000171 llvm::APInt ConstVal(32, StrLength);
Chris Lattner0cb78032009-02-24 22:27:37 +0000172 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +0000173 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
174 ConstVal,
175 ArrayType::Normal, 0);
Richard Smith430c23b2013-05-05 16:40:13 +0000176 updateStringLiteralType(Str, DeclT);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000177 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000178 }
Mike Stump11289f42009-09-09 15:08:12 +0000179
Eli Friedman893abe42009-05-29 18:22:49 +0000180 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000181
Eli Friedman554eba92011-04-11 00:23:45 +0000182 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +0000183 // the size may be smaller or larger than the string we are initializing.
184 // FIXME: Avoid truncation for 64-bit length strings.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000185 if (S.getLangOpts().CPlusPlus) {
Richard Smith430c23b2013-05-05 16:40:13 +0000186 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
Anders Carlssond162fb82011-04-14 00:41:11 +0000187 // For Pascal strings it's OK to strip off the terminating null character,
188 // so the example below is valid:
189 //
190 // unsigned char a[2] = "\pa";
191 if (SL->isPascal())
192 StrLength--;
193 }
194
Eli Friedman554eba92011-04-11 00:23:45 +0000195 // [dcl.init.string]p2
196 if (StrLength > CAT->getSize().getZExtValue())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000197 S.Diag(Str->getLocStart(),
Eli Friedman554eba92011-04-11 00:23:45 +0000198 diag::err_initializer_string_for_char_array_too_long)
199 << Str->getSourceRange();
200 } else {
201 // C99 6.7.8p14.
202 if (StrLength-1 > CAT->getSize().getZExtValue())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000203 S.Diag(Str->getLocStart(),
Richard Smith1b98ccc2014-07-19 01:39:17 +0000204 diag::ext_initializer_string_for_char_array_too_long)
Eli Friedman554eba92011-04-11 00:23:45 +0000205 << Str->getSourceRange();
206 }
Mike Stump11289f42009-09-09 15:08:12 +0000207
Eli Friedman893abe42009-05-29 18:22:49 +0000208 // Set the type to the actual size that we are initializing. If we have
209 // something like:
210 // char x[1] = "foo";
211 // then this will set the string literal's type to char[1].
Richard Smith430c23b2013-05-05 16:40:13 +0000212 updateStringLiteralType(Str, DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000213}
214
Chris Lattner0cb78032009-02-24 22:27:37 +0000215//===----------------------------------------------------------------------===//
216// Semantic checking for initializer lists.
217//===----------------------------------------------------------------------===//
218
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000219namespace {
220
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000221/// Semantic checking for initializer lists.
Douglas Gregorcde232f2009-01-29 01:05:33 +0000222///
223/// The InitListChecker class contains a set of routines that each
224/// handle the initialization of a certain kind of entity, e.g.,
225/// arrays, vectors, struct/union types, scalars, etc. The
226/// InitListChecker itself performs a recursive walk of the subobject
227/// structure of the type to be initialized, while stepping through
228/// the initializer list one element at a time. The IList and Index
229/// parameters to each of the Check* routines contain the active
230/// (syntactic) initializer list and the index into that initializer
231/// list that represents the current initializer. Each routine is
232/// responsible for moving that Index forward as it consumes elements.
233///
234/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000235/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000236/// initializer list and the index into that initializer list where we
237/// are copying initializers as we map them over to the semantic
238/// list. Once we have completed our recursive walk of the subobject
239/// structure, we will have constructed a full semantic initializer
240/// list.
241///
242/// C99 designators cause changes in the initializer list traversal,
243/// because they make the initialization "jump" into a specific
244/// subobject and then continue the initialization from that
245/// point. CheckDesignatedInitializer() recursively steps into the
246/// designated subobject and manages backing out the recursion to
247/// initialize the subobjects after the one designated.
Douglas Gregor85df8d82009-01-29 00:45:39 +0000248class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000249 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000250 bool hadError;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000251 bool VerifyOnly; // no diagnostics, no structure building
Manman Ren073db022016-03-10 18:53:19 +0000252 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
Benjamin Kramer6b441d62012-02-23 14:48:40 +0000253 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000254 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000255
Anders Carlsson6cabf312010-01-23 23:23:01 +0000256 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000257 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000258 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000259 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000260 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000261 InitListExpr *IList, QualType &T,
Richard Smith4e0d2e42013-09-20 20:10:22 +0000262 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000263 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000264 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000265 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000266 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000267 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000268 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000269 unsigned &StructuredIndex,
270 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000271 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000272 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000273 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000274 InitListExpr *StructuredList,
275 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000276 void CheckComplexType(const InitializedEntity &Entity,
277 InitListExpr *IList, QualType DeclType,
278 unsigned &Index,
279 InitListExpr *StructuredList,
280 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000281 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000282 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000283 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000284 InitListExpr *StructuredList,
285 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000286 void CheckReferenceType(const InitializedEntity &Entity,
287 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000288 unsigned &Index,
289 InitListExpr *StructuredList,
290 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000291 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000292 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000293 InitListExpr *StructuredList,
294 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000295 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000296 InitListExpr *IList, QualType DeclType,
Richard Smith872307e2016-03-08 22:17:41 +0000297 CXXRecordDecl::base_class_range Bases,
Mike Stump11289f42009-09-09 15:08:12 +0000298 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000299 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000300 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000301 unsigned &StructuredIndex,
302 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000303 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000304 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000305 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000306 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000307 InitListExpr *StructuredList,
308 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000309 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000310 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000311 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000312 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000313 RecordDecl::field_iterator *NextField,
314 llvm::APSInt *NextElementIndex,
315 unsigned &Index,
316 InitListExpr *StructuredList,
317 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000318 bool FinishSubobjectInit,
319 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000320 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
321 QualType CurrentObjectType,
322 InitListExpr *StructuredList,
323 unsigned StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000324 SourceRange InitRange,
325 bool IsFullyOverwritten = false);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000326 void UpdateStructuredListElement(InitListExpr *StructuredList,
327 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000328 Expr *expr);
329 int numArrayElements(QualType DeclType);
330 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000331
Richard Smith454a7cd2014-06-03 08:26:00 +0000332 static ExprResult PerformEmptyInit(Sema &SemaRef,
333 SourceLocation Loc,
334 const InitializedEntity &Entity,
Manman Ren073db022016-03-10 18:53:19 +0000335 bool VerifyOnly,
336 bool TreatUnavailableAsInvalid);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000337
338 // Explanation on the "FillWithNoInit" mode:
339 //
340 // Assume we have the following definitions (Case#1):
341 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
342 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
343 //
344 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
345 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
346 //
347 // But if we have (Case#2):
348 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
349 //
350 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
351 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
352 //
353 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
354 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
355 // initializers but with special "NoInitExpr" place holders, which tells the
356 // CodeGen not to generate any initializers for these parts.
Richard Smith872307e2016-03-08 22:17:41 +0000357 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
358 const InitializedEntity &ParentEntity,
359 InitListExpr *ILE, bool &RequiresSecondPass,
360 bool FillWithNoInit);
Richard Smith454a7cd2014-06-03 08:26:00 +0000361 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000362 const InitializedEntity &ParentEntity,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000363 InitListExpr *ILE, bool &RequiresSecondPass,
364 bool FillWithNoInit = false);
Richard Smith454a7cd2014-06-03 08:26:00 +0000365 void FillInEmptyInitializations(const InitializedEntity &Entity,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000366 InitListExpr *ILE, bool &RequiresSecondPass,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000367 InitListExpr *OuterILE, unsigned OuterIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000368 bool FillWithNoInit = false);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000369 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
370 Expr *InitExpr, FieldDecl *Field,
371 bool TopLevelObject);
Richard Smith454a7cd2014-06-03 08:26:00 +0000372 void CheckEmptyInitializable(const InitializedEntity &Entity,
373 SourceLocation Loc);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000374
Douglas Gregor85df8d82009-01-29 00:45:39 +0000375public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000376 InitListChecker(Sema &S, const InitializedEntity &Entity,
Manman Ren073db022016-03-10 18:53:19 +0000377 InitListExpr *IL, QualType &T, bool VerifyOnly,
378 bool TreatUnavailableAsInvalid);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000379 bool HadError() { return hadError; }
380
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000381 // Retrieves the fully-structured initializer list used for
Douglas Gregor85df8d82009-01-29 00:45:39 +0000382 // semantic analysis and code generation.
383 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
384};
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000385
Chris Lattner9ececce2009-02-24 22:48:58 +0000386} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000387
Richard Smith454a7cd2014-06-03 08:26:00 +0000388ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
389 SourceLocation Loc,
390 const InitializedEntity &Entity,
Manman Ren073db022016-03-10 18:53:19 +0000391 bool VerifyOnly,
392 bool TreatUnavailableAsInvalid) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000393 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
394 true);
Richard Smith454a7cd2014-06-03 08:26:00 +0000395 MultiExprArg SubInit;
396 Expr *InitExpr;
397 InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
398
399 // C++ [dcl.init.aggr]p7:
400 // If there are fewer initializer-clauses in the list than there are
401 // members in the aggregate, then each member not explicitly initialized
402 // ...
Nico Weberbcb70ee2014-07-02 23:51:09 +0000403 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
404 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
405 if (EmptyInitList) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000406 // C++1y / DR1070:
407 // shall be initialized [...] from an empty initializer list.
408 //
409 // We apply the resolution of this DR to C++11 but not C++98, since C++98
410 // does not have useful semantics for initialization from an init list.
411 // We treat this as copy-initialization, because aggregate initialization
412 // always performs copy-initialization on its elements.
413 //
414 // Only do this if we're initializing a class type, to avoid filling in
415 // the initializer list where possible.
416 InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
417 InitListExpr(SemaRef.Context, Loc, None, Loc);
418 InitExpr->setType(SemaRef.Context.VoidTy);
419 SubInit = InitExpr;
420 Kind = InitializationKind::CreateCopy(Loc, Loc);
421 } else {
422 // C++03:
423 // shall be value-initialized.
424 }
425
426 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000427 // libstdc++4.6 marks the vector default constructor as explicit in
428 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
429 // stlport does so too. Look for std::__debug for libstdc++, and for
430 // std:: for stlport. This is effectively a compiler-side implementation of
431 // LWG2193.
432 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
433 InitializationSequence::FK_ExplicitConstructor) {
434 OverloadCandidateSet::iterator Best;
435 OverloadingResult O =
436 InitSeq.getFailedCandidateSet()
437 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
438 (void)O;
439 assert(O == OR_Success && "Inconsistent overload resolution");
440 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
441 CXXRecordDecl *R = CtorDecl->getParent();
442
443 if (CtorDecl->getMinRequiredArguments() == 0 &&
444 CtorDecl->isExplicit() && R->getDeclName() &&
445 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
Nico Weberbcb70ee2014-07-02 23:51:09 +0000446 bool IsInStd = false;
447 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
Nico Weber5752ad02014-07-03 00:38:25 +0000448 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
Nico Weberbcb70ee2014-07-02 23:51:09 +0000449 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
450 IsInStd = true;
451 }
452
453 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
454 .Cases("basic_string", "deque", "forward_list", true)
455 .Cases("list", "map", "multimap", "multiset", true)
456 .Cases("priority_queue", "queue", "set", "stack", true)
457 .Cases("unordered_map", "unordered_set", "vector", true)
458 .Default(false)) {
459 InitSeq.InitializeFrom(
460 SemaRef, Entity,
461 InitializationKind::CreateValue(Loc, Loc, Loc, true),
Manman Ren073db022016-03-10 18:53:19 +0000462 MultiExprArg(), /*TopLevelOfInitList=*/false,
463 TreatUnavailableAsInvalid);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000464 // Emit a warning for this. System header warnings aren't shown
465 // by default, but people working on system headers should see it.
466 if (!VerifyOnly) {
467 SemaRef.Diag(CtorDecl->getLocation(),
468 diag::warn_invalid_initializer_from_system_header);
David Majnemer9588a952015-08-21 06:44:10 +0000469 if (Entity.getKind() == InitializedEntity::EK_Member)
470 SemaRef.Diag(Entity.getDecl()->getLocation(),
471 diag::note_used_in_initialization_here);
472 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
473 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000474 }
475 }
476 }
477 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000478 if (!InitSeq) {
479 if (!VerifyOnly) {
480 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
481 if (Entity.getKind() == InitializedEntity::EK_Member)
482 SemaRef.Diag(Entity.getDecl()->getLocation(),
483 diag::note_in_omitted_aggregate_initializer)
484 << /*field*/1 << Entity.getDecl();
Richard Smith0511d232016-10-05 22:41:02 +0000485 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
486 bool IsTrailingArrayNewMember =
487 Entity.getParent() &&
488 Entity.getParent()->isVariableLengthArrayNew();
Richard Smith454a7cd2014-06-03 08:26:00 +0000489 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
Richard Smith0511d232016-10-05 22:41:02 +0000490 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
491 << Entity.getElementIndex();
492 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000493 }
494 return ExprError();
495 }
496
497 return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
498 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
499}
500
501void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
502 SourceLocation Loc) {
503 assert(VerifyOnly &&
504 "CheckEmptyInitializable is only inteded for verification mode.");
Manman Ren073db022016-03-10 18:53:19 +0000505 if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true,
506 TreatUnavailableAsInvalid).isInvalid())
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000507 hadError = true;
508}
509
Richard Smith872307e2016-03-08 22:17:41 +0000510void InitListChecker::FillInEmptyInitForBase(
511 unsigned Init, const CXXBaseSpecifier &Base,
512 const InitializedEntity &ParentEntity, InitListExpr *ILE,
513 bool &RequiresSecondPass, bool FillWithNoInit) {
514 assert(Init < ILE->getNumInits() && "should have been expanded");
515
516 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
517 SemaRef.Context, &Base, false, &ParentEntity);
518
519 if (!ILE->getInit(Init)) {
520 ExprResult BaseInit =
521 FillWithNoInit ? new (SemaRef.Context) NoInitExpr(Base.getType())
522 : PerformEmptyInit(SemaRef, ILE->getLocEnd(), BaseEntity,
Manman Ren073db022016-03-10 18:53:19 +0000523 /*VerifyOnly*/ false,
524 TreatUnavailableAsInvalid);
Richard Smith872307e2016-03-08 22:17:41 +0000525 if (BaseInit.isInvalid()) {
526 hadError = true;
527 return;
528 }
529
530 ILE->setInit(Init, BaseInit.getAs<Expr>());
531 } else if (InitListExpr *InnerILE =
532 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
Richard Smithf3b4ca82018-02-07 22:25:16 +0000533 FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
534 ILE, Init, FillWithNoInit);
Richard Smith872307e2016-03-08 22:17:41 +0000535 } else if (DesignatedInitUpdateExpr *InnerDIUE =
536 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
537 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
Richard Smithf3b4ca82018-02-07 22:25:16 +0000538 RequiresSecondPass, ILE, Init,
539 /*FillWithNoInit =*/true);
Richard Smith872307e2016-03-08 22:17:41 +0000540 }
541}
542
Richard Smith454a7cd2014-06-03 08:26:00 +0000543void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000544 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000545 InitListExpr *ILE,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000546 bool &RequiresSecondPass,
547 bool FillWithNoInit) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000548 SourceLocation Loc = ILE->getLocEnd();
Douglas Gregor2bb07652009-12-22 00:05:34 +0000549 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000550 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000551 = InitializedEntity::InitializeMember(Field, &ParentEntity);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000552
553 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
554 if (!RType->getDecl()->isUnion())
555 assert(Init < NumInits && "This ILE should have been expanded");
556
Douglas Gregor2bb07652009-12-22 00:05:34 +0000557 if (Init >= NumInits || !ILE->getInit(Init)) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000558 if (FillWithNoInit) {
559 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
560 if (Init < NumInits)
561 ILE->setInit(Init, Filler);
562 else
563 ILE->updateInit(SemaRef.Context, Init, Filler);
564 return;
565 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000566 // C++1y [dcl.init.aggr]p7:
567 // If there are fewer initializer-clauses in the list than there are
568 // members in the aggregate, then each member not explicitly initialized
569 // shall be initialized from its brace-or-equal-initializer [...]
Richard Smith852c9db2013-04-20 22:23:05 +0000570 if (Field->hasInClassInitializer()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000571 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
572 if (DIE.isInvalid()) {
573 hadError = true;
574 return;
575 }
Richard Smithd87aab92018-07-17 22:24:09 +0000576 SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000577 if (Init < NumInits)
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000578 ILE->setInit(Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000579 else {
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000580 ILE->updateInit(SemaRef.Context, Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000581 RequiresSecondPass = true;
582 }
583 return;
584 }
585
Douglas Gregor2bb07652009-12-22 00:05:34 +0000586 if (Field->getType()->isReferenceType()) {
587 // C++ [dcl.init.aggr]p9:
588 // If an incomplete or empty initializer-list leaves a
589 // member of reference type uninitialized, the program is
590 // ill-formed.
591 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
592 << Field->getType()
593 << ILE->getSyntacticForm()->getSourceRange();
594 SemaRef.Diag(Field->getLocation(),
595 diag::note_uninit_reference_member);
596 hadError = true;
597 return;
598 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000599
Richard Smith454a7cd2014-06-03 08:26:00 +0000600 ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
Manman Ren073db022016-03-10 18:53:19 +0000601 /*VerifyOnly*/false,
602 TreatUnavailableAsInvalid);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000603 if (MemberInit.isInvalid()) {
604 hadError = true;
605 return;
606 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000607
Douglas Gregor2bb07652009-12-22 00:05:34 +0000608 if (hadError) {
609 // Do nothing
610 } else if (Init < NumInits) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000611 ILE->setInit(Init, MemberInit.getAs<Expr>());
Richard Smith454a7cd2014-06-03 08:26:00 +0000612 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
613 // Empty initialization requires a constructor call, so
Douglas Gregor2bb07652009-12-22 00:05:34 +0000614 // extend the initializer list to include the constructor
615 // call and make a note that we'll need to take another pass
616 // through the initializer list.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000617 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000618 RequiresSecondPass = true;
619 }
620 } else if (InitListExpr *InnerILE
621 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Richard Smith454a7cd2014-06-03 08:26:00 +0000622 FillInEmptyInitializations(MemberEntity, InnerILE,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000623 RequiresSecondPass, ILE, Init, FillWithNoInit);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000624 else if (DesignatedInitUpdateExpr *InnerDIUE
625 = dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init)))
626 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
Richard Smithf3b4ca82018-02-07 22:25:16 +0000627 RequiresSecondPass, ILE, Init,
628 /*FillWithNoInit =*/true);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000629}
630
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000631/// Recursively replaces NULL values within the given initializer list
632/// with expressions that perform value-initialization of the
Richard Smithf3b4ca82018-02-07 22:25:16 +0000633/// appropriate type, and finish off the InitListExpr formation.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000634void
Richard Smith454a7cd2014-06-03 08:26:00 +0000635InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
Douglas Gregor723796a2009-12-16 06:35:08 +0000636 InitListExpr *ILE,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000637 bool &RequiresSecondPass,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000638 InitListExpr *OuterILE,
639 unsigned OuterIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000640 bool FillWithNoInit) {
Mike Stump11289f42009-09-09 15:08:12 +0000641 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000642 "Should not have void type");
Mike Stump11289f42009-09-09 15:08:12 +0000643
Richard Smithf3b4ca82018-02-07 22:25:16 +0000644 // If this is a nested initializer list, we might have changed its contents
645 // (and therefore some of its properties, such as instantiation-dependence)
646 // while filling it in. Inform the outer initializer list so that its state
647 // can be updated to match.
648 // FIXME: We should fully build the inner initializers before constructing
649 // the outer InitListExpr instead of mutating AST nodes after they have
650 // been used as subexpressions of other nodes.
651 struct UpdateOuterILEWithUpdatedInit {
652 InitListExpr *Outer;
653 unsigned OuterIndex;
654 ~UpdateOuterILEWithUpdatedInit() {
655 if (Outer)
656 Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
657 }
658 } UpdateOuterRAII = {OuterILE, OuterIndex};
659
Richard Smith382bc512017-02-23 22:41:47 +0000660 // A transparent ILE is not performing aggregate initialization and should
661 // not be filled in.
662 if (ILE->isTransparent())
663 return;
664
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000665 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000666 const RecordDecl *RDecl = RType->getDecl();
667 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Richard Smith454a7cd2014-06-03 08:26:00 +0000668 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
Yunzhong Gaocb779302015-06-10 00:27:52 +0000669 Entity, ILE, RequiresSecondPass, FillWithNoInit);
Richard Smith852c9db2013-04-20 22:23:05 +0000670 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
671 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000672 for (auto *Field : RDecl->fields()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000673 if (Field->hasInClassInitializer()) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000674 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
675 FillWithNoInit);
Richard Smith852c9db2013-04-20 22:23:05 +0000676 break;
677 }
678 }
679 } else {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000680 // The fields beyond ILE->getNumInits() are default initialized, so in
681 // order to leave them uninitialized, the ILE is expanded and the extra
682 // fields are then filled with NoInitExpr.
Richard Smith872307e2016-03-08 22:17:41 +0000683 unsigned NumElems = numStructUnionElements(ILE->getType());
684 if (RDecl->hasFlexibleArrayMember())
685 ++NumElems;
686 if (ILE->getNumInits() < NumElems)
687 ILE->resizeInits(SemaRef.Context, NumElems);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000688
Douglas Gregor2bb07652009-12-22 00:05:34 +0000689 unsigned Init = 0;
Richard Smith872307e2016-03-08 22:17:41 +0000690
691 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
692 for (auto &Base : CXXRD->bases()) {
693 if (hadError)
694 return;
695
696 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
697 FillWithNoInit);
698 ++Init;
699 }
700 }
701
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000702 for (auto *Field : RDecl->fields()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000703 if (Field->isUnnamedBitfield())
704 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000705
Douglas Gregor2bb07652009-12-22 00:05:34 +0000706 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000707 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000708
Yunzhong Gaocb779302015-06-10 00:27:52 +0000709 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
710 FillWithNoInit);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000711 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000712 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000713
Douglas Gregor2bb07652009-12-22 00:05:34 +0000714 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000715
Douglas Gregor2bb07652009-12-22 00:05:34 +0000716 // Only look at the first initialization of a union.
Richard Smith852c9db2013-04-20 22:23:05 +0000717 if (RDecl->isUnion())
Douglas Gregor2bb07652009-12-22 00:05:34 +0000718 break;
719 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000720 }
721
722 return;
Mike Stump11289f42009-09-09 15:08:12 +0000723 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000724
725 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000726
Douglas Gregor723796a2009-12-16 06:35:08 +0000727 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000728 unsigned NumInits = ILE->getNumInits();
729 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000730 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000731 ElementType = AType->getElementType();
Richard Smith0511d232016-10-05 22:41:02 +0000732 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000733 NumElements = CAType->getSize().getZExtValue();
Richard Smith0511d232016-10-05 22:41:02 +0000734 // For an array new with an unknown bound, ask for one additional element
735 // in order to populate the array filler.
736 if (Entity.isVariableLengthArrayNew())
737 ++NumElements;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000738 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000739 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000740 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000741 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000742 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000743 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000744 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000745 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000746 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000747
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000748 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000749 if (hadError)
750 return;
751
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000752 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
753 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000754 ElementEntity.setElementIndex(Init);
755
Richard Smith3e268632018-05-23 23:41:38 +0000756 if (Init >= NumInits && ILE->hasArrayFiller())
757 return;
758
Craig Topperc3ec1492014-05-26 06:22:03 +0000759 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000760 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
761 ILE->setInit(Init, ILE->getArrayFiller());
762 else if (!InitExpr && !ILE->hasArrayFiller()) {
763 Expr *Filler = nullptr;
764
765 if (FillWithNoInit)
766 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
767 else {
768 ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(),
769 ElementEntity,
Manman Ren073db022016-03-10 18:53:19 +0000770 /*VerifyOnly*/false,
771 TreatUnavailableAsInvalid);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000772 if (ElementInit.isInvalid()) {
773 hadError = true;
774 return;
775 }
776
777 Filler = ElementInit.getAs<Expr>();
Douglas Gregor723796a2009-12-16 06:35:08 +0000778 }
779
780 if (hadError) {
781 // Do nothing
782 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000783 // For arrays, just set the expression used for value-initialization
784 // of the "holes" in the array.
785 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
Yunzhong Gaocb779302015-06-10 00:27:52 +0000786 ILE->setArrayFiller(Filler);
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000787 else
Yunzhong Gaocb779302015-06-10 00:27:52 +0000788 ILE->setInit(Init, Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000789 } else {
790 // For arrays, just set the expression used for value-initialization
791 // of the rest of elements and exit.
792 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000793 ILE->setArrayFiller(Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000794 return;
795 }
796
Yunzhong Gaocb779302015-06-10 00:27:52 +0000797 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000798 // Empty initialization requires a constructor call, so
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000799 // extend the initializer list to include the constructor
800 // call and make a note that we'll need to take another pass
801 // through the initializer list.
Yunzhong Gaocb779302015-06-10 00:27:52 +0000802 ILE->updateInit(SemaRef.Context, Init, Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000803 RequiresSecondPass = true;
804 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000805 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000806 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000807 = dyn_cast_or_null<InitListExpr>(InitExpr))
Yunzhong Gaocb779302015-06-10 00:27:52 +0000808 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000809 ILE, Init, FillWithNoInit);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000810 else if (DesignatedInitUpdateExpr *InnerDIUE
811 = dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr))
812 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
Richard Smithf3b4ca82018-02-07 22:25:16 +0000813 RequiresSecondPass, ILE, Init,
814 /*FillWithNoInit =*/true);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000815 }
816}
817
Douglas Gregor723796a2009-12-16 06:35:08 +0000818InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000819 InitListExpr *IL, QualType &T,
Manman Ren073db022016-03-10 18:53:19 +0000820 bool VerifyOnly,
821 bool TreatUnavailableAsInvalid)
822 : SemaRef(S), VerifyOnly(VerifyOnly),
823 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid) {
Richard Smith520449d2015-02-05 06:15:50 +0000824 // FIXME: Check that IL isn't already the semantic form of some other
825 // InitListExpr. If it is, we'd create a broken AST.
826
Steve Narofff8ecff22008-05-01 22:18:59 +0000827 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000828
Richard Smith4e0d2e42013-09-20 20:10:22 +0000829 FullyStructuredList =
Craig Topperc3ec1492014-05-26 06:22:03 +0000830 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000831 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000832 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000833
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000834 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000835 bool RequiresSecondPass = false;
Richard Smithf3b4ca82018-02-07 22:25:16 +0000836 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
837 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000838 if (RequiresSecondPass && !hadError)
Richard Smith454a7cd2014-06-03 08:26:00 +0000839 FillInEmptyInitializations(Entity, FullyStructuredList,
Richard Smithf3b4ca82018-02-07 22:25:16 +0000840 RequiresSecondPass, nullptr, 0);
Douglas Gregor723796a2009-12-16 06:35:08 +0000841 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000842}
843
844int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000845 // FIXME: use a proper constant
846 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000847 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000848 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000849 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
850 }
851 return maxElements;
852}
853
854int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000855 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000856 int InitializableMembers = 0;
Richard Smith872307e2016-03-08 22:17:41 +0000857 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
858 InitializableMembers += CXXRD->getNumBases();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000859 for (const auto *Field : structDecl->fields())
Douglas Gregor556e5862011-10-10 17:22:13 +0000860 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000861 ++InitializableMembers;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000862
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000863 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000864 return std::min(InitializableMembers, 1);
865 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000866}
867
Richard Smith283e2072017-10-03 20:36:00 +0000868/// Determine whether Entity is an entity for which it is idiomatic to elide
869/// the braces in aggregate initialization.
870static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
871 // Recursive initialization of the one and only field within an aggregate
872 // class is considered idiomatic. This case arises in particular for
873 // initialization of std::array, where the C++ standard suggests the idiom of
874 //
875 // std::array<T, N> arr = {1, 2, 3};
876 //
877 // (where std::array is an aggregate struct containing a single array field.
878
879 // FIXME: Should aggregate initialization of a struct with a single
880 // base class and no members also suppress the warning?
881 if (Entity.getKind() != InitializedEntity::EK_Member || !Entity.getParent())
882 return false;
883
884 auto *ParentRD =
885 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
886 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD))
887 if (CXXRD->getNumBases())
888 return false;
889
890 auto FieldIt = ParentRD->field_begin();
891 assert(FieldIt != ParentRD->field_end() &&
892 "no fields but have initializer for member?");
893 return ++FieldIt == ParentRD->field_end();
894}
895
Richard Smith4e0d2e42013-09-20 20:10:22 +0000896/// Check whether the range of the initializer \p ParentIList from element
897/// \p Index onwards can be used to initialize an object of type \p T. Update
898/// \p Index to indicate how many elements of the list were consumed.
899///
900/// This also fills in \p StructuredList, from element \p StructuredIndex
901/// onwards, with the fully-braced, desugared form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000902void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000903 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000904 QualType T, unsigned &Index,
905 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000906 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000907 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000908
Steve Narofff8ecff22008-05-01 22:18:59 +0000909 if (T->isArrayType())
910 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000911 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000912 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000913 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000914 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000915 else
David Blaikie83d382b2011-09-23 05:06:16 +0000916 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000917
Eli Friedmane0f832b2008-05-25 13:49:22 +0000918 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000919 if (!VerifyOnly)
920 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
921 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000922 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000923 hadError = true;
924 return;
925 }
926
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000927 // Build a structured initializer list corresponding to this subobject.
928 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000929 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
930 StructuredIndex,
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000931 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregor5741efb2009-03-01 17:12:46 +0000932 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000933 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000934
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000935 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000936 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000937 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000938 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000939 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000940 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000941
Richard Smithde229232013-06-06 11:41:05 +0000942 if (!VerifyOnly) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000943 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000944
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000945 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000946 // Update the structured sub-object initializer so that it's ending
947 // range corresponds with the end of the last initializer it used.
Reid Kleckner4a09e882015-12-09 23:18:38 +0000948 if (EndIndex < ParentIList->getNumInits() &&
949 ParentIList->getInit(EndIndex)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000950 SourceLocation EndLoc
951 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
952 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
953 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000954
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000955 // Complain about missing braces.
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +0000956 if ((T->isArrayType() || T->isRecordType()) &&
Richard Smith283e2072017-10-03 20:36:00 +0000957 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
958 !isIdiomaticBraceElisionEntity(Entity)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000959 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Richard Smithde229232013-06-06 11:41:05 +0000960 diag::warn_missing_braces)
Alp Tokerb6cc5922014-05-03 03:45:55 +0000961 << StructuredSubobjectInitList->getSourceRange()
962 << FixItHint::CreateInsertion(
963 StructuredSubobjectInitList->getLocStart(), "{")
964 << FixItHint::CreateInsertion(
965 SemaRef.getLocForEndOfToken(
966 StructuredSubobjectInitList->getLocEnd()),
967 "}");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000968 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000969 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000970}
971
Richard Smith420fa122015-02-12 01:50:05 +0000972/// Warn that \p Entity was of scalar type and was initialized by a
973/// single-element braced initializer list.
974static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
975 SourceRange Braces) {
976 // Don't warn during template instantiation. If the initialization was
977 // non-dependent, we warned during the initial parse; otherwise, the
978 // type might not be scalar in some uses of the template.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000979 if (S.inTemplateInstantiation())
Richard Smith420fa122015-02-12 01:50:05 +0000980 return;
981
982 unsigned DiagID = 0;
983
984 switch (Entity.getKind()) {
985 case InitializedEntity::EK_VectorElement:
986 case InitializedEntity::EK_ComplexElement:
987 case InitializedEntity::EK_ArrayElement:
988 case InitializedEntity::EK_Parameter:
989 case InitializedEntity::EK_Parameter_CF_Audited:
990 case InitializedEntity::EK_Result:
991 // Extra braces here are suspicious.
992 DiagID = diag::warn_braces_around_scalar_init;
993 break;
994
995 case InitializedEntity::EK_Member:
996 // Warn on aggregate initialization but not on ctor init list or
997 // default member initializer.
998 if (Entity.getParent())
999 DiagID = diag::warn_braces_around_scalar_init;
1000 break;
1001
1002 case InitializedEntity::EK_Variable:
1003 case InitializedEntity::EK_LambdaCapture:
1004 // No warning, might be direct-list-initialization.
1005 // FIXME: Should we warn for copy-list-initialization in these cases?
1006 break;
1007
1008 case InitializedEntity::EK_New:
1009 case InitializedEntity::EK_Temporary:
1010 case InitializedEntity::EK_CompoundLiteralInit:
1011 // No warning, braces are part of the syntax of the underlying construct.
1012 break;
1013
1014 case InitializedEntity::EK_RelatedResult:
1015 // No warning, we already warned when initializing the result.
1016 break;
1017
1018 case InitializedEntity::EK_Exception:
1019 case InitializedEntity::EK_Base:
1020 case InitializedEntity::EK_Delegating:
1021 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00001022 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Richard Smith7873de02016-08-11 22:25:46 +00001023 case InitializedEntity::EK_Binding:
Richard Smith67af95b2018-07-23 19:19:08 +00001024 case InitializedEntity::EK_StmtExprResult:
Richard Smith420fa122015-02-12 01:50:05 +00001025 llvm_unreachable("unexpected braced scalar init");
1026 }
1027
1028 if (DiagID) {
1029 S.Diag(Braces.getBegin(), DiagID)
1030 << Braces
1031 << FixItHint::CreateRemoval(Braces.getBegin())
1032 << FixItHint::CreateRemoval(Braces.getEnd());
1033 }
1034}
1035
Richard Smith4e0d2e42013-09-20 20:10:22 +00001036/// Check whether the initializer \p IList (that was written with explicit
1037/// braces) can be used to initialize an object of type \p T.
1038///
1039/// This also fills in \p StructuredList with the fully-braced, desugared
1040/// form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +00001041void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001042 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001043 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001044 bool TopLevelObject) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001045 if (!VerifyOnly) {
1046 SyntacticToSemantic[IList] = StructuredList;
1047 StructuredList->setSyntacticForm(IList);
1048 }
Richard Smith4e0d2e42013-09-20 20:10:22 +00001049
1050 unsigned Index = 0, StructuredIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001051 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +00001052 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001053 if (!VerifyOnly) {
Eli Friedman91f5ae52012-02-23 02:25:10 +00001054 QualType ExprTy = T;
1055 if (!ExprTy->isArrayType())
1056 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001057 IList->setType(ExprTy);
1058 StructuredList->setType(ExprTy);
1059 }
Eli Friedman85f54972008-05-25 13:22:35 +00001060 if (hadError)
1061 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001062
Eli Friedman85f54972008-05-25 13:22:35 +00001063 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001064 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001065 if (VerifyOnly) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001066 if (SemaRef.getLangOpts().CPlusPlus ||
1067 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001068 IList->getType()->isVectorType())) {
1069 hadError = true;
1070 }
1071 return;
1072 }
1073
Eli Friedmanbd327452009-05-29 20:20:05 +00001074 if (StructuredIndex == 1 &&
Hans Wennborg950f3182013-05-16 09:22:40 +00001075 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1076 SIF_None) {
Richard Smith1b98ccc2014-07-19 01:39:17 +00001077 unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001078 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001079 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +00001080 hadError = true;
1081 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001082 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +00001083 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +00001084 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +00001085 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +00001086 // Don't complain for incomplete types, since we'll get an error
1087 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001088 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001089 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001090 CurrentObjectType->isArrayType()? 0 :
1091 CurrentObjectType->isVectorType()? 1 :
1092 CurrentObjectType->isScalarType()? 2 :
1093 CurrentObjectType->isUnionType()? 3 :
1094 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001095
Richard Smith1b98ccc2014-07-19 01:39:17 +00001096 unsigned DK = diag::ext_excess_initializers;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001097 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanbd327452009-05-29 20:20:05 +00001098 DK = diag::err_excess_initializers;
1099 hadError = true;
1100 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00001101 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman425038c2009-07-07 21:53:06 +00001102 DK = diag::err_excess_initializers;
1103 hadError = true;
1104 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +00001105
Chris Lattnerb0912a52009-02-24 22:50:46 +00001106 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001107 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001108 }
1109 }
Eli Friedman6fcdec22008-05-19 20:20:43 +00001110
Richard Smith420fa122015-02-12 01:50:05 +00001111 if (!VerifyOnly && T->isScalarType() &&
1112 IList->getNumInits() == 1 && !isa<InitListExpr>(IList->getInit(0)))
1113 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
Steve Narofff8ecff22008-05-01 22:18:59 +00001114}
1115
Anders Carlsson6cabf312010-01-23 23:23:01 +00001116void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001117 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001118 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001119 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001120 unsigned &Index,
1121 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001122 unsigned &StructuredIndex,
1123 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001124 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1125 // Explicitly braced initializer for complex type can be real+imaginary
1126 // parts.
1127 CheckComplexType(Entity, IList, DeclType, Index,
1128 StructuredList, StructuredIndex);
1129 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +00001130 CheckScalarType(Entity, IList, DeclType, Index,
1131 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001132 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001133 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +00001134 StructuredList, StructuredIndex);
Richard Smithe20c83d2012-07-07 08:35:56 +00001135 } else if (DeclType->isRecordType()) {
1136 assert(DeclType->isAggregateType() &&
1137 "non-aggregate records should be handed in CheckSubElementType");
1138 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith872307e2016-03-08 22:17:41 +00001139 auto Bases =
1140 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
1141 CXXRecordDecl::base_class_iterator());
1142 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1143 Bases = CXXRD->bases();
1144 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1145 SubobjectIsDesignatorContext, Index, StructuredList,
1146 StructuredIndex, TopLevelObject);
Richard Smithe20c83d2012-07-07 08:35:56 +00001147 } else if (DeclType->isArrayType()) {
1148 llvm::APSInt Zero(
1149 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1150 false);
1151 CheckArrayType(Entity, IList, DeclType, Zero,
1152 SubobjectIsDesignatorContext, Index,
1153 StructuredList, StructuredIndex);
Steve Naroffeaf58532008-08-10 16:05:48 +00001154 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1155 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001156 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001157 if (!VerifyOnly)
1158 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1159 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +00001160 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +00001161 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +00001162 CheckReferenceType(Entity, IList, DeclType, Index,
1163 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +00001164 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001165 if (!VerifyOnly)
1166 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
1167 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +00001168 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +00001169 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001170 if (!VerifyOnly)
1171 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1172 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +00001173 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +00001174 }
1175}
1176
Anders Carlsson6cabf312010-01-23 23:23:01 +00001177void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001178 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001179 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001180 unsigned &Index,
1181 InitListExpr *StructuredList,
1182 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +00001183 Expr *expr = IList->getInit(Index);
Richard Smith72752e82013-05-31 02:56:17 +00001184
1185 if (ElemType->isReferenceType())
1186 return CheckReferenceType(Entity, IList, ElemType, Index,
1187 StructuredList, StructuredIndex);
1188
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001189 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Yunzhong Gaocb779302015-06-10 00:27:52 +00001190 if (SubInitList->getNumInits() == 1 &&
1191 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1192 SIF_None) {
1193 expr = SubInitList->getInit(0);
1194 } else if (!SemaRef.getLangOpts().CPlusPlus) {
Richard Smith4e0d2e42013-09-20 20:10:22 +00001195 InitListExpr *InnerStructuredList
Richard Smithe20c83d2012-07-07 08:35:56 +00001196 = getStructuredSubobjectInit(IList, Index, ElemType,
1197 StructuredList, StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +00001198 SubInitList->getSourceRange(), true);
Richard Smith4e0d2e42013-09-20 20:10:22 +00001199 CheckExplicitInitList(Entity, SubInitList, ElemType,
1200 InnerStructuredList);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001201
1202 if (!hadError && !VerifyOnly) {
1203 bool RequiresSecondPass = false;
1204 FillInEmptyInitializations(Entity, InnerStructuredList,
Richard Smithf3b4ca82018-02-07 22:25:16 +00001205 RequiresSecondPass, StructuredList,
1206 StructuredIndex);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001207 if (RequiresSecondPass && !hadError)
1208 FillInEmptyInitializations(Entity, InnerStructuredList,
Richard Smithf3b4ca82018-02-07 22:25:16 +00001209 RequiresSecondPass, StructuredList,
1210 StructuredIndex);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001211 }
Richard Smithe20c83d2012-07-07 08:35:56 +00001212 ++StructuredIndex;
1213 ++Index;
1214 return;
1215 }
Richard Smithe20c83d2012-07-07 08:35:56 +00001216 // C++ initialization is handled later.
Richard Smithc4158e862014-07-18 04:47:25 +00001217 } else if (isa<ImplicitValueInitExpr>(expr)) {
Richard Smith8aa561b2014-07-17 23:12:06 +00001218 // This happens during template instantiation when we see an InitListExpr
1219 // that we've already checked once.
Richard Smithc4158e862014-07-18 04:47:25 +00001220 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
Richard Smith8aa561b2014-07-17 23:12:06 +00001221 "found implicit initialization for the wrong type");
1222 if (!VerifyOnly)
1223 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1224 ++Index;
1225 return;
Richard Smithe20c83d2012-07-07 08:35:56 +00001226 }
1227
Richard Smith3c567fc2015-02-12 01:55:09 +00001228 if (SemaRef.getLangOpts().CPlusPlus) {
1229 // C++ [dcl.init.aggr]p2:
1230 // Each member is copy-initialized from the corresponding
1231 // initializer-clause.
1232
1233 // FIXME: Better EqualLoc?
1234 InitializationKind Kind =
1235 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
1236 InitializationSequence Seq(SemaRef, Entity, Kind, expr,
1237 /*TopLevelOfInitList*/ true);
1238
1239 // C++14 [dcl.init.aggr]p13:
1240 // If the assignment-expression can initialize a member, the member is
1241 // initialized. Otherwise [...] brace elision is assumed
1242 //
1243 // Brace elision is never performed if the element is not an
1244 // assignment-expression.
1245 if (Seq || isa<InitListExpr>(expr)) {
1246 if (!VerifyOnly) {
1247 ExprResult Result =
1248 Seq.Perform(SemaRef, Entity, Kind, expr);
1249 if (Result.isInvalid())
1250 hadError = true;
1251
1252 UpdateStructuredListElement(StructuredList, StructuredIndex,
1253 Result.getAs<Expr>());
Richard Smith40574cc2015-02-16 04:42:59 +00001254 } else if (!Seq)
1255 hadError = true;
Richard Smith3c567fc2015-02-12 01:55:09 +00001256 ++Index;
1257 return;
1258 }
1259
1260 // Fall through for subaggregate initialization
1261 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1262 // FIXME: Need to handle atomic aggregate types with implicit init lists.
John McCall5decec92011-02-21 07:57:55 +00001263 return CheckScalarType(Entity, IList, ElemType, Index,
1264 StructuredList, StructuredIndex);
Richard Smith3c567fc2015-02-12 01:55:09 +00001265 } else if (const ArrayType *arrayType =
1266 SemaRef.Context.getAsArrayType(ElemType)) {
John McCall5decec92011-02-21 07:57:55 +00001267 // arrayType can be incomplete if we're initializing a flexible
1268 // array member. There's nothing we can do with the completed
1269 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001270
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001271 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedmand8d7a372011-09-26 19:09:09 +00001272 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001273 CheckStringInit(expr, ElemType, arrayType, SemaRef);
1274 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedmand8d7a372011-09-26 19:09:09 +00001275 }
Douglas Gregord14247a2009-01-30 22:09:00 +00001276 ++Index;
John McCall5decec92011-02-21 07:57:55 +00001277 return;
Douglas Gregord14247a2009-01-30 22:09:00 +00001278 }
John McCall5decec92011-02-21 07:57:55 +00001279
1280 // Fall through for subaggregate initialization.
1281
John McCall5decec92011-02-21 07:57:55 +00001282 } else {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001283 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
Egor Churaev45fe70f2017-05-10 10:28:34 +00001284 ElemType->isOpenCLSpecificType()) && "Unexpected type");
Richard Smith3c567fc2015-02-12 01:55:09 +00001285
John McCall5decec92011-02-21 07:57:55 +00001286 // C99 6.7.8p13:
1287 //
1288 // The initializer for a structure or union object that has
1289 // automatic storage duration shall be either an initializer
1290 // list as described below, or a single expression that has
1291 // compatible structure or union type. In the latter case, the
1292 // initial value of the object, including unnamed members, is
1293 // that of the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001294 ExprResult ExprRes = expr;
Richard Smith3c567fc2015-02-12 01:55:09 +00001295 if (SemaRef.CheckSingleAssignmentConstraints(
1296 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
John Wiegley01296292011-04-08 18:41:53 +00001297 if (ExprRes.isInvalid())
1298 hadError = true;
1299 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001300 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001301 if (ExprRes.isInvalid())
1302 hadError = true;
John Wiegley01296292011-04-08 18:41:53 +00001303 }
1304 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001305 ExprRes.getAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +00001306 ++Index;
1307 return;
1308 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001309 ExprRes.get();
John McCall5decec92011-02-21 07:57:55 +00001310 // Fall through for subaggregate initialization
1311 }
1312
1313 // C++ [dcl.init.aggr]p12:
1314 //
1315 // [...] Otherwise, if the member is itself a non-empty
1316 // subaggregate, brace elision is assumed and the initializer is
1317 // considered for the initialization of the first member of
1318 // the subaggregate.
Yaxun Liua91da4b2016-10-11 15:53:28 +00001319 // OpenCL vector initializer is handled elsewhere.
1320 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1321 ElemType->isAggregateType()) {
John McCall5decec92011-02-21 07:57:55 +00001322 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1323 StructuredIndex);
1324 ++StructuredIndex;
1325 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001326 if (!VerifyOnly) {
1327 // We cannot initialize this element, so let
1328 // PerformCopyInitialization produce the appropriate diagnostic.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001329 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001330 /*TopLevelOfInitList=*/true);
1331 }
John McCall5decec92011-02-21 07:57:55 +00001332 hadError = true;
1333 ++Index;
1334 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +00001335 }
Eli Friedman23a9e312008-05-19 19:16:24 +00001336}
1337
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001338void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1339 InitListExpr *IList, QualType DeclType,
1340 unsigned &Index,
1341 InitListExpr *StructuredList,
1342 unsigned &StructuredIndex) {
1343 assert(Index == 0 && "Index in explicit init list must be zero");
1344
1345 // As an extension, clang supports complex initializers, which initialize
1346 // a complex number component-wise. When an explicit initializer list for
1347 // a complex number contains two two initializers, this extension kicks in:
1348 // it exepcts the initializer list to contain two elements convertible to
1349 // the element type of the complex type. The first element initializes
1350 // the real part, and the second element intitializes the imaginary part.
1351
1352 if (IList->getNumInits() != 2)
1353 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1354 StructuredIndex);
1355
1356 // This is an extension in C. (The builtin _Complex type does not exist
1357 // in the C++ standard.)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001358 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001359 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
1360 << IList->getSourceRange();
1361
1362 // Initialize the complex number.
1363 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1364 InitializedEntity ElementEntity =
1365 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1366
1367 for (unsigned i = 0; i < 2; ++i) {
1368 ElementEntity.setElementIndex(Index);
1369 CheckSubElementType(ElementEntity, IList, elementType, Index,
1370 StructuredList, StructuredIndex);
1371 }
1372}
1373
Anders Carlsson6cabf312010-01-23 23:23:01 +00001374void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001375 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +00001376 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001377 InitListExpr *StructuredList,
1378 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +00001379 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +00001380 if (!VerifyOnly)
1381 SemaRef.Diag(IList->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001382 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smithc8239732011-10-18 21:39:00 +00001383 diag::warn_cxx98_compat_empty_scalar_initializer :
1384 diag::err_empty_scalar_initializer)
1385 << IList->getSourceRange();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001386 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001387 ++Index;
1388 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001389 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001390 }
John McCall643169b2010-11-11 00:46:36 +00001391
1392 Expr *expr = IList->getInit(Index);
1393 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Richard Smithfe9d2c02013-11-19 03:41:32 +00001394 // FIXME: This is invalid, and accepting it causes overload resolution
1395 // to pick the wrong overload in some corner cases.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001396 if (!VerifyOnly)
1397 SemaRef.Diag(SubIList->getLocStart(),
Richard Smithfe9d2c02013-11-19 03:41:32 +00001398 diag::ext_many_braces_around_scalar_init)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001399 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001400
1401 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1402 StructuredIndex);
1403 return;
1404 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001405 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001406 SemaRef.Diag(expr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001407 diag::err_designator_for_scalar_init)
1408 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001409 hadError = true;
1410 ++Index;
1411 ++StructuredIndex;
1412 return;
1413 }
1414
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001415 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001416 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001417 hadError = true;
1418 ++Index;
1419 return;
1420 }
1421
John McCall643169b2010-11-11 00:46:36 +00001422 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001423 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001424 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +00001425
Craig Topperc3ec1492014-05-26 06:22:03 +00001426 Expr *ResultExpr = nullptr;
John McCall643169b2010-11-11 00:46:36 +00001427
1428 if (Result.isInvalid())
1429 hadError = true; // types weren't compatible.
1430 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001431 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001432
John McCall643169b2010-11-11 00:46:36 +00001433 if (ResultExpr != expr) {
1434 // The type was promoted, update initializer list.
1435 IList->setInit(Index, ResultExpr);
1436 }
1437 }
1438 if (hadError)
1439 ++StructuredIndex;
1440 else
1441 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1442 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001443}
1444
Anders Carlsson6cabf312010-01-23 23:23:01 +00001445void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1446 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +00001447 unsigned &Index,
1448 InitListExpr *StructuredList,
1449 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001450 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001451 // FIXME: It would be wonderful if we could point at the actual member. In
1452 // general, it would be useful to pass location information down the stack,
1453 // so that we know the location (or decl) of the "current object" being
1454 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001455 if (!VerifyOnly)
1456 SemaRef.Diag(IList->getLocStart(),
1457 diag::err_init_reference_member_uninitialized)
1458 << DeclType
1459 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +00001460 hadError = true;
1461 ++Index;
1462 ++StructuredIndex;
1463 return;
1464 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001465
1466 Expr *expr = IList->getInit(Index);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001467 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001468 if (!VerifyOnly)
1469 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1470 << DeclType << IList->getSourceRange();
1471 hadError = true;
1472 ++Index;
1473 ++StructuredIndex;
1474 return;
1475 }
1476
1477 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001478 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001479 hadError = true;
1480 ++Index;
1481 return;
1482 }
1483
1484 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001485 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1486 /*TopLevelOfInitList=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001487
1488 if (Result.isInvalid())
1489 hadError = true;
1490
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001491 expr = Result.getAs<Expr>();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001492 IList->setInit(Index, expr);
1493
1494 if (hadError)
1495 ++StructuredIndex;
1496 else
1497 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1498 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001499}
1500
Anders Carlsson6cabf312010-01-23 23:23:01 +00001501void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001502 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001503 unsigned &Index,
1504 InitListExpr *StructuredList,
1505 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001506 const VectorType *VT = DeclType->getAs<VectorType>();
1507 unsigned maxElements = VT->getNumElements();
1508 unsigned numEltsInit = 0;
1509 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001510
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001511 if (Index >= IList->getNumInits()) {
1512 // Make sure the element type can be value-initialized.
1513 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001514 CheckEmptyInitializable(
1515 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1516 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001517 return;
1518 }
1519
David Blaikiebbafb8a2012-03-11 07:00:24 +00001520 if (!SemaRef.getLangOpts().OpenCL) {
John McCall6a16b2f2010-10-30 00:11:39 +00001521 // If the initializing element is a vector, try to copy-initialize
1522 // instead of breaking it apart (which is doomed to failure anyway).
1523 Expr *Init = IList->getInit(Index);
1524 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001525 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001526 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001527 hadError = true;
1528 ++Index;
1529 return;
1530 }
1531
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001532 ExprResult Result =
1533 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
1534 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001535
Craig Topperc3ec1492014-05-26 06:22:03 +00001536 Expr *ResultExpr = nullptr;
John McCall6a16b2f2010-10-30 00:11:39 +00001537 if (Result.isInvalid())
1538 hadError = true; // types weren't compatible.
1539 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001540 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001541
John McCall6a16b2f2010-10-30 00:11:39 +00001542 if (ResultExpr != Init) {
1543 // The type was promoted, update initializer list.
1544 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001545 }
1546 }
John McCall6a16b2f2010-10-30 00:11:39 +00001547 if (hadError)
1548 ++StructuredIndex;
1549 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001550 UpdateStructuredListElement(StructuredList, StructuredIndex,
1551 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001552 ++Index;
1553 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001554 }
Mike Stump11289f42009-09-09 15:08:12 +00001555
John McCall6a16b2f2010-10-30 00:11:39 +00001556 InitializedEntity ElementEntity =
1557 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001558
John McCall6a16b2f2010-10-30 00:11:39 +00001559 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1560 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001561 if (Index >= IList->getNumInits()) {
1562 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001563 CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
John McCall6a16b2f2010-10-30 00:11:39 +00001564 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001565 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001566
John McCall6a16b2f2010-10-30 00:11:39 +00001567 ElementEntity.setElementIndex(Index);
1568 CheckSubElementType(ElementEntity, IList, elementType, Index,
1569 StructuredList, StructuredIndex);
1570 }
James Molloy9eef2652014-06-20 14:35:13 +00001571
1572 if (VerifyOnly)
1573 return;
1574
1575 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1576 const VectorType *T = Entity.getType()->getAs<VectorType>();
1577 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1578 T->getVectorKind() == VectorType::NeonPolyVector)) {
1579 // The ability to use vector initializer lists is a GNU vector extension
1580 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1581 // endian machines it works fine, however on big endian machines it
1582 // exhibits surprising behaviour:
1583 //
1584 // uint32x2_t x = {42, 64};
1585 // return vget_lane_u32(x, 0); // Will return 64.
1586 //
1587 // Because of this, explicitly call out that it is non-portable.
1588 //
1589 SemaRef.Diag(IList->getLocStart(),
1590 diag::warn_neon_vector_initializer_non_portable);
1591
1592 const char *typeCode;
1593 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1594
1595 if (elementType->isFloatingType())
1596 typeCode = "f";
1597 else if (elementType->isSignedIntegerType())
1598 typeCode = "s";
1599 else if (elementType->isUnsignedIntegerType())
1600 typeCode = "u";
1601 else
1602 llvm_unreachable("Invalid element type!");
1603
1604 SemaRef.Diag(IList->getLocStart(),
1605 SemaRef.Context.getTypeSize(VT) > 64 ?
1606 diag::note_neon_vector_initializer_non_portable_q :
1607 diag::note_neon_vector_initializer_non_portable)
1608 << typeCode << typeSize;
1609 }
1610
John McCall6a16b2f2010-10-30 00:11:39 +00001611 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001612 }
John McCall6a16b2f2010-10-30 00:11:39 +00001613
1614 InitializedEntity ElementEntity =
1615 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001616
John McCall6a16b2f2010-10-30 00:11:39 +00001617 // OpenCL initializers allows vectors to be constructed from vectors.
1618 for (unsigned i = 0; i < maxElements; ++i) {
1619 // Don't attempt to go past the end of the init list
1620 if (Index >= IList->getNumInits())
1621 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001622
John McCall6a16b2f2010-10-30 00:11:39 +00001623 ElementEntity.setElementIndex(Index);
1624
1625 QualType IType = IList->getInit(Index)->getType();
1626 if (!IType->isVectorType()) {
1627 CheckSubElementType(ElementEntity, IList, elementType, Index,
1628 StructuredList, StructuredIndex);
1629 ++numEltsInit;
1630 } else {
1631 QualType VecType;
1632 const VectorType *IVT = IType->getAs<VectorType>();
1633 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001634
John McCall6a16b2f2010-10-30 00:11:39 +00001635 if (IType->isExtVectorType())
1636 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1637 else
1638 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001639 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001640 CheckSubElementType(ElementEntity, IList, VecType, Index,
1641 StructuredList, StructuredIndex);
1642 numEltsInit += numIElts;
1643 }
1644 }
1645
1646 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001647 if (numEltsInit != maxElements) {
1648 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001649 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001650 diag::err_vector_incorrect_num_initializers)
1651 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1652 hadError = true;
1653 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001654}
1655
Anders Carlsson6cabf312010-01-23 23:23:01 +00001656void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001657 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001658 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001659 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001660 unsigned &Index,
1661 InitListExpr *StructuredList,
1662 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001663 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1664
Steve Narofff8ecff22008-05-01 22:18:59 +00001665 // Check for the special-case of initializing an array with a string.
1666 if (Index < IList->getNumInits()) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001667 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1668 SIF_None) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001669 // We place the string literal directly into the resulting
1670 // initializer list. This is the only place where the structure
1671 // of the structured initializer list doesn't match exactly,
1672 // because doing so would involve allocating one character
1673 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001674 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001675 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1676 UpdateStructuredListElement(StructuredList, StructuredIndex,
1677 IList->getInit(Index));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001678 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1679 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001680 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001681 return;
1682 }
1683 }
John McCall66884dd2011-02-21 07:22:22 +00001684 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001685 // Check for VLAs; in standard C it would be possible to check this
1686 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1687 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001688 if (!VerifyOnly)
1689 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1690 diag::err_variable_object_no_init)
1691 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001692 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001693 ++Index;
1694 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001695 return;
1696 }
1697
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001698 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001699 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1700 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001701 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001702 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001703 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001704 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001705 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001706 maxElementsKnown = true;
1707 }
1708
John McCall66884dd2011-02-21 07:22:22 +00001709 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001710 while (Index < IList->getNumInits()) {
1711 Expr *Init = IList->getInit(Index);
1712 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001713 // If we're not the subobject that matches up with the '{' for
1714 // the designator, we shouldn't be handling the
1715 // designator. Return immediately.
1716 if (!SubobjectIsDesignatorContext)
1717 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001718
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001719 // Handle this designated initializer. elementIndex will be
1720 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001721 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001722 DeclType, nullptr, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001723 StructuredList, StructuredIndex, true,
1724 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001725 hadError = true;
1726 continue;
1727 }
1728
Douglas Gregor033d1252009-01-23 16:54:12 +00001729 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001730 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001731 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001732 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001733 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001734
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001735 // If the array is of incomplete type, keep track of the number of
1736 // elements in the initializer.
1737 if (!maxElementsKnown && elementIndex > maxElements)
1738 maxElements = elementIndex;
1739
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001740 continue;
1741 }
1742
1743 // If we know the maximum number of elements, and we've already
1744 // hit it, stop consuming elements in the initializer list.
1745 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001746 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001747
Anders Carlsson6cabf312010-01-23 23:23:01 +00001748 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001749 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001750 Entity);
1751 // Check this element.
1752 CheckSubElementType(ElementEntity, IList, elementType, Index,
1753 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001754 ++elementIndex;
1755
1756 // If the array is of incomplete type, keep track of the number of
1757 // elements in the initializer.
1758 if (!maxElementsKnown && elementIndex > maxElements)
1759 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001760 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001761 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001762 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001763 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001764 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Richard Smith73edb6d2017-01-24 23:18:28 +00001765 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001766 // Sizing an array implicitly to zero is not allowed by ISO C,
1767 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001768 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001769 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001770 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001771
Mike Stump11289f42009-09-09 15:08:12 +00001772 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001773 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001774 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001775 if (!hadError && VerifyOnly) {
Richard Smith0511d232016-10-05 22:41:02 +00001776 // If there are any members of the array that get value-initialized, check
1777 // that is possible. That happens if we know the bound and don't have
1778 // enough elements, or if we're performing an array new with an unknown
1779 // bound.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001780 // FIXME: This needs to detect holes left by designated initializers too.
Richard Smith0511d232016-10-05 22:41:02 +00001781 if ((maxElementsKnown && elementIndex < maxElements) ||
1782 Entity.isVariableLengthArrayNew())
Richard Smith454a7cd2014-06-03 08:26:00 +00001783 CheckEmptyInitializable(InitializedEntity::InitializeElement(
1784 SemaRef.Context, 0, Entity),
1785 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001786 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001787}
1788
Eli Friedman3fa64df2011-08-23 22:24:57 +00001789bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1790 Expr *InitExpr,
1791 FieldDecl *Field,
1792 bool TopLevelObject) {
1793 // Handle GNU flexible array initializers.
1794 unsigned FlexArrayDiag;
1795 if (isa<InitListExpr>(InitExpr) &&
1796 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1797 // Empty flexible array init always allowed as an extension
1798 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001799 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedman3fa64df2011-08-23 22:24:57 +00001800 // Disallow flexible array init in C++; it is not required for gcc
1801 // compatibility, and it needs work to IRGen correctly in general.
1802 FlexArrayDiag = diag::err_flexible_array_init;
1803 } else if (!TopLevelObject) {
1804 // Disallow flexible array init on non-top-level object
1805 FlexArrayDiag = diag::err_flexible_array_init;
1806 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1807 // Disallow flexible array init on anything which is not a variable.
1808 FlexArrayDiag = diag::err_flexible_array_init;
1809 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1810 // Disallow flexible array init on local variables.
1811 FlexArrayDiag = diag::err_flexible_array_init;
1812 } else {
1813 // Allow other cases.
1814 FlexArrayDiag = diag::ext_flexible_array_init;
1815 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001816
1817 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001818 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001819 FlexArrayDiag)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001820 << InitExpr->getLocStart();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001821 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1822 << Field;
1823 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001824
1825 return FlexArrayDiag != diag::ext_flexible_array_init;
1826}
1827
Richard Smith872307e2016-03-08 22:17:41 +00001828void InitListChecker::CheckStructUnionTypes(
1829 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
1830 CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field,
1831 bool SubobjectIsDesignatorContext, unsigned &Index,
1832 InitListExpr *StructuredList, unsigned &StructuredIndex,
1833 bool TopLevelObject) {
1834 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001835
Eli Friedman23a9e312008-05-19 19:16:24 +00001836 // If the record is invalid, some of it's members are invalid. To avoid
1837 // confusion, we forgo checking the intializer for the entire record.
1838 if (structDecl->isInvalidDecl()) {
Richard Smith845aa662012-09-28 21:23:50 +00001839 // Assume it was supposed to consume a single initializer.
1840 ++Index;
Eli Friedman23a9e312008-05-19 19:16:24 +00001841 hadError = true;
1842 return;
Mike Stump11289f42009-09-09 15:08:12 +00001843 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001844
1845 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001846 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith852c9db2013-04-20 22:23:05 +00001847
1848 // If there's a default initializer, use it.
1849 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1850 if (VerifyOnly)
1851 return;
1852 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1853 Field != FieldEnd; ++Field) {
1854 if (Field->hasInClassInitializer()) {
1855 StructuredList->setInitializedFieldInUnion(*Field);
1856 // FIXME: Actually build a CXXDefaultInitExpr?
1857 return;
1858 }
1859 }
1860 }
1861
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001862 // Value-initialize the first member of the union that isn't an unnamed
1863 // bitfield.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001864 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1865 Field != FieldEnd; ++Field) {
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001866 if (!Field->isUnnamedBitfield()) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001867 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001868 CheckEmptyInitializable(
1869 InitializedEntity::InitializeMember(*Field, &Entity),
1870 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001871 else
David Blaikie40ed2972012-06-06 20:45:41 +00001872 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001873 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001874 }
1875 }
1876 return;
1877 }
1878
Richard Smith872307e2016-03-08 22:17:41 +00001879 bool InitializedSomething = false;
1880
1881 // If we have any base classes, they are initialized prior to the fields.
1882 for (auto &Base : Bases) {
1883 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
1884 SourceLocation InitLoc = Init ? Init->getLocStart() : IList->getLocEnd();
1885
1886 // Designated inits always initialize fields, so if we see one, all
1887 // remaining base classes have no explicit initializer.
1888 if (Init && isa<DesignatedInitExpr>(Init))
1889 Init = nullptr;
1890
1891 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
1892 SemaRef.Context, &Base, false, &Entity);
1893 if (Init) {
1894 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
1895 StructuredList, StructuredIndex);
1896 InitializedSomething = true;
1897 } else if (VerifyOnly) {
1898 CheckEmptyInitializable(BaseEntity, InitLoc);
1899 }
1900 }
1901
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001902 // If structDecl is a forward declaration, this loop won't do
1903 // anything except look at designated initializers; That's okay,
1904 // because an error should get printed out elsewhere. It might be
1905 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001906 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001907 RecordDecl::field_iterator FieldEnd = RD->field_end();
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00001908 bool CheckForMissingFields =
1909 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
1910
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001911 while (Index < IList->getNumInits()) {
1912 Expr *Init = IList->getInit(Index);
1913
1914 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001915 // If we're not the subobject that matches up with the '{' for
1916 // the designator, we shouldn't be handling the
1917 // designator. Return immediately.
1918 if (!SubobjectIsDesignatorContext)
1919 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001920
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001921 // Handle this designated initializer. Field will be updated to
1922 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001923 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001924 DeclType, &Field, nullptr, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001925 StructuredList, StructuredIndex,
1926 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001927 hadError = true;
1928
Douglas Gregora9add4e2009-02-12 19:00:39 +00001929 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001930
1931 // Disable check for missing fields when designators are used.
1932 // This matches gcc behaviour.
1933 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001934 continue;
1935 }
1936
1937 if (Field == FieldEnd) {
1938 // We've run out of fields. We're done.
1939 break;
1940 }
1941
Douglas Gregora9add4e2009-02-12 19:00:39 +00001942 // We've already initialized a member of a union. We're done.
1943 if (InitializedSomething && DeclType->isUnionType())
1944 break;
1945
Douglas Gregor91f84212008-12-11 16:49:14 +00001946 // If we've hit the flexible array member at the end, we're done.
1947 if (Field->getType()->isIncompleteArrayType())
1948 break;
1949
Douglas Gregor51695702009-01-29 16:53:55 +00001950 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001951 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001952 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001953 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001954 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001955
Douglas Gregora82064c2011-06-29 21:51:31 +00001956 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001957 bool InvalidUse;
1958 if (VerifyOnly)
Manman Ren073db022016-03-10 18:53:19 +00001959 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001960 else
David Blaikie40ed2972012-06-06 20:45:41 +00001961 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001962 IList->getInit(Index)->getLocStart());
1963 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001964 ++Index;
1965 ++Field;
1966 hadError = true;
1967 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001968 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001969
Anders Carlsson6cabf312010-01-23 23:23:01 +00001970 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001971 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001972 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1973 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001974 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001975
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001976 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001977 // Initialize the first field within the union.
David Blaikie40ed2972012-06-06 20:45:41 +00001978 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001979 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001980
1981 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001982 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001983
John McCalle40b58e2010-03-11 19:32:38 +00001984 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001985 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1986 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1987 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001988 // It is possible we have one or more unnamed bitfields remaining.
1989 // Find first (if any) named field and emit warning.
1990 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1991 it != end; ++it) {
Richard Smith852c9db2013-04-20 22:23:05 +00001992 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCalle40b58e2010-03-11 19:32:38 +00001993 SemaRef.Diag(IList->getSourceRange().getEnd(),
Aaron Ballmanb9bb2012014-01-03 14:54:10 +00001994 diag::warn_missing_field_initializers) << *it;
John McCalle40b58e2010-03-11 19:32:38 +00001995 break;
1996 }
1997 }
1998 }
1999
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00002000 // Check that any remaining fields can be value-initialized.
2001 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
2002 !Field->getType()->isIncompleteArrayType()) {
2003 // FIXME: Should check for holes left by designated initializers too.
2004 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smith852c9db2013-04-20 22:23:05 +00002005 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Richard Smith454a7cd2014-06-03 08:26:00 +00002006 CheckEmptyInitializable(
2007 InitializedEntity::InitializeMember(*Field, &Entity),
2008 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00002009 }
2010 }
2011
Mike Stump11289f42009-09-09 15:08:12 +00002012 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00002013 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002014 return;
2015
David Blaikie40ed2972012-06-06 20:45:41 +00002016 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00002017 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002018 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00002019 ++Index;
2020 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002021 }
2022
Anders Carlsson6cabf312010-01-23 23:23:01 +00002023 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002024 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002025
Anders Carlsson6cabf312010-01-23 23:23:01 +00002026 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002027 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00002028 StructuredList, StructuredIndex);
2029 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002030 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00002031 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00002032}
Steve Narofff8ecff22008-05-01 22:18:59 +00002033
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002034/// Expand a field designator that refers to a member of an
Douglas Gregord5846a12009-04-15 06:41:24 +00002035/// anonymous struct or union into a series of field designators that
2036/// refers to the field within the appropriate subobject.
2037///
Douglas Gregord5846a12009-04-15 06:41:24 +00002038static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00002039 DesignatedInitExpr *DIE,
2040 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002041 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00002042 typedef DesignatedInitExpr::Designator Designator;
2043
Douglas Gregord5846a12009-04-15 06:41:24 +00002044 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002045 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002046 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2047 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2048 if (PI + 1 == PE)
Craig Topperc3ec1492014-05-26 06:22:03 +00002049 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
Douglas Gregord5846a12009-04-15 06:41:24 +00002050 DIE->getDesignator(DesigIdx)->getDotLoc(),
2051 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2052 else
Craig Topperc3ec1492014-05-26 06:22:03 +00002053 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2054 SourceLocation(), SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002055 assert(isa<FieldDecl>(*PI));
2056 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00002057 }
2058
2059 // Expand the current designator into the set of replacement
2060 // designators, so we have a full subobject path down to where the
2061 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00002062 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00002063 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002064}
Mike Stump11289f42009-09-09 15:08:12 +00002065
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002066static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
2067 DesignatedInitExpr *DIE) {
2068 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2069 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2070 for (unsigned I = 0; I < NumIndexExprs; ++I)
2071 IndexExprs[I] = DIE->getSubExpr(I + 1);
David Majnemerf7e36092016-06-23 00:15:04 +00002072 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2073 IndexExprs,
Benjamin Kramerc215e762012-08-24 11:54:20 +00002074 DIE->getEqualOrColonLoc(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002075 DIE->usesGNUSyntax(), DIE->getInit());
2076}
2077
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002078namespace {
2079
2080// Callback to only accept typo corrections that are for field members of
2081// the given struct or union.
2082class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
2083 public:
2084 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
2085 : Record(RD) {}
2086
Craig Toppere14c0f82014-03-12 04:55:44 +00002087 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002088 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2089 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2090 }
2091
2092 private:
2093 RecordDecl *Record;
2094};
2095
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002096} // end anonymous namespace
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00002097
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002098/// Check the well-formedness of a C99 designated initializer.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002099///
2100/// Determines whether the designated initializer @p DIE, which
2101/// resides at the given @p Index within the initializer list @p
2102/// IList, is well-formed for a current object of type @p DeclType
2103/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00002104/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002105/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002106///
2107/// @param IList The initializer list in which this designated
2108/// initializer occurs.
2109///
Douglas Gregora5324162009-04-15 04:56:10 +00002110/// @param DIE The designated initializer expression.
2111///
2112/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002113///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002114/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002115/// into which the designation in @p DIE should refer.
2116///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002117/// @param NextField If non-NULL and the first designator in @p DIE is
2118/// a field, this will be set to the field declaration corresponding
2119/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002120///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002121/// @param NextElementIndex If non-NULL and the first designator in @p
2122/// DIE is an array designator or GNU array-range designator, this
2123/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002124///
2125/// @param Index Index into @p IList where the designated initializer
2126/// @p DIE occurs.
2127///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002128/// @param StructuredList The initializer list expression that
2129/// describes all of the subobject initializers in the order they'll
2130/// actually be initialized.
2131///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002132/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002133bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00002134InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002135 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002136 DesignatedInitExpr *DIE,
2137 unsigned DesigIdx,
2138 QualType &CurrentObjectType,
2139 RecordDecl::field_iterator *NextField,
2140 llvm::APSInt *NextElementIndex,
2141 unsigned &Index,
2142 InitListExpr *StructuredList,
2143 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002144 bool FinishSubobjectInit,
2145 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00002146 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002147 // Check the actual initialization for the designated object type.
2148 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00002149
2150 // Temporarily remove the designator expression from the
2151 // initializer list that the child calls see, so that we don't try
2152 // to re-process the designator.
2153 unsigned OldIndex = Index;
2154 IList->setInit(OldIndex, DIE->getInit());
2155
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002156 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002157 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00002158
2159 // Restore the designated initializer expression in the syntactic
2160 // form of the initializer list.
2161 if (IList->getInit(OldIndex) != DIE->getInit())
2162 DIE->setInit(IList->getInit(OldIndex));
2163 IList->setInit(OldIndex, DIE);
2164
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002165 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002166 }
2167
Douglas Gregora5324162009-04-15 04:56:10 +00002168 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002169 bool IsFirstDesignator = (DesigIdx == 0);
2170 if (!VerifyOnly) {
2171 assert((IsFirstDesignator || StructuredList) &&
2172 "Need a non-designated initializer list to start from");
2173
2174 // Determine the structural initializer list that corresponds to the
2175 // current subobject.
Yunzhong Gaocb779302015-06-10 00:27:52 +00002176 if (IsFirstDesignator)
2177 StructuredList = SyntacticToSemantic.lookup(IList);
2178 else {
2179 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2180 StructuredList->getInit(StructuredIndex) : nullptr;
2181 if (!ExistingInit && StructuredList->hasArrayFiller())
2182 ExistingInit = StructuredList->getArrayFiller();
2183
2184 if (!ExistingInit)
2185 StructuredList =
2186 getStructuredSubobjectInit(IList, Index, CurrentObjectType,
2187 StructuredList, StructuredIndex,
2188 SourceRange(D->getLocStart(),
2189 DIE->getLocEnd()));
2190 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2191 StructuredList = Result;
2192 else {
2193 if (DesignatedInitUpdateExpr *E =
2194 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2195 StructuredList = E->getUpdater();
2196 else {
2197 DesignatedInitUpdateExpr *DIUE =
2198 new (SemaRef.Context) DesignatedInitUpdateExpr(SemaRef.Context,
2199 D->getLocStart(), ExistingInit,
2200 DIE->getLocEnd());
2201 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2202 StructuredList = DIUE->getUpdater();
2203 }
2204
2205 // We need to check on source range validity because the previous
2206 // initializer does not have to be an explicit initializer. e.g.,
2207 //
2208 // struct P { int a, b; };
2209 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2210 //
2211 // There is an overwrite taking place because the first braced initializer
2212 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
2213 if (ExistingInit->getSourceRange().isValid()) {
2214 // We are creating an initializer list that initializes the
2215 // subobjects of the current object, but there was already an
2216 // initialization that completely initialized the current
2217 // subobject, e.g., by a compound literal:
2218 //
2219 // struct X { int a, b; };
2220 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2221 //
2222 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2223 // designated initializer re-initializes the whole
2224 // subobject [0], overwriting previous initializers.
2225 SemaRef.Diag(D->getLocStart(),
2226 diag::warn_subobject_initializer_overrides)
2227 << SourceRange(D->getLocStart(), DIE->getLocEnd());
2228
2229 SemaRef.Diag(ExistingInit->getLocStart(),
2230 diag::note_previous_initializer)
2231 << /*FIXME:has side effects=*/0
2232 << ExistingInit->getSourceRange();
2233 }
2234 }
2235 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002236 assert(StructuredList && "Expected a structured initializer list");
2237 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002238
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002239 if (D->isFieldDesignator()) {
2240 // C99 6.7.8p7:
2241 //
2242 // If a designator has the form
2243 //
2244 // . identifier
2245 //
2246 // then the current object (defined below) shall have
2247 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00002248 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002249 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002250 if (!RT) {
2251 SourceLocation Loc = D->getDotLoc();
2252 if (Loc.isInvalid())
2253 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002254 if (!VerifyOnly)
2255 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002256 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002257 ++Index;
2258 return true;
2259 }
2260
Douglas Gregord5846a12009-04-15 06:41:24 +00002261 FieldDecl *KnownField = D->getField();
David Majnemer36ef8982014-08-11 18:33:59 +00002262 if (!KnownField) {
2263 IdentifierInfo *FieldName = D->getFieldName();
2264 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
2265 for (NamedDecl *ND : Lookup) {
2266 if (auto *FD = dyn_cast<FieldDecl>(ND)) {
2267 KnownField = FD;
2268 break;
2269 }
2270 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002271 // In verify mode, don't modify the original.
2272 if (VerifyOnly)
2273 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
David Majnemer36ef8982014-08-11 18:33:59 +00002274 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002275 D = DIE->getDesignator(DesigIdx);
David Majnemer36ef8982014-08-11 18:33:59 +00002276 KnownField = cast<FieldDecl>(*IFD->chain_begin());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002277 break;
2278 }
2279 }
David Majnemer36ef8982014-08-11 18:33:59 +00002280 if (!KnownField) {
2281 if (VerifyOnly) {
2282 ++Index;
2283 return true; // No typo correction when just trying this out.
2284 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002285
David Majnemer36ef8982014-08-11 18:33:59 +00002286 // Name lookup found something, but it wasn't a field.
2287 if (!Lookup.empty()) {
2288 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2289 << FieldName;
2290 SemaRef.Diag(Lookup.front()->getLocation(),
2291 diag::note_field_designator_found);
2292 ++Index;
2293 return true;
2294 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002295
David Majnemer36ef8982014-08-11 18:33:59 +00002296 // Name lookup didn't find anything.
2297 // Determine whether this was a typo for another field name.
Richard Smithf9b15102013-08-17 00:46:16 +00002298 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2299 DeclarationNameInfo(FieldName, D->getFieldLoc()),
David Majnemer36ef8982014-08-11 18:33:59 +00002300 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002301 llvm::make_unique<FieldInitializerValidatorCCC>(RT->getDecl()),
2302 Sema::CTK_ErrorRecovery, RT->getDecl())) {
Richard Smithf9b15102013-08-17 00:46:16 +00002303 SemaRef.diagnoseTypo(
2304 Corrected,
2305 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
David Majnemer36ef8982014-08-11 18:33:59 +00002306 << FieldName << CurrentObjectType);
2307 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
Benjamin Kramerafe718f2011-09-25 02:41:26 +00002308 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002309 } else {
David Majnemer36ef8982014-08-11 18:33:59 +00002310 // Typo correction didn't find anything.
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002311 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
2312 << FieldName << CurrentObjectType;
2313 ++Index;
2314 return true;
2315 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002316 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002317 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002318
David Majnemer58e4ea92014-08-23 01:48:50 +00002319 unsigned FieldIndex = 0;
Akira Hatanaka8eccb9b2017-01-17 19:35:54 +00002320
2321 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2322 FieldIndex = CXXRD->getNumBases();
2323
David Majnemer58e4ea92014-08-23 01:48:50 +00002324 for (auto *FI : RT->getDecl()->fields()) {
2325 if (FI->isUnnamedBitfield())
2326 continue;
Richard Smithfe1bc702016-04-08 19:57:40 +00002327 if (declaresSameEntity(KnownField, FI)) {
2328 KnownField = FI;
David Majnemer58e4ea92014-08-23 01:48:50 +00002329 break;
Richard Smithfe1bc702016-04-08 19:57:40 +00002330 }
David Majnemer58e4ea92014-08-23 01:48:50 +00002331 ++FieldIndex;
2332 }
2333
David Majnemer36ef8982014-08-11 18:33:59 +00002334 RecordDecl::field_iterator Field =
2335 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2336
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002337 // All of the fields of a union are located at the same place in
2338 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00002339 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002340 FieldIndex = 0;
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002341 if (!VerifyOnly) {
2342 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
Richard Smithfe1bc702016-04-08 19:57:40 +00002343 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002344 assert(StructuredList->getNumInits() == 1
2345 && "A union should never have more than one initializer!");
2346
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002347 Expr *ExistingInit = StructuredList->getInit(0);
Vassil Vassilev1a1678e2017-04-14 08:48:08 +00002348 if (ExistingInit) {
2349 // We're about to throw away an initializer, emit warning.
2350 SemaRef.Diag(D->getFieldLoc(),
2351 diag::warn_initializer_overrides)
2352 << D->getSourceRange();
2353 SemaRef.Diag(ExistingInit->getLocStart(),
2354 diag::note_previous_initializer)
2355 << /*FIXME:has side effects=*/0
2356 << ExistingInit->getSourceRange();
2357 }
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002358
2359 // remove existing initializer
2360 StructuredList->resizeInits(SemaRef.Context, 0);
Craig Topperc3ec1492014-05-26 06:22:03 +00002361 StructuredList->setInitializedFieldInUnion(nullptr);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002362 }
2363
David Blaikie40ed2972012-06-06 20:45:41 +00002364 StructuredList->setInitializedFieldInUnion(*Field);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002365 }
Douglas Gregor51695702009-01-29 16:53:55 +00002366 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002367
Douglas Gregora82064c2011-06-29 21:51:31 +00002368 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002369 bool InvalidUse;
2370 if (VerifyOnly)
Manman Ren073db022016-03-10 18:53:19 +00002371 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002372 else
David Blaikie40ed2972012-06-06 20:45:41 +00002373 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002374 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00002375 ++Index;
2376 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002377 }
Douglas Gregora82064c2011-06-29 21:51:31 +00002378
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002379 if (!VerifyOnly) {
2380 // Update the designator with the field declaration.
David Blaikie40ed2972012-06-06 20:45:41 +00002381 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00002382
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002383 // Make sure that our non-designated initializer list has space
2384 // for a subobject corresponding to this field.
2385 if (FieldIndex >= StructuredList->getNumInits())
2386 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2387 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002388
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002389 // This designator names a flexible array member.
2390 if (Field->getType()->isIncompleteArrayType()) {
2391 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00002392 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002393 // We can't designate an object within the flexible array
2394 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002395 if (!VerifyOnly) {
2396 DesignatedInitExpr::Designator *NextD
2397 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002398 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002399 diag::err_designator_into_flexible_array_member)
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002400 << SourceRange(NextD->getLocStart(),
2401 DIE->getLocEnd());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002402 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002403 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002404 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002405 Invalid = true;
2406 }
2407
Chris Lattner001b29c2010-10-10 17:49:49 +00002408 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2409 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002410 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002411 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002412 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002413 diag::err_flexible_array_init_needs_braces)
2414 << DIE->getInit()->getSourceRange();
2415 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002416 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002417 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002418 Invalid = true;
2419 }
2420
Eli Friedman3fa64df2011-08-23 22:24:57 +00002421 // Check GNU flexible array initializer.
David Blaikie40ed2972012-06-06 20:45:41 +00002422 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00002423 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002424 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002425
2426 if (Invalid) {
2427 ++Index;
2428 return true;
2429 }
2430
2431 // Initialize the array.
2432 bool prevHadError = hadError;
2433 unsigned newStructuredIndex = FieldIndex;
2434 unsigned OldIndex = Index;
2435 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00002436
2437 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002438 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002439 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002440 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002441
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002442 IList->setInit(OldIndex, DIE);
2443 if (hadError && !prevHadError) {
2444 ++Field;
2445 ++FieldIndex;
2446 if (NextField)
2447 *NextField = Field;
2448 StructuredIndex = FieldIndex;
2449 return true;
2450 }
2451 } else {
2452 // Recurse to check later designated subobjects.
David Blaikie2d7c57e2012-04-30 02:36:29 +00002453 QualType FieldType = Field->getType();
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002454 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002455
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002456 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002457 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002458 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002459 FieldType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002460 StructuredList, newStructuredIndex,
Alexey Bataev86a489e2016-01-25 05:14:03 +00002461 FinishSubobjectInit, false))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002462 return true;
2463 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002464
2465 // Find the position of the next field to be initialized in this
2466 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002467 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002468 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002469
2470 // If this the first designator, our caller will continue checking
2471 // the rest of this struct/class/union subobject.
2472 if (IsFirstDesignator) {
2473 if (NextField)
2474 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002475 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002476 return false;
2477 }
2478
Douglas Gregor17bd0942009-01-28 23:36:17 +00002479 if (!FinishSubobjectInit)
2480 return false;
2481
Douglas Gregord5846a12009-04-15 06:41:24 +00002482 // We've already initialized something in the union; we're done.
2483 if (RT->getDecl()->isUnion())
2484 return hadError;
2485
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002486 // Check the remaining fields within this class/struct/union subobject.
2487 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002488
Richard Smith872307e2016-03-08 22:17:41 +00002489 auto NoBases =
2490 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
2491 CXXRecordDecl::base_class_iterator());
2492 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2493 false, Index, StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002494 return hadError && !prevHadError;
2495 }
2496
2497 // C99 6.7.8p6:
2498 //
2499 // If a designator has the form
2500 //
2501 // [ constant-expression ]
2502 //
2503 // then the current object (defined below) shall have array
2504 // type and the expression shall be an integer constant
2505 // expression. If the array is of unknown size, any
2506 // nonnegative value is valid.
2507 //
2508 // Additionally, cope with the GNU extension that permits
2509 // designators of the form
2510 //
2511 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00002512 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002513 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002514 if (!VerifyOnly)
2515 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2516 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002517 ++Index;
2518 return true;
2519 }
2520
Craig Topperc3ec1492014-05-26 06:22:03 +00002521 Expr *IndexExpr = nullptr;
Douglas Gregor17bd0942009-01-28 23:36:17 +00002522 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2523 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002524 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00002525 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002526 DesignatedEndIndex = DesignatedStartIndex;
2527 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002528 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00002529
Mike Stump11289f42009-09-09 15:08:12 +00002530 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002531 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002532 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002533 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002534 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002535
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00002536 // Codegen can't handle evaluating array range designators that have side
2537 // effects, because we replicate the AST value for each initialized element.
2538 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2539 // elements with something that has a side effect, so codegen can emit an
2540 // "error unsupported" error instead of miscompiling the app.
2541 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002542 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00002543 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002544 }
2545
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002546 if (isa<ConstantArrayType>(AT)) {
2547 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002548 DesignatedStartIndex
2549 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002550 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00002551 DesignatedEndIndex
2552 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002553 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2554 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00002555 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002556 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002557 diag::err_array_designator_too_large)
2558 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2559 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002560 ++Index;
2561 return true;
2562 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00002563 } else {
Argyrios Kyrtzidis4746c2f2015-07-27 23:16:53 +00002564 unsigned DesignatedIndexBitWidth =
2565 ConstantArrayType::getMaxSizeBits(SemaRef.Context);
2566 DesignatedStartIndex =
2567 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
2568 DesignatedEndIndex =
2569 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002570 DesignatedStartIndex.setIsUnsigned(true);
2571 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002572 }
Mike Stump11289f42009-09-09 15:08:12 +00002573
Eli Friedman1f16b742013-06-11 21:48:11 +00002574 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2575 // We're modifying a string literal init; we have to decompose the string
2576 // so we can modify the individual characters.
2577 ASTContext &Context = SemaRef.Context;
2578 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2579
2580 // Compute the character type
2581 QualType CharTy = AT->getElementType();
2582
2583 // Compute the type of the integer literals.
2584 QualType PromotedCharTy = CharTy;
2585 if (CharTy->isPromotableIntegerType())
2586 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2587 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2588
2589 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2590 // Get the length of the string.
2591 uint64_t StrLen = SL->getLength();
2592 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2593 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2594 StructuredList->resizeInits(Context, StrLen);
2595
2596 // Build a literal for each character in the string, and put them into
2597 // the init list.
2598 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2599 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2600 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002601 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002602 if (CharTy != PromotedCharTy)
2603 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002604 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002605 StructuredList->updateInit(Context, i, Init);
2606 }
2607 } else {
2608 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2609 std::string Str;
2610 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2611
2612 // Get the length of the string.
2613 uint64_t StrLen = Str.size();
2614 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2615 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2616 StructuredList->resizeInits(Context, StrLen);
2617
2618 // Build a literal for each character in the string, and put them into
2619 // the init list.
2620 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2621 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2622 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002623 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002624 if (CharTy != PromotedCharTy)
2625 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002626 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002627 StructuredList->updateInit(Context, i, Init);
2628 }
2629 }
2630 }
2631
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002632 // Make sure that our non-designated initializer list has space
2633 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002634 if (!VerifyOnly &&
2635 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00002636 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00002637 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002638
Douglas Gregor17bd0942009-01-28 23:36:17 +00002639 // Repeatedly perform subobject initializations in the range
2640 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002641
Douglas Gregor17bd0942009-01-28 23:36:17 +00002642 // Move to the next designator
2643 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2644 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002645
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002646 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00002647 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002648
Douglas Gregor17bd0942009-01-28 23:36:17 +00002649 while (DesignatedStartIndex <= DesignatedEndIndex) {
2650 // Recurse to check later designated subobjects.
2651 QualType ElementType = AT->getElementType();
2652 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002653
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002654 ElementEntity.setElementIndex(ElementIndex);
Alexey Bataev86a489e2016-01-25 05:14:03 +00002655 if (CheckDesignatedInitializer(
2656 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
2657 nullptr, Index, StructuredList, ElementIndex,
2658 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
2659 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002660 return true;
2661
2662 // Move to the next index in the array that we'll be initializing.
2663 ++DesignatedStartIndex;
2664 ElementIndex = DesignatedStartIndex.getZExtValue();
2665 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002666
2667 // If this the first designator, our caller will continue checking
2668 // the rest of this array subobject.
2669 if (IsFirstDesignator) {
2670 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002671 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002672 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002673 return false;
2674 }
Mike Stump11289f42009-09-09 15:08:12 +00002675
Douglas Gregor17bd0942009-01-28 23:36:17 +00002676 if (!FinishSubobjectInit)
2677 return false;
2678
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002679 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002680 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002681 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002682 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002683 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002684 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002685}
2686
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002687// Get the structured initializer list for a subobject of type
2688// @p CurrentObjectType.
2689InitListExpr *
2690InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2691 QualType CurrentObjectType,
2692 InitListExpr *StructuredList,
2693 unsigned StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +00002694 SourceRange InitRange,
2695 bool IsFullyOverwritten) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002696 if (VerifyOnly)
Craig Topperc3ec1492014-05-26 06:22:03 +00002697 return nullptr; // No structured list in verification-only mode.
2698 Expr *ExistingInit = nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002699 if (!StructuredList)
Benjamin Kramer6b441d62012-02-23 14:48:40 +00002700 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002701 else if (StructuredIndex < StructuredList->getNumInits())
2702 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002703
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002704 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
Yunzhong Gaocb779302015-06-10 00:27:52 +00002705 // There might have already been initializers for subobjects of the current
2706 // object, but a subsequent initializer list will overwrite the entirety
2707 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
2708 //
2709 // struct P { char x[6]; };
2710 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
2711 //
2712 // The first designated initializer is ignored, and l.x is just "f".
2713 if (!IsFullyOverwritten)
2714 return Result;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002715
2716 if (ExistingInit) {
2717 // We are creating an initializer list that initializes the
2718 // subobjects of the current object, but there was already an
2719 // initialization that completely initialized the current
2720 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002721 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002722 // struct X { int a, b; };
2723 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002724 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002725 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2726 // designated initializer re-initializes the whole
2727 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002728 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002729 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002730 << InitRange;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002731 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002732 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002733 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002734 << ExistingInit->getSourceRange();
2735 }
2736
Mike Stump11289f42009-09-09 15:08:12 +00002737 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002738 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko78852e92013-05-05 20:40:26 +00002739 InitRange.getBegin(), None,
Ted Kremenek013041e2010-02-19 01:50:18 +00002740 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002741
Eli Friedman91f5ae52012-02-23 02:25:10 +00002742 QualType ResultType = CurrentObjectType;
2743 if (!ResultType->isArrayType())
2744 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2745 Result->setType(ResultType);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002746
Douglas Gregor6d00c992009-03-20 23:58:33 +00002747 // Pre-allocate storage for the structured initializer list.
2748 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002749 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002750 bool GotNumInits = false;
2751 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002752 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002753 GotNumInits = true;
2754 } else if (Index < IList->getNumInits()) {
2755 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002756 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002757 GotNumInits = true;
2758 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002759 }
2760
Mike Stump11289f42009-09-09 15:08:12 +00002761 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002762 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2763 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2764 NumElements = CAType->getSize().getZExtValue();
2765 // Simple heuristic so that we don't allocate a very large
2766 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002767 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002768 NumElements = 0;
2769 }
John McCall9dd450b2009-09-21 23:43:11 +00002770 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002771 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002772 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002773 RecordDecl *RDecl = RType->getDecl();
2774 if (RDecl->isUnion())
2775 NumElements = 1;
2776 else
Aaron Ballman62e47c42014-03-10 13:43:55 +00002777 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002778 }
2779
Ted Kremenekac034612010-04-13 23:39:13 +00002780 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002781
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002782 // Link this new initializer list into the structured initializer
2783 // lists.
2784 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002785 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002786 else {
2787 Result->setSyntacticForm(IList);
2788 SyntacticToSemantic[IList] = Result;
2789 }
2790
2791 return Result;
2792}
2793
2794/// Update the initializer at index @p StructuredIndex within the
2795/// structured initializer list to the value @p expr.
2796void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2797 unsigned &StructuredIndex,
2798 Expr *expr) {
2799 // No structured initializer list to update
2800 if (!StructuredList)
2801 return;
2802
Ted Kremenekac034612010-04-13 23:39:13 +00002803 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2804 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002805 // This initializer overwrites a previous initializer. Warn.
Yunzhong Gaocb779302015-06-10 00:27:52 +00002806 // We need to check on source range validity because the previous
2807 // initializer does not have to be an explicit initializer.
2808 // struct P { int a, b; };
2809 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2810 // There is an overwrite taking place because the first braced initializer
2811 // list "{ .a = 2 }' already provides value for .p.b (which is zero).
2812 if (PrevInit->getSourceRange().isValid()) {
2813 SemaRef.Diag(expr->getLocStart(),
2814 diag::warn_initializer_overrides)
2815 << expr->getSourceRange();
2816
2817 SemaRef.Diag(PrevInit->getLocStart(),
2818 diag::note_previous_initializer)
2819 << /*FIXME:has side effects=*/0
2820 << PrevInit->getSourceRange();
2821 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002822 }
Mike Stump11289f42009-09-09 15:08:12 +00002823
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002824 ++StructuredIndex;
2825}
2826
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002827/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002828/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002829/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002830/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002831/// failure. Returns the index expression, possibly with an implicit cast
2832/// added, on success. If everything went okay, Value will receive the
2833/// value of the constant expression.
2834static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002835CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002836 SourceLocation Loc = Index->getLocStart();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002837
2838 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002839 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2840 if (Result.isInvalid())
2841 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002842
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002843 if (Value.isSigned() && Value.isNegative())
2844 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002845 << Value.toString(10) << Index->getSourceRange();
2846
Douglas Gregor51650d32009-01-23 21:04:18 +00002847 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002848 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002849}
2850
John McCalldadc5752010-08-24 06:29:42 +00002851ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002852 SourceLocation Loc,
2853 bool GNUSyntax,
2854 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002855 typedef DesignatedInitExpr::Designator ASTDesignator;
2856
2857 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002858 SmallVector<ASTDesignator, 32> Designators;
2859 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002860
2861 // Build designators and check array designator expressions.
2862 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2863 const Designator &D = Desig.getDesignator(Idx);
2864 switch (D.getKind()) {
2865 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002866 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002867 D.getFieldLoc()));
2868 break;
2869
2870 case Designator::ArrayDesignator: {
2871 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2872 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00002873 if (!Index->isTypeDependent() && !Index->isValueDependent())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002874 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002875 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002876 Invalid = true;
2877 else {
2878 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002879 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002880 D.getRBracketLoc()));
2881 InitExpressions.push_back(Index);
2882 }
2883 break;
2884 }
2885
2886 case Designator::ArrayRangeDesignator: {
2887 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2888 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2889 llvm::APSInt StartValue;
2890 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002891 bool StartDependent = StartIndex->isTypeDependent() ||
2892 StartIndex->isValueDependent();
2893 bool EndDependent = EndIndex->isTypeDependent() ||
2894 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00002895 if (!StartDependent)
2896 StartIndex =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002897 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002898 if (!EndDependent)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002899 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002900
2901 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002902 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002903 else {
2904 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002905 if (StartDependent || EndDependent) {
2906 // Nothing to compute.
2907 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002908 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002909 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002910 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002911
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002912 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002913 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002914 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002915 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2916 Invalid = true;
2917 } else {
2918 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002919 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002920 D.getEllipsisLoc(),
2921 D.getRBracketLoc()));
2922 InitExpressions.push_back(StartIndex);
2923 InitExpressions.push_back(EndIndex);
2924 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002925 }
2926 break;
2927 }
2928 }
2929 }
2930
2931 if (Invalid || Init.isInvalid())
2932 return ExprError();
2933
2934 // Clear out the expressions within the designation.
2935 Desig.ClearExprs(*this);
2936
2937 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002938 = DesignatedInitExpr::Create(Context,
David Majnemerf7e36092016-06-23 00:15:04 +00002939 Designators,
Benjamin Kramerc215e762012-08-24 11:54:20 +00002940 InitExpressions, Loc, GNUSyntax,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002941 Init.getAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002942
David Blaikiebbafb8a2012-03-11 07:00:24 +00002943 if (!getLangOpts().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002944 Diag(DIE->getLocStart(), diag::ext_designated_init)
2945 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002946
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002947 return DIE;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002948}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002949
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002950//===----------------------------------------------------------------------===//
2951// Initialization entity
2952//===----------------------------------------------------------------------===//
2953
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002954InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002955 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002956 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002957{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002958 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2959 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002960 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002961 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002962 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002963 Type = VT->getElementType();
2964 } else {
2965 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2966 assert(CT && "Unexpected type");
2967 Kind = EK_ComplexElement;
2968 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002969 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002970}
2971
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002972InitializedEntity
2973InitializedEntity::InitializeBase(ASTContext &Context,
2974 const CXXBaseSpecifier *Base,
Richard Smith872307e2016-03-08 22:17:41 +00002975 bool IsInheritedVirtualBase,
2976 const InitializedEntity *Parent) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002977 InitializedEntity Result;
2978 Result.Kind = EK_Base;
Richard Smith872307e2016-03-08 22:17:41 +00002979 Result.Parent = Parent;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002980 Result.Base = reinterpret_cast<uintptr_t>(Base);
2981 if (IsInheritedVirtualBase)
2982 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002983
Douglas Gregor1b303932009-12-22 15:35:07 +00002984 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002985 return Result;
2986}
2987
Douglas Gregor85dabae2009-12-16 01:38:02 +00002988DeclarationName InitializedEntity::getName() const {
2989 switch (getKind()) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002990 case EK_Parameter:
2991 case EK_Parameter_CF_Audited: {
John McCall31168b02011-06-15 23:02:42 +00002992 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2993 return (D ? D->getDeclName() : DeclarationName());
2994 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002995
2996 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002997 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00002998 case EK_Binding:
Richard Smith410306b2016-12-12 02:53:20 +00002999 return Variable.VariableOrMember->getDeclName();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003000
Douglas Gregor19666fb2012-02-15 16:57:26 +00003001 case EK_LambdaCapture:
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00003002 return DeclarationName(Capture.VarID);
Douglas Gregor19666fb2012-02-15 16:57:26 +00003003
Douglas Gregor85dabae2009-12-16 01:38:02 +00003004 case EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00003005 case EK_StmtExprResult:
Douglas Gregor85dabae2009-12-16 01:38:02 +00003006 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003007 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00003008 case EK_Temporary:
3009 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003010 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003011 case EK_ArrayElement:
3012 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003013 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003014 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00003015 case EK_LambdaToBlockConversionBlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00003016 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003017 case EK_RelatedResult:
Douglas Gregor85dabae2009-12-16 01:38:02 +00003018 return DeclarationName();
3019 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003020
David Blaikie8a40f702012-01-17 06:56:22 +00003021 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00003022}
3023
Richard Smith7873de02016-08-11 22:25:46 +00003024ValueDecl *InitializedEntity::getDecl() const {
Douglas Gregora4b592a2009-12-19 03:01:41 +00003025 switch (getKind()) {
3026 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003027 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00003028 case EK_Binding:
Richard Smith410306b2016-12-12 02:53:20 +00003029 return Variable.VariableOrMember;
Douglas Gregora4b592a2009-12-19 03:01:41 +00003030
John McCall31168b02011-06-15 23:02:42 +00003031 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003032 case EK_Parameter_CF_Audited:
John McCall31168b02011-06-15 23:02:42 +00003033 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
3034
Douglas Gregora4b592a2009-12-19 03:01:41 +00003035 case EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00003036 case EK_StmtExprResult:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003037 case EK_Exception:
3038 case EK_New:
3039 case EK_Temporary:
3040 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003041 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003042 case EK_ArrayElement:
3043 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003044 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003045 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00003046 case EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00003047 case EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00003048 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003049 case EK_RelatedResult:
Craig Topperc3ec1492014-05-26 06:22:03 +00003050 return nullptr;
Douglas Gregora4b592a2009-12-19 03:01:41 +00003051 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003052
David Blaikie8a40f702012-01-17 06:56:22 +00003053 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00003054}
3055
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003056bool InitializedEntity::allowsNRVO() const {
3057 switch (getKind()) {
3058 case EK_Result:
3059 case EK_Exception:
3060 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003061
Richard Smith67af95b2018-07-23 19:19:08 +00003062 case EK_StmtExprResult:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003063 case EK_Variable:
3064 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003065 case EK_Parameter_CF_Audited:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003066 case EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00003067 case EK_Binding:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003068 case EK_New:
3069 case EK_Temporary:
Jordan Rose6c0505e2013-05-06 16:48:12 +00003070 case EK_CompoundLiteralInit:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003071 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003072 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003073 case EK_ArrayElement:
3074 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003075 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003076 case EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00003077 case EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00003078 case EK_LambdaCapture:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003079 case EK_RelatedResult:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003080 break;
3081 }
3082
3083 return false;
3084}
3085
Richard Smithe6c01442013-06-05 00:46:14 +00003086unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
Richard Smithe3b28bc2013-06-12 21:51:50 +00003087 assert(getParent() != this);
Richard Smithe6c01442013-06-05 00:46:14 +00003088 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3089 for (unsigned I = 0; I != Depth; ++I)
3090 OS << "`-";
3091
3092 switch (getKind()) {
3093 case EK_Variable: OS << "Variable"; break;
3094 case EK_Parameter: OS << "Parameter"; break;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003095 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3096 break;
Richard Smithe6c01442013-06-05 00:46:14 +00003097 case EK_Result: OS << "Result"; break;
Richard Smith67af95b2018-07-23 19:19:08 +00003098 case EK_StmtExprResult: OS << "StmtExprResult"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00003099 case EK_Exception: OS << "Exception"; break;
3100 case EK_Member: OS << "Member"; break;
Richard Smith7873de02016-08-11 22:25:46 +00003101 case EK_Binding: OS << "Binding"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00003102 case EK_New: OS << "New"; break;
3103 case EK_Temporary: OS << "Temporary"; break;
3104 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003105 case EK_RelatedResult: OS << "RelatedResult"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00003106 case EK_Base: OS << "Base"; break;
3107 case EK_Delegating: OS << "Delegating"; break;
3108 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3109 case EK_VectorElement: OS << "VectorElement " << Index; break;
3110 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3111 case EK_BlockElement: OS << "Block"; break;
Alex Lorenzb4791c72017-04-06 12:53:43 +00003112 case EK_LambdaToBlockConversionBlockElement:
3113 OS << "Block (lambda)";
3114 break;
Richard Smithe6c01442013-06-05 00:46:14 +00003115 case EK_LambdaCapture:
3116 OS << "LambdaCapture ";
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00003117 OS << DeclarationName(Capture.VarID);
Richard Smithe6c01442013-06-05 00:46:14 +00003118 break;
3119 }
3120
Richard Smith7873de02016-08-11 22:25:46 +00003121 if (auto *D = getDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00003122 OS << " ";
Richard Smith7873de02016-08-11 22:25:46 +00003123 D->printQualifiedName(OS);
Richard Smithe6c01442013-06-05 00:46:14 +00003124 }
3125
3126 OS << " '" << getType().getAsString() << "'\n";
3127
3128 return Depth + 1;
3129}
3130
Yaron Kerencdae9412016-01-29 19:38:18 +00003131LLVM_DUMP_METHOD void InitializedEntity::dump() const {
Richard Smithe6c01442013-06-05 00:46:14 +00003132 dumpImpl(llvm::errs());
3133}
3134
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003135//===----------------------------------------------------------------------===//
3136// Initialization sequence
3137//===----------------------------------------------------------------------===//
3138
3139void InitializationSequence::Step::Destroy() {
3140 switch (Kind) {
3141 case SK_ResolveAddressOfOverloadedFunction:
3142 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003143 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003144 case SK_CastDerivedToBaseLValue:
3145 case SK_BindReference:
3146 case SK_BindReferenceToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00003147 case SK_FinalCopy:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003148 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003149 case SK_UserConversion:
3150 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003151 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003152 case SK_QualificationConversionLValue:
Richard Smith77be48a2014-07-31 06:31:19 +00003153 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00003154 case SK_LValueToRValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00003155 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00003156 case SK_UnwrapInitList:
3157 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003158 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00003159 case SK_ConstructorInitializationFromList:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003160 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00003161 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003162 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003163 case SK_ObjCObjectConversion:
Richard Smith410306b2016-12-12 02:53:20 +00003164 case SK_ArrayLoopIndex:
3165 case SK_ArrayLoopInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003166 case SK_ArrayInit:
Richard Smith378b8c82016-12-14 03:22:16 +00003167 case SK_GNUArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00003168 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00003169 case SK_PassByIndirectCopyRestore:
3170 case SK_PassByIndirectRestore:
3171 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00003172 case SK_StdInitializerList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00003173 case SK_StdInitializerListConstructorCall:
Guy Benyei61054192013-02-07 10:55:47 +00003174 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003175 case SK_OCLZeroEvent:
Egor Churaev89831422016-12-23 14:55:49 +00003176 case SK_OCLZeroQueue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003177 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003178
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003179 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00003180 case SK_ConversionSequenceNoNarrowing:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003181 delete ICS;
3182 }
3183}
3184
Douglas Gregor838fcc32010-03-26 20:14:36 +00003185bool InitializationSequence::isDirectReferenceBinding() const {
Richard Smithb8c0f552016-12-09 18:49:13 +00003186 // There can be some lvalue adjustments after the SK_BindReference step.
3187 for (auto I = Steps.rbegin(); I != Steps.rend(); ++I) {
3188 if (I->Kind == SK_BindReference)
3189 return true;
3190 if (I->Kind == SK_BindReferenceToTemporary)
3191 return false;
3192 }
3193 return false;
Douglas Gregor838fcc32010-03-26 20:14:36 +00003194}
3195
3196bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00003197 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00003198 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003199
Douglas Gregor838fcc32010-03-26 20:14:36 +00003200 switch (getFailureKind()) {
3201 case FK_TooManyInitsForReference:
Richard Smith49a6b6e2017-03-24 01:14:25 +00003202 case FK_ParenthesizedListInitForReference:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003203 case FK_ArrayNeedsInitList:
3204 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00003205 case FK_ArrayNeedsInitListOrWideStringLiteral:
3206 case FK_NarrowStringIntoWideCharArray:
3207 case FK_WideStringIntoCharArray:
3208 case FK_IncompatWideStringIntoWideChar:
Richard Smith3a8244d2018-05-01 05:02:45 +00003209 case FK_PlainStringIntoUTF8Char:
3210 case FK_UTF8StringIntoPlainChar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003211 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3212 case FK_NonConstLValueReferenceBindingToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00003213 case FK_NonConstLValueReferenceBindingToBitfield:
3214 case FK_NonConstLValueReferenceBindingToVectorElement:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003215 case FK_NonConstLValueReferenceBindingToUnrelated:
3216 case FK_RValueReferenceBindingToLValue:
3217 case FK_ReferenceInitDropsQualifiers:
3218 case FK_ReferenceInitFailed:
3219 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00003220 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003221 case FK_TooManyInitsForScalar:
Richard Smith49a6b6e2017-03-24 01:14:25 +00003222 case FK_ParenthesizedListInitForScalar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003223 case FK_ReferenceBindingToInitList:
3224 case FK_InitListBadDestinationType:
3225 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003226 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003227 case FK_ArrayTypeMismatch:
3228 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00003229 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00003230 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00003231 case FK_PlaceholderType:
Sebastian Redl048a6d72012-04-01 19:54:59 +00003232 case FK_ExplicitConstructor:
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003233 case FK_AddressOfUnaddressableFunction:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003234 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003235
Douglas Gregor838fcc32010-03-26 20:14:36 +00003236 case FK_ReferenceInitOverloadFailed:
3237 case FK_UserConversionOverloadFailed:
3238 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003239 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003240 return FailedOverloadResult == OR_Ambiguous;
3241 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003242
David Blaikie8a40f702012-01-17 06:56:22 +00003243 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00003244}
3245
Douglas Gregorb33eed02010-04-16 22:09:46 +00003246bool InitializationSequence::isConstructorInitialization() const {
3247 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3248}
3249
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003250void
3251InitializationSequence
3252::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3253 DeclAccessPair Found,
3254 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003255 Step S;
3256 S.Kind = SK_ResolveAddressOfOverloadedFunction;
3257 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003258 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003259 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00003260 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003261 Steps.push_back(S);
3262}
3263
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003264void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00003265 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003266 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00003267 switch (VK) {
3268 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
3269 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3270 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003271 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003272 S.Type = BaseType;
3273 Steps.push_back(S);
3274}
3275
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003276void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003277 bool BindingTemporary) {
3278 Step S;
3279 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3280 S.Type = T;
3281 Steps.push_back(S);
3282}
3283
Richard Smithb8c0f552016-12-09 18:49:13 +00003284void InitializationSequence::AddFinalCopy(QualType T) {
3285 Step S;
3286 S.Kind = SK_FinalCopy;
3287 S.Type = T;
3288 Steps.push_back(S);
3289}
3290
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003291void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
3292 Step S;
3293 S.Kind = SK_ExtraneousCopyToTemporary;
3294 S.Type = T;
3295 Steps.push_back(S);
3296}
3297
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003298void
3299InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
3300 DeclAccessPair FoundDecl,
3301 QualType T,
3302 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003303 Step S;
3304 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003305 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003306 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003307 S.Function.Function = Function;
3308 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003309 Steps.push_back(S);
3310}
3311
3312void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00003313 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003314 Step S;
John McCall7a1da892010-08-26 16:36:35 +00003315 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00003316 switch (VK) {
3317 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003318 S.Kind = SK_QualificationConversionRValue;
3319 break;
John McCall2536c6d2010-08-25 10:28:54 +00003320 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003321 S.Kind = SK_QualificationConversionXValue;
3322 break;
John McCall2536c6d2010-08-25 10:28:54 +00003323 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003324 S.Kind = SK_QualificationConversionLValue;
3325 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003326 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003327 S.Type = Ty;
3328 Steps.push_back(S);
3329}
3330
Richard Smith77be48a2014-07-31 06:31:19 +00003331void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
3332 Step S;
3333 S.Kind = SK_AtomicConversion;
3334 S.Type = Ty;
3335 Steps.push_back(S);
3336}
3337
Jordan Roseb1312a52013-04-11 00:58:58 +00003338void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
3339 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
3340
3341 Step S;
3342 S.Kind = SK_LValueToRValue;
3343 S.Type = Ty;
3344 Steps.push_back(S);
3345}
3346
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003347void InitializationSequence::AddConversionSequenceStep(
Richard Smithaaa0ec42013-09-21 21:19:19 +00003348 const ImplicitConversionSequence &ICS, QualType T,
3349 bool TopLevelOfInitList) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003350 Step S;
Richard Smithaaa0ec42013-09-21 21:19:19 +00003351 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3352 : SK_ConversionSequence;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003353 S.Type = T;
3354 S.ICS = new ImplicitConversionSequence(ICS);
3355 Steps.push_back(S);
3356}
3357
Douglas Gregor51e77d52009-12-10 17:56:55 +00003358void InitializationSequence::AddListInitializationStep(QualType T) {
3359 Step S;
3360 S.Kind = SK_ListInitialization;
3361 S.Type = T;
3362 Steps.push_back(S);
3363}
3364
Richard Smith55c28882016-05-12 23:45:49 +00003365void InitializationSequence::AddConstructorInitializationStep(
3366 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3367 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003368 Step S;
Richard Smithf8adcdc2014-07-17 05:12:35 +00003369 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
Richard Smith53324112014-07-16 21:33:43 +00003370 : SK_ConstructorInitializationFromList
3371 : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003372 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003373 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003374 S.Function.Function = Constructor;
Richard Smith55c28882016-05-12 23:45:49 +00003375 S.Function.FoundDecl = FoundDecl;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003376 Steps.push_back(S);
3377}
3378
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003379void InitializationSequence::AddZeroInitializationStep(QualType T) {
3380 Step S;
3381 S.Kind = SK_ZeroInitialization;
3382 S.Type = T;
3383 Steps.push_back(S);
3384}
3385
Douglas Gregore1314a62009-12-18 05:02:21 +00003386void InitializationSequence::AddCAssignmentStep(QualType T) {
3387 Step S;
3388 S.Kind = SK_CAssignment;
3389 S.Type = T;
3390 Steps.push_back(S);
3391}
3392
Eli Friedman78275202009-12-19 08:11:05 +00003393void InitializationSequence::AddStringInitStep(QualType T) {
3394 Step S;
3395 S.Kind = SK_StringInit;
3396 S.Type = T;
3397 Steps.push_back(S);
3398}
3399
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003400void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3401 Step S;
3402 S.Kind = SK_ObjCObjectConversion;
3403 S.Type = T;
3404 Steps.push_back(S);
3405}
3406
Richard Smith378b8c82016-12-14 03:22:16 +00003407void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00003408 Step S;
Richard Smith378b8c82016-12-14 03:22:16 +00003409 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
Douglas Gregore2f943b2011-02-22 18:29:51 +00003410 S.Type = T;
3411 Steps.push_back(S);
3412}
3413
Richard Smith410306b2016-12-12 02:53:20 +00003414void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
3415 Step S;
3416 S.Kind = SK_ArrayLoopIndex;
3417 S.Type = EltT;
3418 Steps.insert(Steps.begin(), S);
3419
3420 S.Kind = SK_ArrayLoopInit;
3421 S.Type = T;
3422 Steps.push_back(S);
3423}
3424
Richard Smithebeed412012-02-15 22:38:09 +00003425void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3426 Step S;
3427 S.Kind = SK_ParenthesizedArrayInit;
3428 S.Type = T;
3429 Steps.push_back(S);
3430}
3431
John McCall31168b02011-06-15 23:02:42 +00003432void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3433 bool shouldCopy) {
3434 Step s;
3435 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3436 : SK_PassByIndirectRestore);
3437 s.Type = type;
3438 Steps.push_back(s);
3439}
3440
3441void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3442 Step S;
3443 S.Kind = SK_ProduceObjCObject;
3444 S.Type = T;
3445 Steps.push_back(S);
3446}
3447
Sebastian Redlc1839b12012-01-17 22:49:42 +00003448void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3449 Step S;
3450 S.Kind = SK_StdInitializerList;
3451 S.Type = T;
3452 Steps.push_back(S);
3453}
3454
Guy Benyei61054192013-02-07 10:55:47 +00003455void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3456 Step S;
3457 S.Kind = SK_OCLSamplerInit;
3458 S.Type = T;
3459 Steps.push_back(S);
3460}
3461
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003462void InitializationSequence::AddOCLZeroEventStep(QualType T) {
3463 Step S;
3464 S.Kind = SK_OCLZeroEvent;
3465 S.Type = T;
3466 Steps.push_back(S);
3467}
3468
Egor Churaev89831422016-12-23 14:55:49 +00003469void InitializationSequence::AddOCLZeroQueueStep(QualType T) {
3470 Step S;
3471 S.Kind = SK_OCLZeroQueue;
3472 S.Type = T;
3473 Steps.push_back(S);
3474}
3475
Sebastian Redl29526f02011-11-27 16:50:07 +00003476void InitializationSequence::RewrapReferenceInitList(QualType T,
3477 InitListExpr *Syntactic) {
3478 assert(Syntactic->getNumInits() == 1 &&
3479 "Can only rewrap trivial init lists.");
3480 Step S;
3481 S.Kind = SK_UnwrapInitList;
3482 S.Type = Syntactic->getInit(0)->getType();
3483 Steps.insert(Steps.begin(), S);
3484
3485 S.Kind = SK_RewrapInitList;
3486 S.Type = T;
3487 S.WrappingSyntacticList = Syntactic;
3488 Steps.push_back(S);
3489}
3490
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003491void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003492 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00003493 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003494 this->Failure = Failure;
3495 this->FailedOverloadResult = Result;
3496}
3497
3498//===----------------------------------------------------------------------===//
3499// Attempt initialization
3500//===----------------------------------------------------------------------===//
3501
Nico Weber337d5aa2015-04-17 08:32:38 +00003502/// Tries to add a zero initializer. Returns true if that worked.
3503static bool
3504maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
3505 const InitializedEntity &Entity) {
3506 if (Entity.getKind() != InitializedEntity::EK_Variable)
3507 return false;
3508
3509 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
3510 if (VD->getInit() || VD->getLocEnd().isMacroID())
3511 return false;
3512
3513 QualType VariableTy = VD->getType().getCanonicalType();
3514 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
3515 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3516 if (!Init.empty()) {
3517 Sequence.AddZeroInitializationStep(Entity.getType());
3518 Sequence.SetZeroInitializationFixit(Init, Loc);
3519 return true;
3520 }
3521 return false;
3522}
3523
John McCall31168b02011-06-15 23:02:42 +00003524static void MaybeProduceObjCObject(Sema &S,
3525 InitializationSequence &Sequence,
3526 const InitializedEntity &Entity) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003527 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCall31168b02011-06-15 23:02:42 +00003528
3529 /// When initializing a parameter, produce the value if it's marked
3530 /// __attribute__((ns_consumed)).
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003531 if (Entity.isParameterKind()) {
John McCall31168b02011-06-15 23:02:42 +00003532 if (!Entity.isParameterConsumed())
3533 return;
3534
3535 assert(Entity.getType()->isObjCRetainableType() &&
3536 "consuming an object of unretainable type?");
3537 Sequence.AddProduceObjCObjectStep(Entity.getType());
3538
3539 /// When initializing a return value, if the return type is a
3540 /// retainable type, then returns need to immediately retain the
3541 /// object. If an autorelease is required, it will be done at the
3542 /// last instant.
Richard Smith67af95b2018-07-23 19:19:08 +00003543 } else if (Entity.getKind() == InitializedEntity::EK_Result ||
3544 Entity.getKind() == InitializedEntity::EK_StmtExprResult) {
John McCall31168b02011-06-15 23:02:42 +00003545 if (!Entity.getType()->isObjCRetainableType())
3546 return;
3547
3548 Sequence.AddProduceObjCObjectStep(Entity.getType());
3549 }
3550}
3551
Richard Smithcc1b96d2013-06-12 22:31:48 +00003552static void TryListInitialization(Sema &S,
3553 const InitializedEntity &Entity,
3554 const InitializationKind &Kind,
3555 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00003556 InitializationSequence &Sequence,
3557 bool TreatUnavailableAsInvalid);
Richard Smithcc1b96d2013-06-12 22:31:48 +00003558
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003559/// When initializing from init list via constructor, handle
Richard Smithd86812d2012-07-05 08:39:21 +00003560/// initialization of an object of type std::initializer_list<T>.
Sebastian Redled2e5322011-12-22 14:44:04 +00003561///
Richard Smithd86812d2012-07-05 08:39:21 +00003562/// \return true if we have handled initialization of an object of type
3563/// std::initializer_list<T>, false otherwise.
3564static bool TryInitializerListConstruction(Sema &S,
3565 InitListExpr *List,
3566 QualType DestType,
Manman Ren073db022016-03-10 18:53:19 +00003567 InitializationSequence &Sequence,
3568 bool TreatUnavailableAsInvalid) {
Richard Smithd86812d2012-07-05 08:39:21 +00003569 QualType E;
3570 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1bfe0682012-02-14 21:14:13 +00003571 return false;
3572
Richard Smithdb0ac552015-12-18 22:40:25 +00003573 if (!S.isCompleteType(List->getExprLoc(), E)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00003574 Sequence.setIncompleteTypeFailure(E);
3575 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003576 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00003577
3578 // Try initializing a temporary array from the init list.
3579 QualType ArrayType = S.Context.getConstantArrayType(
3580 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3581 List->getNumInits()),
3582 clang::ArrayType::Normal, 0);
3583 InitializedEntity HiddenArray =
3584 InitializedEntity::InitializeTemporary(ArrayType);
Vedant Kumara14a1f92018-01-17 18:53:51 +00003585 InitializationKind Kind = InitializationKind::CreateDirectList(
3586 List->getExprLoc(), List->getLocStart(), List->getLocEnd());
Manman Ren073db022016-03-10 18:53:19 +00003587 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
3588 TreatUnavailableAsInvalid);
Richard Smithcc1b96d2013-06-12 22:31:48 +00003589 if (Sequence)
3590 Sequence.AddStdInitializerListConstructionStep(DestType);
Richard Smithd86812d2012-07-05 08:39:21 +00003591 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003592}
3593
Richard Smith7c2bcc92016-09-07 02:14:33 +00003594/// Determine if the constructor has the signature of a copy or move
3595/// constructor for the type T of the class in which it was found. That is,
3596/// determine if its first parameter is of type T or reference to (possibly
3597/// cv-qualified) T.
3598static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
3599 const ConstructorInfo &Info) {
3600 if (Info.Constructor->getNumParams() == 0)
3601 return false;
3602
3603 QualType ParmT =
3604 Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
3605 QualType ClassT =
3606 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
3607
3608 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
3609}
3610
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003611static OverloadingResult
3612ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003613 MultiExprArg Args,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003614 OverloadCandidateSet &CandidateSet,
Richard Smith67ef14f2017-09-26 18:37:55 +00003615 QualType DestType,
Richard Smith40c78062015-02-21 02:31:57 +00003616 DeclContext::lookup_result Ctors,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003617 OverloadCandidateSet::iterator &Best,
3618 bool CopyInitializing, bool AllowExplicit,
Richard Smith7c2bcc92016-09-07 02:14:33 +00003619 bool OnlyListConstructors, bool IsListInit,
3620 bool SecondStepOfCopyInit = false) {
Richard Smith67ef14f2017-09-26 18:37:55 +00003621 CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003622
Richard Smith40c78062015-02-21 02:31:57 +00003623 for (NamedDecl *D : Ctors) {
Richard Smithc2bebe92016-05-11 20:37:46 +00003624 auto Info = getConstructorInfo(D);
Richard Smith7c2bcc92016-09-07 02:14:33 +00003625 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
Richard Smithc2bebe92016-05-11 20:37:46 +00003626 continue;
3627
Richard Smith7c2bcc92016-09-07 02:14:33 +00003628 if (!AllowExplicit && Info.Constructor->isExplicit())
3629 continue;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003630
Richard Smith7c2bcc92016-09-07 02:14:33 +00003631 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
3632 continue;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003633
Richard Smith7c2bcc92016-09-07 02:14:33 +00003634 // C++11 [over.best.ics]p4:
3635 // ... and the constructor or user-defined conversion function is a
3636 // candidate by
3637 // - 13.3.1.3, when the argument is the temporary in the second step
3638 // of a class copy-initialization, or
3639 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
3640 // - the second phase of 13.3.1.7 when the initializer list has exactly
3641 // one element that is itself an initializer list, and the target is
3642 // the first parameter of a constructor of class X, and the conversion
3643 // is to X or reference to (possibly cv-qualified X),
3644 // user-defined conversion sequences are not considered.
3645 bool SuppressUserConversions =
3646 SecondStepOfCopyInit ||
3647 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
3648 hasCopyOrMoveCtorParam(S.Context, Info));
3649
3650 if (Info.ConstructorTmpl)
3651 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3652 /*ExplicitArgs*/ nullptr, Args,
3653 CandidateSet, SuppressUserConversions);
3654 else {
3655 // C++ [over.match.copy]p1:
3656 // - When initializing a temporary to be bound to the first parameter
3657 // of a constructor [for type T] that takes a reference to possibly
3658 // cv-qualified T as its first argument, called with a single
3659 // argument in the context of direct-initialization, explicit
3660 // conversion functions are also considered.
3661 // FIXME: What if a constructor template instantiates to such a signature?
3662 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
3663 Args.size() == 1 &&
3664 hasCopyOrMoveCtorParam(S.Context, Info);
3665 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
3666 CandidateSet, SuppressUserConversions,
3667 /*PartialOverloading=*/false,
3668 /*AllowExplicit=*/AllowExplicitConv);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003669 }
3670 }
3671
Richard Smith67ef14f2017-09-26 18:37:55 +00003672 // FIXME: Work around a bug in C++17 guaranteed copy elision.
3673 //
3674 // When initializing an object of class type T by constructor
3675 // ([over.match.ctor]) or by list-initialization ([over.match.list])
3676 // from a single expression of class type U, conversion functions of
3677 // U that convert to the non-reference type cv T are candidates.
3678 // Explicit conversion functions are only candidates during
3679 // direct-initialization.
3680 //
3681 // Note: SecondStepOfCopyInit is only ever true in this case when
3682 // evaluating whether to produce a C++98 compatibility warning.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003683 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
Richard Smith67ef14f2017-09-26 18:37:55 +00003684 !SecondStepOfCopyInit) {
3685 Expr *Initializer = Args[0];
3686 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
3687 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
3688 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
3689 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3690 NamedDecl *D = *I;
3691 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3692 D = D->getUnderlyingDecl();
3693
3694 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3695 CXXConversionDecl *Conv;
3696 if (ConvTemplate)
3697 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3698 else
3699 Conv = cast<CXXConversionDecl>(D);
3700
3701 if ((AllowExplicit && !CopyInitializing) || !Conv->isExplicit()) {
3702 if (ConvTemplate)
3703 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3704 ActingDC, Initializer, DestType,
3705 CandidateSet, AllowExplicit,
3706 /*AllowResultConversion*/false);
3707 else
3708 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
3709 DestType, CandidateSet, AllowExplicit,
3710 /*AllowResultConversion*/false);
3711 }
3712 }
3713 }
3714 }
3715
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003716 // Perform overload resolution and return the result.
3717 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3718}
3719
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003720/// Attempt initialization by constructor (C++ [dcl.init]), which
Sebastian Redled2e5322011-12-22 14:44:04 +00003721/// enumerates the constructors of the initialized entity and performs overload
3722/// resolution to select the best.
Richard Smith410306b2016-12-12 02:53:20 +00003723/// \param DestType The destination class type.
3724/// \param DestArrayType The destination type, which is either DestType or
3725/// a (possibly multidimensional) array of DestType.
NAKAMURA Takumiffcc98a2015-02-05 23:12:13 +00003726/// \param IsListInit Is this list-initialization?
Richard Smithed83ebd2015-02-05 07:02:11 +00003727/// \param IsInitListCopy Is this non-list-initialization resulting from a
3728/// list-initialization from {x} where x is the same
3729/// type as the entity?
Sebastian Redled2e5322011-12-22 14:44:04 +00003730static void TryConstructorInitialization(Sema &S,
3731 const InitializedEntity &Entity,
3732 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003733 MultiExprArg Args, QualType DestType,
Richard Smith410306b2016-12-12 02:53:20 +00003734 QualType DestArrayType,
Sebastian Redled2e5322011-12-22 14:44:04 +00003735 InitializationSequence &Sequence,
Richard Smithed83ebd2015-02-05 07:02:11 +00003736 bool IsListInit = false,
3737 bool IsInitListCopy = false) {
Richard Smith122f88d2016-12-06 23:52:28 +00003738 assert(((!IsListInit && !IsInitListCopy) ||
3739 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3740 "IsListInit/IsInitListCopy must come with a single initializer list "
3741 "argument.");
3742 InitListExpr *ILE =
3743 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
3744 MultiExprArg UnwrappedArgs =
3745 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003746
Sebastian Redled2e5322011-12-22 14:44:04 +00003747 // The type we're constructing needs to be complete.
Richard Smithdb0ac552015-12-18 22:40:25 +00003748 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003749 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003750 return;
Sebastian Redled2e5322011-12-22 14:44:04 +00003751 }
3752
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003753 // C++17 [dcl.init]p17:
Richard Smith122f88d2016-12-06 23:52:28 +00003754 // - If the initializer expression is a prvalue and the cv-unqualified
3755 // version of the source type is the same class as the class of the
3756 // destination, the initializer expression is used to initialize the
3757 // destination object.
3758 // Per DR (no number yet), this does not apply when initializing a base
3759 // class or delegating to another constructor from a mem-initializer.
Alex Lorenzb4791c72017-04-06 12:53:43 +00003760 // ObjC++: Lambda captured by the block in the lambda to block conversion
3761 // should avoid copy elision.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003762 if (S.getLangOpts().CPlusPlus17 &&
Richard Smith122f88d2016-12-06 23:52:28 +00003763 Entity.getKind() != InitializedEntity::EK_Base &&
3764 Entity.getKind() != InitializedEntity::EK_Delegating &&
Alex Lorenzb4791c72017-04-06 12:53:43 +00003765 Entity.getKind() !=
3766 InitializedEntity::EK_LambdaToBlockConversionBlockElement &&
Richard Smith122f88d2016-12-06 23:52:28 +00003767 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isRValue() &&
3768 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
3769 // Convert qualifications if necessary.
Richard Smith16d31502016-12-21 01:31:56 +00003770 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Richard Smith122f88d2016-12-06 23:52:28 +00003771 if (ILE)
3772 Sequence.RewrapReferenceInitList(DestType, ILE);
3773 return;
3774 }
3775
Sebastian Redled2e5322011-12-22 14:44:04 +00003776 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3777 assert(DestRecordType && "Constructor initialization requires record type");
3778 CXXRecordDecl *DestRecordDecl
3779 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3780
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003781 // Build the candidate set directly in the initialization sequence
3782 // structure, so that it will persist if we fail.
3783 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3784
3785 // Determine whether we are allowed to call explicit constructors or
3786 // explicit conversion operators.
Richard Smithed83ebd2015-02-05 07:02:11 +00003787 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003788 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003789
Sebastian Redled2e5322011-12-22 14:44:04 +00003790 // - Otherwise, if T is a class type, constructors are considered. The
3791 // applicable constructors are enumerated, and the best one is chosen
3792 // through overload resolution.
Richard Smith40c78062015-02-21 02:31:57 +00003793 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
Sebastian Redled2e5322011-12-22 14:44:04 +00003794
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003795 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redled2e5322011-12-22 14:44:04 +00003796 OverloadCandidateSet::iterator Best;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003797 bool AsInitializerList = false;
3798
Larisse Voufo19d08672015-01-27 18:47:05 +00003799 // C++11 [over.match.list]p1, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00003800 // When objects of non-aggregate type T are list-initialized, such that
3801 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
3802 // according to the rules in this section, overload resolution selects
3803 // the constructor in two phases:
3804 //
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003805 // - Initially, the candidate functions are the initializer-list
3806 // constructors of the class T and the argument list consists of the
3807 // initializer list as a single argument.
Richard Smithed83ebd2015-02-05 07:02:11 +00003808 if (IsListInit) {
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003809 AsInitializerList = true;
Richard Smithd86812d2012-07-05 08:39:21 +00003810
3811 // If the initializer list has no elements and T has a default constructor,
3812 // the first phase is omitted.
Richard Smith122f88d2016-12-06 23:52:28 +00003813 if (!(UnwrappedArgs.empty() && DestRecordDecl->hasDefaultConstructor()))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003814 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Richard Smith67ef14f2017-09-26 18:37:55 +00003815 CandidateSet, DestType, Ctors, Best,
Richard Smithd86812d2012-07-05 08:39:21 +00003816 CopyInitialization, AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003817 /*OnlyListConstructor=*/true,
3818 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003819 }
3820
3821 // C++11 [over.match.list]p1:
3822 // - If no viable initializer-list constructor is found, overload resolution
3823 // is performed again, where the candidate functions are all the
Richard Smithd86812d2012-07-05 08:39:21 +00003824 // constructors of the class T and the argument list consists of the
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003825 // elements of the initializer list.
3826 if (Result == OR_No_Viable_Function) {
3827 AsInitializerList = false;
Richard Smith122f88d2016-12-06 23:52:28 +00003828 Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs,
Richard Smith67ef14f2017-09-26 18:37:55 +00003829 CandidateSet, DestType, Ctors, Best,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003830 CopyInitialization, AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003831 /*OnlyListConstructors=*/false,
3832 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003833 }
3834 if (Result) {
Richard Smithed83ebd2015-02-05 07:02:11 +00003835 Sequence.SetOverloadFailure(IsListInit ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003836 InitializationSequence::FK_ListConstructorOverloadFailed :
3837 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00003838 Result);
3839 return;
3840 }
3841
Richard Smith67ef14f2017-09-26 18:37:55 +00003842 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3843
3844 // In C++17, ResolveConstructorOverload can select a conversion function
3845 // instead of a constructor.
3846 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
3847 // Add the user-defined conversion step that calls the conversion function.
3848 QualType ConvType = CD->getConversionType();
3849 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
3850 "should not have selected this conversion function");
3851 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
3852 HadMultipleCandidates);
3853 if (!S.Context.hasSameType(ConvType, DestType))
3854 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
3855 if (IsListInit)
3856 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
3857 return;
3858 }
3859
Richard Smithd86812d2012-07-05 08:39:21 +00003860 // C++11 [dcl.init]p6:
Sebastian Redled2e5322011-12-22 14:44:04 +00003861 // If a program calls for the default initialization of an object
3862 // of a const-qualified type T, T shall be a class type with a
3863 // user-provided default constructor.
Nico Weber6a6376b2016-02-19 01:52:46 +00003864 // C++ core issue 253 proposal:
3865 // If the implicit default constructor initializes all subobjects, no
3866 // initializer should be required.
3867 // The 253 proposal is for example needed to process libstdc++ headers in 5.x.
3868 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redled2e5322011-12-22 14:44:04 +00003869 if (Kind.getKind() == InitializationKind::IK_Default &&
Nico Weber6a6376b2016-02-19 01:52:46 +00003870 Entity.getType().isConstQualified()) {
3871 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
3872 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
3873 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3874 return;
3875 }
Sebastian Redled2e5322011-12-22 14:44:04 +00003876 }
3877
Sebastian Redl048a6d72012-04-01 19:54:59 +00003878 // C++11 [over.match.list]p1:
3879 // In copy-list-initialization, if an explicit constructor is chosen, the
3880 // initializer is ill-formed.
Richard Smithed83ebd2015-02-05 07:02:11 +00003881 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
Sebastian Redl048a6d72012-04-01 19:54:59 +00003882 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3883 return;
3884 }
3885
Sebastian Redled2e5322011-12-22 14:44:04 +00003886 // Add the constructor initialization step. Any cv-qualification conversion is
3887 // subsumed by the initialization.
Richard Smithed83ebd2015-02-05 07:02:11 +00003888 Sequence.AddConstructorInitializationStep(
Richard Smith410306b2016-12-12 02:53:20 +00003889 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
Richard Smithed83ebd2015-02-05 07:02:11 +00003890 IsListInit | IsInitListCopy, AsInitializerList);
Sebastian Redled2e5322011-12-22 14:44:04 +00003891}
3892
Sebastian Redl29526f02011-11-27 16:50:07 +00003893static bool
3894ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3895 Expr *Initializer,
3896 QualType &SourceType,
3897 QualType &UnqualifiedSourceType,
3898 QualType UnqualifiedTargetType,
3899 InitializationSequence &Sequence) {
3900 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3901 S.Context.OverloadTy) {
3902 DeclAccessPair Found;
3903 bool HadMultipleCandidates = false;
3904 if (FunctionDecl *Fn
3905 = S.ResolveAddressOfOverloadedFunction(Initializer,
3906 UnqualifiedTargetType,
3907 false, Found,
3908 &HadMultipleCandidates)) {
3909 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3910 HadMultipleCandidates);
3911 SourceType = Fn->getType();
3912 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3913 } else if (!UnqualifiedTargetType->isRecordType()) {
3914 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3915 return true;
3916 }
3917 }
3918 return false;
3919}
3920
3921static void TryReferenceInitializationCore(Sema &S,
3922 const InitializedEntity &Entity,
3923 const InitializationKind &Kind,
3924 Expr *Initializer,
3925 QualType cv1T1, QualType T1,
3926 Qualifiers T1Quals,
3927 QualType cv2T2, QualType T2,
3928 Qualifiers T2Quals,
3929 InitializationSequence &Sequence);
3930
Richard Smithd86812d2012-07-05 08:39:21 +00003931static void TryValueInitialization(Sema &S,
3932 const InitializedEntity &Entity,
3933 const InitializationKind &Kind,
3934 InitializationSequence &Sequence,
Craig Topperc3ec1492014-05-26 06:22:03 +00003935 InitListExpr *InitList = nullptr);
Richard Smithd86812d2012-07-05 08:39:21 +00003936
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003937/// Attempt list initialization of a reference.
Sebastian Redl29526f02011-11-27 16:50:07 +00003938static void TryReferenceListInitialization(Sema &S,
3939 const InitializedEntity &Entity,
3940 const InitializationKind &Kind,
3941 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00003942 InitializationSequence &Sequence,
3943 bool TreatUnavailableAsInvalid) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003944 // First, catch C++03 where this isn't possible.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003945 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003946 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3947 return;
3948 }
David Majnemer9370dc22015-04-26 07:35:03 +00003949 // Can't reference initialize a compound literal.
3950 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
3951 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3952 return;
3953 }
Sebastian Redl29526f02011-11-27 16:50:07 +00003954
3955 QualType DestType = Entity.getType();
3956 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3957 Qualifiers T1Quals;
3958 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3959
3960 // Reference initialization via an initializer list works thus:
3961 // If the initializer list consists of a single element that is
3962 // reference-related to the referenced type, bind directly to that element
3963 // (possibly creating temporaries).
3964 // Otherwise, initialize a temporary with the initializer list and
3965 // bind to that.
3966 if (InitList->getNumInits() == 1) {
3967 Expr *Initializer = InitList->getInit(0);
3968 QualType cv2T2 = Initializer->getType();
3969 Qualifiers T2Quals;
3970 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3971
3972 // If this fails, creating a temporary wouldn't work either.
3973 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3974 T1, Sequence))
3975 return;
3976
3977 SourceLocation DeclLoc = Initializer->getLocStart();
3978 bool dummy1, dummy2, dummy3;
3979 Sema::ReferenceCompareResult RefRelationship
3980 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3981 dummy2, dummy3);
3982 if (RefRelationship >= Sema::Ref_Related) {
3983 // Try to bind the reference here.
3984 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3985 T1Quals, cv2T2, T2, T2Quals, Sequence);
3986 if (Sequence)
3987 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3988 return;
3989 }
Richard Smith03d93932013-01-15 07:58:29 +00003990
3991 // Update the initializer if we've resolved an overloaded function.
3992 if (Sequence.step_begin() != Sequence.step_end())
3993 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl29526f02011-11-27 16:50:07 +00003994 }
3995
3996 // Not reference-related. Create a temporary and bind to that.
3997 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3998
Manman Ren073db022016-03-10 18:53:19 +00003999 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
4000 TreatUnavailableAsInvalid);
Sebastian Redl29526f02011-11-27 16:50:07 +00004001 if (Sequence) {
4002 if (DestType->isRValueReferenceType() ||
4003 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
4004 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
4005 else
4006 Sequence.SetFailed(
4007 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4008 }
4009}
4010
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004011/// Attempt list initialization (C++0x [dcl.init.list])
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004012static void TryListInitialization(Sema &S,
4013 const InitializedEntity &Entity,
4014 const InitializationKind &Kind,
4015 InitListExpr *InitList,
Manman Ren073db022016-03-10 18:53:19 +00004016 InitializationSequence &Sequence,
4017 bool TreatUnavailableAsInvalid) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004018 QualType DestType = Entity.getType();
4019
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004020 // C++ doesn't allow scalar initialization with more than one argument.
4021 // But C99 complex numbers are scalars and it makes sense there.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004022 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004023 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4024 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
4025 return;
4026 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004027 if (DestType->isReferenceType()) {
Manman Ren073db022016-03-10 18:53:19 +00004028 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4029 TreatUnavailableAsInvalid);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004030 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004031 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00004032
Larisse Voufod2010992015-01-24 23:09:54 +00004033 if (DestType->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004034 !S.isCompleteType(InitList->getLocStart(), DestType)) {
Larisse Voufod2010992015-01-24 23:09:54 +00004035 Sequence.setIncompleteTypeFailure(DestType);
4036 return;
4037 }
Richard Smithd86812d2012-07-05 08:39:21 +00004038
Larisse Voufo19d08672015-01-27 18:47:05 +00004039 // C++11 [dcl.init.list]p3, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00004040 // - If T is a class type and the initializer list has a single element of
4041 // type cv U, where U is T or a class derived from T, the object is
4042 // initialized from that element (by copy-initialization for
4043 // copy-list-initialization, or by direct-initialization for
4044 // direct-list-initialization).
4045 // - Otherwise, if T is a character array and the initializer list has a
4046 // single element that is an appropriately-typed string literal
4047 // (8.5.2 [dcl.init.string]), initialization is performed as described
4048 // in that section.
Larisse Voufo19d08672015-01-27 18:47:05 +00004049 // - Otherwise, if T is an aggregate, [...] (continue below).
4050 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
Larisse Voufod2010992015-01-24 23:09:54 +00004051 if (DestType->isRecordType()) {
4052 QualType InitType = InitList->getInit(0)->getType();
4053 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004054 S.IsDerivedFrom(InitList->getLocStart(), InitType, DestType)) {
Richard Smith122f88d2016-12-06 23:52:28 +00004055 Expr *InitListAsExpr = InitList;
4056 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smith410306b2016-12-12 02:53:20 +00004057 DestType, Sequence,
4058 /*InitListSyntax*/false,
4059 /*IsInitListCopy*/true);
Larisse Voufod2010992015-01-24 23:09:54 +00004060 return;
4061 }
4062 }
4063 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4064 Expr *SubInit[1] = {InitList->getInit(0)};
4065 if (!isa<VariableArrayType>(DestAT) &&
4066 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4067 InitializationKind SubKind =
4068 Kind.getKind() == InitializationKind::IK_DirectList
4069 ? InitializationKind::CreateDirect(Kind.getLocation(),
4070 InitList->getLBraceLoc(),
4071 InitList->getRBraceLoc())
4072 : Kind;
4073 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
Manman Ren073db022016-03-10 18:53:19 +00004074 /*TopLevelOfInitList*/ true,
4075 TreatUnavailableAsInvalid);
Larisse Voufod2010992015-01-24 23:09:54 +00004076
4077 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4078 // the element is not an appropriately-typed string literal, in which
4079 // case we should proceed as in C++11 (below).
4080 if (Sequence) {
4081 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4082 return;
4083 }
4084 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00004085 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004086 }
Larisse Voufod2010992015-01-24 23:09:54 +00004087
4088 // C++11 [dcl.init.list]p3:
4089 // - If T is an aggregate, aggregate initialization is performed.
Faisal Vali30622bb2015-12-07 02:37:44 +00004090 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4091 (S.getLangOpts().CPlusPlus11 &&
4092 S.isStdInitializerList(DestType, nullptr))) {
Larisse Voufod2010992015-01-24 23:09:54 +00004093 if (S.getLangOpts().CPlusPlus11) {
4094 // - Otherwise, if the initializer list has no elements and T is a
4095 // class type with a default constructor, the object is
4096 // value-initialized.
4097 if (InitList->getNumInits() == 0) {
4098 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4099 if (RD->hasDefaultConstructor()) {
4100 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4101 return;
4102 }
4103 }
4104
4105 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4106 // an initializer_list object constructed [...]
Manman Ren073db022016-03-10 18:53:19 +00004107 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4108 TreatUnavailableAsInvalid))
Larisse Voufod2010992015-01-24 23:09:54 +00004109 return;
4110
4111 // - Otherwise, if T is a class type, constructors are considered.
4112 Expr *InitListAsExpr = InitList;
4113 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smith410306b2016-12-12 02:53:20 +00004114 DestType, Sequence, /*InitListSyntax*/true);
Larisse Voufod2010992015-01-24 23:09:54 +00004115 } else
4116 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
4117 return;
4118 }
4119
Richard Smith089c3162013-09-21 21:55:46 +00004120 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
Richard Smithed638862016-03-28 06:08:37 +00004121 InitList->getNumInits() == 1) {
4122 Expr *E = InitList->getInit(0);
4123
4124 // - Otherwise, if T is an enumeration with a fixed underlying type,
4125 // the initializer-list has a single element v, and the initialization
4126 // is direct-list-initialization, the object is initialized with the
4127 // value T(v); if a narrowing conversion is required to convert v to
4128 // the underlying type of T, the program is ill-formed.
4129 auto *ET = DestType->getAs<EnumType>();
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004130 if (S.getLangOpts().CPlusPlus17 &&
Richard Smithed638862016-03-28 06:08:37 +00004131 Kind.getKind() == InitializationKind::IK_DirectList &&
4132 ET && ET->getDecl()->isFixed() &&
4133 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4134 (E->getType()->isIntegralOrEnumerationType() ||
4135 E->getType()->isFloatingType())) {
4136 // There are two ways that T(v) can work when T is an enumeration type.
4137 // If there is either an implicit conversion sequence from v to T or
4138 // a conversion function that can convert from v to T, then we use that.
4139 // Otherwise, if v is of integral, enumeration, or floating-point type,
4140 // it is converted to the enumeration type via its underlying type.
4141 // There is no overlap possible between these two cases (except when the
4142 // source value is already of the destination type), and the first
4143 // case is handled by the general case for single-element lists below.
4144 ImplicitConversionSequence ICS;
4145 ICS.setStandard();
4146 ICS.Standard.setAsIdentityConversion();
Vedant Kumarf4217f82017-02-16 01:20:00 +00004147 if (!E->isRValue())
4148 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
Richard Smithed638862016-03-28 06:08:37 +00004149 // If E is of a floating-point type, then the conversion is ill-formed
4150 // due to narrowing, but go through the motions in order to produce the
4151 // right diagnostic.
4152 ICS.Standard.Second = E->getType()->isFloatingType()
4153 ? ICK_Floating_Integral
4154 : ICK_Integral_Conversion;
4155 ICS.Standard.setFromType(E->getType());
4156 ICS.Standard.setToType(0, E->getType());
4157 ICS.Standard.setToType(1, DestType);
4158 ICS.Standard.setToType(2, DestType);
4159 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4160 /*TopLevelOfInitList*/true);
4161 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4162 return;
4163 }
4164
Richard Smith089c3162013-09-21 21:55:46 +00004165 // - Otherwise, if the initializer list has a single element of type E
4166 // [...references are handled above...], the object or reference is
Larisse Voufod2010992015-01-24 23:09:54 +00004167 // initialized from that element (by copy-initialization for
4168 // copy-list-initialization, or by direct-initialization for
4169 // direct-list-initialization); if a narrowing conversion is required
4170 // to convert the element to T, the program is ill-formed.
4171 //
Richard Smith089c3162013-09-21 21:55:46 +00004172 // Per core-24034, this is direct-initialization if we were performing
4173 // direct-list-initialization and copy-initialization otherwise.
4174 // We can't use InitListChecker for this, because it always performs
4175 // copy-initialization. This only matters if we might use an 'explicit'
4176 // conversion operator, so we only need to handle the cases where the source
4177 // is of record type.
Richard Smithed638862016-03-28 06:08:37 +00004178 if (InitList->getInit(0)->getType()->isRecordType()) {
4179 InitializationKind SubKind =
4180 Kind.getKind() == InitializationKind::IK_DirectList
4181 ? InitializationKind::CreateDirect(Kind.getLocation(),
4182 InitList->getLBraceLoc(),
4183 InitList->getRBraceLoc())
4184 : Kind;
4185 Expr *SubInit[1] = { InitList->getInit(0) };
4186 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4187 /*TopLevelOfInitList*/true,
4188 TreatUnavailableAsInvalid);
4189 if (Sequence)
4190 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4191 return;
4192 }
Richard Smith089c3162013-09-21 21:55:46 +00004193 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004194
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004195 InitListChecker CheckInitList(S, Entity, InitList,
Manman Ren073db022016-03-10 18:53:19 +00004196 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004197 if (CheckInitList.HadError()) {
4198 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
4199 return;
4200 }
4201
4202 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004203 Sequence.AddListInitializationStep(DestType);
4204}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004205
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004206/// Try a reference initialization that involves calling a conversion
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004207/// function.
Richard Smithb8c0f552016-12-09 18:49:13 +00004208static OverloadingResult TryRefInitWithConversionFunction(
4209 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4210 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4211 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004212 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004213 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4214 QualType T1 = cv1T1.getUnqualifiedType();
4215 QualType cv2T2 = Initializer->getType();
4216 QualType T2 = cv2T2.getUnqualifiedType();
4217
4218 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004219 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00004220 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004221 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004222 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004223 ObjCConversion,
4224 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004225 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00004226 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004227 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00004228 (void)ObjCLifetimeConversion;
4229
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004230 // Build the candidate set directly in the initialization sequence
4231 // structure, so that it will persist if we fail.
4232 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
Richard Smith67ef14f2017-09-26 18:37:55 +00004233 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004234
Richard Smithb368ea82018-07-02 23:25:22 +00004235 // Determine whether we are allowed to call explicit conversion operators.
4236 // Note that none of [over.match.copy], [over.match.conv], nor
4237 // [over.match.ref] permit an explicit constructor to be chosen when
4238 // initializing a reference, not even for direct-initialization.
4239 bool AllowExplicitCtors = false;
Richard Smith6c6ddab2013-09-21 21:23:47 +00004240 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4241
Craig Topperc3ec1492014-05-26 06:22:03 +00004242 const RecordType *T1RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00004243 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004244 S.isCompleteType(Kind.getLocation(), T1)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004245 // The type we're converting to is a class type. Enumerate its constructors
4246 // to see if there is a suitable conversion.
4247 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00004248
Richard Smith40c78062015-02-21 02:31:57 +00004249 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
Richard Smithc2bebe92016-05-11 20:37:46 +00004250 auto Info = getConstructorInfo(D);
4251 if (!Info.Constructor)
4252 continue;
John McCalla0296f72010-03-19 07:35:19 +00004253
Richard Smithc2bebe92016-05-11 20:37:46 +00004254 if (!Info.Constructor->isInvalidDecl() &&
Richard Smithb368ea82018-07-02 23:25:22 +00004255 Info.Constructor->isConvertingConstructor(AllowExplicitCtors)) {
Richard Smithc2bebe92016-05-11 20:37:46 +00004256 if (Info.ConstructorTmpl)
4257 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004258 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004259 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00004260 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004261 else
Richard Smithc2bebe92016-05-11 20:37:46 +00004262 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004263 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00004264 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004265 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004266 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004267 }
John McCall3696dcb2010-08-17 07:23:57 +00004268 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4269 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004270
Craig Topperc3ec1492014-05-26 06:22:03 +00004271 const RecordType *T2RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00004272 if ((T2RecordType = T2->getAs<RecordType>()) &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004273 S.isCompleteType(Kind.getLocation(), T2)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004274 // The type we're converting from is a class type, enumerate its conversion
4275 // functions.
4276 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4277
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004278 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4279 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004280 NamedDecl *D = *I;
4281 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4282 if (isa<UsingShadowDecl>(D))
4283 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004284
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004285 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4286 CXXConversionDecl *Conv;
4287 if (ConvTemplate)
4288 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4289 else
Sebastian Redld92badf2010-06-30 18:13:39 +00004290 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004291
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004292 // If the conversion function doesn't return a reference type,
4293 // it can't be considered for this conversion unless we're allowed to
4294 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004295 // FIXME: Do we need to make sure that we only consider conversion
4296 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004297 // break recursion.
Douglas Gregor6073dca2012-02-24 23:56:31 +00004298 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004299 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
4300 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004301 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004302 ActingDC, Initializer,
Douglas Gregor68782142013-12-18 21:46:16 +00004303 DestType, CandidateSet,
4304 /*AllowObjCConversionOnExplicit=*/
4305 false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004306 else
John McCalla0296f72010-03-19 07:35:19 +00004307 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004308 Initializer, DestType, CandidateSet,
4309 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004310 }
4311 }
4312 }
John McCall3696dcb2010-08-17 07:23:57 +00004313 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4314 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004315
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004316 SourceLocation DeclLoc = Initializer->getLocStart();
4317
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004318 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004319 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004320 if (OverloadingResult Result
Richard Smith67ef14f2017-09-26 18:37:55 +00004321 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004322 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004323
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004324 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004325 // This is the overload that will be used for this initialization step if we
4326 // use this initialization. Mark it as referenced.
4327 Function->setReferenced();
Chandler Carruth30141632011-02-25 19:41:05 +00004328
Richard Smithb8c0f552016-12-09 18:49:13 +00004329 // Compute the returned type and value kind of the conversion.
4330 QualType cv3T3;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004331 if (isa<CXXConversionDecl>(Function))
Richard Smithb8c0f552016-12-09 18:49:13 +00004332 cv3T3 = Function->getReturnType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004333 else
Richard Smithb8c0f552016-12-09 18:49:13 +00004334 cv3T3 = T1;
4335
4336 ExprValueKind VK = VK_RValue;
4337 if (cv3T3->isLValueReferenceType())
4338 VK = VK_LValue;
4339 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4340 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4341 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004342
4343 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004344 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Richard Smithb8c0f552016-12-09 18:49:13 +00004345 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004346 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00004347
Richard Smithb8c0f552016-12-09 18:49:13 +00004348 // Determine whether we'll need to perform derived-to-base adjustments or
4349 // other conversions.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004350 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004351 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004352 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004353 Sema::ReferenceCompareResult NewRefRelationship
Richard Smithb8c0f552016-12-09 18:49:13 +00004354 = S.CompareReferenceRelationship(DeclLoc, T1, cv3T3,
John McCall31168b02011-06-15 23:02:42 +00004355 NewDerivedToBase, NewObjCConversion,
4356 NewObjCLifetimeConversion);
Richard Smithb8c0f552016-12-09 18:49:13 +00004357
4358 // Add the final conversion sequence, if necessary.
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00004359 if (NewRefRelationship == Sema::Ref_Incompatible) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004360 assert(!isa<CXXConstructorDecl>(Function) &&
4361 "should not have conversion after constructor");
4362
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00004363 ImplicitConversionSequence ICS;
4364 ICS.setStandard();
4365 ICS.Standard = Best->FinalConversion;
Richard Smithb8c0f552016-12-09 18:49:13 +00004366 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4367
4368 // Every implicit conversion results in a prvalue, except for a glvalue
4369 // derived-to-base conversion, which we handle below.
4370 cv3T3 = ICS.Standard.getToType(2);
4371 VK = VK_RValue;
4372 }
4373
4374 // If the converted initializer is a prvalue, its type T4 is adjusted to
4375 // type "cv1 T4" and the temporary materialization conversion is applied.
4376 //
4377 // We adjust the cv-qualifications to match the reference regardless of
4378 // whether we have a prvalue so that the AST records the change. In this
4379 // case, T4 is "cv3 T3".
4380 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4381 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4382 Sequence.AddQualificationConversionStep(cv1T4, VK);
4383 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue);
4384 VK = IsLValueRef ? VK_LValue : VK_XValue;
4385
4386 if (NewDerivedToBase)
4387 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004388 else if (NewObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004389 Sequence.AddObjCObjectConversionStep(cv1T1);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004390
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004391 return OR_Success;
4392}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004393
Richard Smithc620f552011-10-19 16:55:56 +00004394static void CheckCXX98CompatAccessibleCopy(Sema &S,
4395 const InitializedEntity &Entity,
4396 Expr *CurInitExpr);
4397
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004398/// Attempt reference initialization (C++0x [dcl.init.ref])
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004399static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004400 const InitializedEntity &Entity,
4401 const InitializationKind &Kind,
4402 Expr *Initializer,
4403 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004404 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004405 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00004406 Qualifiers T1Quals;
4407 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004408 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00004409 Qualifiers T2Quals;
4410 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00004411
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004412 // If the initializer is the address of an overloaded function, try
4413 // to resolve the overloaded function. If all goes well, T2 is the
4414 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00004415 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4416 T1, Sequence))
4417 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00004418
Sebastian Redl29526f02011-11-27 16:50:07 +00004419 // Delegate everything else to a subfunction.
4420 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4421 T1Quals, cv2T2, T2, T2Quals, Sequence);
4422}
4423
Richard Smithb8c0f552016-12-09 18:49:13 +00004424/// Determine whether an expression is a non-referenceable glvalue (one to
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004425/// which a reference can never bind). Attempting to bind a reference to
Richard Smithb8c0f552016-12-09 18:49:13 +00004426/// such a glvalue will always create a temporary.
4427static bool isNonReferenceableGLValue(Expr *E) {
4428 return E->refersToBitField() || E->refersToVectorElement();
Jordan Roseb1312a52013-04-11 00:58:58 +00004429}
4430
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004431/// Reference initialization without resolving overloaded functions.
Sebastian Redl29526f02011-11-27 16:50:07 +00004432static void TryReferenceInitializationCore(Sema &S,
4433 const InitializedEntity &Entity,
4434 const InitializationKind &Kind,
4435 Expr *Initializer,
4436 QualType cv1T1, QualType T1,
4437 Qualifiers T1Quals,
4438 QualType cv2T2, QualType T2,
4439 Qualifiers T2Quals,
4440 InitializationSequence &Sequence) {
4441 QualType DestType = Entity.getType();
4442 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004443 // Compute some basic properties of the types and the initializer.
4444 bool isLValueRef = DestType->isLValueReferenceType();
4445 bool isRValueRef = !isLValueRef;
4446 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004447 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004448 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004449 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004450 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004451 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004452 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00004453
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004454 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004455 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004456 // "cv2 T2" as follows:
4457 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004458 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004459 // expression
Richard Smith6c6ddab2013-09-21 21:23:47 +00004460 // Note the analogous bullet points for rvalue refs to functions. Because
Sebastian Redld92badf2010-06-30 18:13:39 +00004461 // there are no function rvalues in C++, rvalue refs to functions are treated
4462 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004463 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00004464 bool T1Function = T1->isFunctionType();
4465 if (isLValueRef || T1Function) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004466 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
Richard Smithce766292016-10-21 23:01:55 +00004467 (RefRelationship == Sema::Ref_Compatible ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004468 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004469 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004470 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004471 // reference-compatible with "cv2 T2," or
Richard Smithb8c0f552016-12-09 18:49:13 +00004472 if (T1Quals != T2Quals)
4473 // Convert to cv1 T2. This should only add qualifiers unless this is a
4474 // c-style cast. The removal of qualifiers in that case notionally
4475 // happens after the reference binding, but that doesn't matter.
4476 Sequence.AddQualificationConversionStep(
4477 S.Context.getQualifiedType(T2, T1Quals),
4478 Initializer->getValueKind());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004479 if (DerivedToBase)
Richard Smithb8c0f552016-12-09 18:49:13 +00004480 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004481 else if (ObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004482 Sequence.AddObjCObjectConversionStep(cv1T1);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004483
Richard Smithb8c0f552016-12-09 18:49:13 +00004484 // We only create a temporary here when binding a reference to a
4485 // bit-field or vector element. Those cases are't supposed to be
4486 // handled by this bullet, but the outcome is the same either way.
4487 Sequence.AddReferenceBindingStep(cv1T1, false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004488 return;
4489 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004490
4491 // - has a class type (i.e., T2 is a class type), where T1 is not
4492 // reference-related to T2, and can be implicitly converted to an
4493 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
4494 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004495 // applicable conversion functions (13.3.1.6) and choosing the best
4496 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00004497 // If we have an rvalue ref to function type here, the rhs must be
Richard Smith6c6ddab2013-09-21 21:23:47 +00004498 // an rvalue. DR1287 removed the "implicitly" here.
Sebastian Redld92badf2010-06-30 18:13:39 +00004499 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
4500 (isLValueRef || InitCategory.isRValue())) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00004501 ConvOvlResult = TryRefInitWithConversionFunction(
Richard Smithb8c0f552016-12-09 18:49:13 +00004502 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
4503 /*IsLValueRef*/ isLValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004504 if (ConvOvlResult == OR_Success)
4505 return;
Richard Smith6c6ddab2013-09-21 21:23:47 +00004506 if (ConvOvlResult != OR_No_Viable_Function)
John McCall0d1da222010-01-12 00:44:57 +00004507 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00004508 InitializationSequence::FK_ReferenceInitOverloadFailed,
4509 ConvOvlResult);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004510 }
4511 }
Sebastian Redld92badf2010-06-30 18:13:39 +00004512
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004513 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004514 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00004515 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004516 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00004517 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4518 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4519 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004520 Sequence.SetOverloadFailure(
4521 InitializationSequence::FK_ReferenceInitOverloadFailed,
4522 ConvOvlResult);
Richard Smithb8c0f552016-12-09 18:49:13 +00004523 else if (!InitCategory.isLValue())
4524 Sequence.SetFailed(
4525 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4526 else {
4527 InitializationSequence::FailureKind FK;
4528 switch (RefRelationship) {
4529 case Sema::Ref_Compatible:
4530 if (Initializer->refersToBitField())
4531 FK = InitializationSequence::
4532 FK_NonConstLValueReferenceBindingToBitfield;
4533 else if (Initializer->refersToVectorElement())
4534 FK = InitializationSequence::
4535 FK_NonConstLValueReferenceBindingToVectorElement;
4536 else
4537 llvm_unreachable("unexpected kind of compatible initializer");
4538 break;
4539 case Sema::Ref_Related:
4540 FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
4541 break;
4542 case Sema::Ref_Incompatible:
4543 FK = InitializationSequence::
4544 FK_NonConstLValueReferenceBindingToUnrelated;
4545 break;
4546 }
4547 Sequence.SetFailed(FK);
4548 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004549 return;
4550 }
Sebastian Redld92badf2010-06-30 18:13:39 +00004551
Douglas Gregor92e460e2011-01-20 16:44:54 +00004552 // - If the initializer expression
Richard Smithb8c0f552016-12-09 18:49:13 +00004553 // - is an
4554 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
4555 // [1z] rvalue (but not a bit-field) or
4556 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
4557 //
4558 // Note: functions are handled above and below rather than here...
Douglas Gregor92e460e2011-01-20 16:44:54 +00004559 if (!T1Function &&
Richard Smithce766292016-10-21 23:01:55 +00004560 (RefRelationship == Sema::Ref_Compatible ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004561 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004562 RefRelationship == Sema::Ref_Related)) &&
Richard Smithb8c0f552016-12-09 18:49:13 +00004563 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
Richard Smith122f88d2016-12-06 23:52:28 +00004564 (InitCategory.isPRValue() &&
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004565 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
Richard Smith122f88d2016-12-06 23:52:28 +00004566 T2->isArrayType())))) {
Richard Smithb8c0f552016-12-09 18:49:13 +00004567 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_RValue;
Douglas Gregor92e460e2011-01-20 16:44:54 +00004568 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004569 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
4570 // compiler the freedom to perform a copy here or bind to the
4571 // object, while C++0x requires that we bind directly to the
4572 // object. Hence, we always bind to the object without making an
4573 // extra copy. However, in C++03 requires that we check for the
4574 // presence of a suitable copy constructor:
4575 //
4576 // The constructor that would be used to make the copy shall
4577 // be callable whether or not the copy is actually done.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004578 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004579 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004580 else if (S.getLangOpts().CPlusPlus11)
Richard Smithc620f552011-10-19 16:55:56 +00004581 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004582 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004583
Richard Smithb8c0f552016-12-09 18:49:13 +00004584 // C++1z [dcl.init.ref]/5.2.1.2:
4585 // If the converted initializer is a prvalue, its type T4 is adjusted
4586 // to type "cv1 T4" and the temporary materialization conversion is
4587 // applied.
4588 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1Quals);
4589 if (T1Quals != T2Quals)
4590 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
4591 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue);
4592 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
4593
4594 // In any case, the reference is bound to the resulting glvalue (or to
4595 // an appropriate base class subobject).
Douglas Gregor92e460e2011-01-20 16:44:54 +00004596 if (DerivedToBase)
Richard Smithb8c0f552016-12-09 18:49:13 +00004597 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
Douglas Gregor92e460e2011-01-20 16:44:54 +00004598 else if (ObjCConversion)
Richard Smithb8c0f552016-12-09 18:49:13 +00004599 Sequence.AddObjCObjectConversionStep(cv1T1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004600 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00004601 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004602
4603 // - has a class type (i.e., T2 is a class type), where T1 is not
4604 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00004605 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
4606 // where "cv1 T1" is reference-compatible with "cv3 T3",
Richard Smith6c6ddab2013-09-21 21:23:47 +00004607 //
4608 // DR1287 removes the "implicitly" here.
Douglas Gregor92e460e2011-01-20 16:44:54 +00004609 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004610 if (RefRelationship == Sema::Ref_Incompatible) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00004611 ConvOvlResult = TryRefInitWithConversionFunction(
Richard Smithb8c0f552016-12-09 18:49:13 +00004612 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
4613 /*IsLValueRef*/ isLValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004614 if (ConvOvlResult)
4615 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00004616 InitializationSequence::FK_ReferenceInitOverloadFailed,
4617 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004618
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004619 return;
4620 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004621
Richard Smithce766292016-10-21 23:01:55 +00004622 if (RefRelationship == Sema::Ref_Compatible &&
Douglas Gregor6fa6ab02013-03-26 23:59:23 +00004623 isRValueRef && InitCategory.isLValue()) {
4624 Sequence.SetFailed(
4625 InitializationSequence::FK_RValueReferenceBindingToLValue);
4626 return;
4627 }
4628
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004629 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4630 return;
4631 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004632
4633 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004634 // from the initializer expression using the rules for a non-reference
Richard Smith2eabf782013-06-13 00:57:57 +00004635 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004636 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00004637
John McCallec6f4e92010-06-04 02:29:22 +00004638 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4639
Richard Smith2eabf782013-06-13 00:57:57 +00004640 // FIXME: Why do we use an implicit conversion here rather than trying
4641 // copy-initialization?
John McCall31168b02011-06-15 23:02:42 +00004642 ImplicitConversionSequence ICS
4643 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith2eabf782013-06-13 00:57:57 +00004644 /*SuppressUserConversions=*/false,
4645 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004646 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004647 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4648 /*AllowObjCWritebackConversion=*/false);
4649
4650 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004651 // FIXME: Use the conversion function set stored in ICS to turn
4652 // this into an overloading ambiguity diagnostic. However, we need
4653 // to keep that set as an OverloadCandidateSet rather than as some
4654 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00004655 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4656 Sequence.SetOverloadFailure(
4657 InitializationSequence::FK_ReferenceInitOverloadFailed,
4658 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00004659 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4660 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00004661 else
4662 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004663 return;
John McCall31168b02011-06-15 23:02:42 +00004664 } else {
4665 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004666 }
4667
4668 // [...] If T1 is reference-related to T2, cv1 must be the
4669 // same cv-qualification as, or greater cv-qualification
4670 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00004671 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4672 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004673 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00004674 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004675 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4676 return;
4677 }
4678
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004679 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004680 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004681 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004682 InitCategory.isLValue()) {
4683 Sequence.SetFailed(
4684 InitializationSequence::FK_RValueReferenceBindingToLValue);
4685 return;
4686 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004687
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004688 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004689}
4690
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004691/// Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004692/// (C++ [dcl.init.string], C99 6.7.8).
4693static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004694 const InitializedEntity &Entity,
4695 const InitializationKind &Kind,
4696 Expr *Initializer,
4697 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004698 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004699}
4700
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004701/// Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004702static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004703 const InitializedEntity &Entity,
4704 const InitializationKind &Kind,
Richard Smithd86812d2012-07-05 08:39:21 +00004705 InitializationSequence &Sequence,
4706 InitListExpr *InitList) {
4707 assert((!InitList || InitList->getNumInits() == 0) &&
4708 "Shouldn't use value-init for non-empty init lists");
4709
Richard Smith1bfe0682012-02-14 21:14:13 +00004710 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004711 //
4712 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00004713 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004714
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004715 // -- if T is an array type, then each element is value-initialized;
Richard Smith1bfe0682012-02-14 21:14:13 +00004716 T = S.Context.getBaseElementType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004717
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004718 if (const RecordType *RT = T->getAs<RecordType>()) {
4719 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithd86812d2012-07-05 08:39:21 +00004720 bool NeedZeroInitialization = true;
Richard Smith505ef812016-12-21 01:57:02 +00004721 // C++98:
4722 // -- if T is a class type (clause 9) with a user-declared constructor
4723 // (12.1), then the default constructor for T is called (and the
4724 // initialization is ill-formed if T has no accessible default
4725 // constructor);
4726 // C++11:
4727 // -- if T is a class type (clause 9) with either no default constructor
4728 // (12.1 [class.ctor]) or a default constructor that is user-provided
4729 // or deleted, then the object is default-initialized;
4730 //
4731 // Note that the C++11 rule is the same as the C++98 rule if there are no
4732 // defaulted or deleted constructors, so we just use it unconditionally.
4733 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4734 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
4735 NeedZeroInitialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004736
Richard Smith1bfe0682012-02-14 21:14:13 +00004737 // -- if T is a (possibly cv-qualified) non-union class type without a
4738 // user-provided or deleted default constructor, then the object is
4739 // zero-initialized and, if T has a non-trivial default constructor,
4740 // default-initialized;
Richard Smithfb266522012-10-18 00:44:17 +00004741 // The 'non-union' here was removed by DR1502. The 'non-trivial default
4742 // constructor' part was removed by DR1507.
Richard Smithd86812d2012-07-05 08:39:21 +00004743 if (NeedZeroInitialization)
4744 Sequence.AddZeroInitializationStep(Entity.getType());
4745
Richard Smith593f9932012-12-08 02:01:17 +00004746 // C++03:
4747 // -- if T is a non-union class type without a user-declared constructor,
4748 // then every non-static data member and base class component of T is
4749 // value-initialized;
4750 // [...] A program that calls for [...] value-initialization of an
4751 // entity of reference type is ill-formed.
4752 //
4753 // C++11 doesn't need this handling, because value-initialization does not
4754 // occur recursively there, and the implicit default constructor is
4755 // defined as deleted in the problematic cases.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004756 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smith593f9932012-12-08 02:01:17 +00004757 ClassDecl->hasUninitializedReferenceMember()) {
4758 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4759 return;
4760 }
4761
Richard Smithd86812d2012-07-05 08:39:21 +00004762 // If this is list-value-initialization, pass the empty init list on when
4763 // building the constructor call. This affects the semantics of a few
4764 // things (such as whether an explicit default constructor can be called).
4765 Expr *InitListAsExpr = InitList;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004766 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithd86812d2012-07-05 08:39:21 +00004767 bool InitListSyntax = InitList;
4768
Richard Smith81f5ade2016-12-15 02:28:18 +00004769 // FIXME: Instead of creating a CXXConstructExpr of array type here,
Richard Smith410306b2016-12-12 02:53:20 +00004770 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
4771 return TryConstructorInitialization(
4772 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004773 }
4774 }
4775
Douglas Gregor1b303932009-12-22 15:35:07 +00004776 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004777}
4778
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004779/// Attempt default initialization (C++ [dcl.init]p6).
Douglas Gregor85dabae2009-12-16 01:38:02 +00004780static void TryDefaultInitialization(Sema &S,
4781 const InitializedEntity &Entity,
4782 const InitializationKind &Kind,
4783 InitializationSequence &Sequence) {
4784 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004785
Douglas Gregor85dabae2009-12-16 01:38:02 +00004786 // C++ [dcl.init]p6:
4787 // To default-initialize an object of type T means:
4788 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00004789 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4790
Douglas Gregor85dabae2009-12-16 01:38:02 +00004791 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4792 // constructor for T is called (and the initialization is ill-formed if
4793 // T has no accessible default constructor);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004794 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Richard Smith410306b2016-12-12 02:53:20 +00004795 TryConstructorInitialization(S, Entity, Kind, None, DestType,
4796 Entity.getType(), Sequence);
Chandler Carruthc9262402010-08-23 07:55:51 +00004797 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004798 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004799
Douglas Gregor85dabae2009-12-16 01:38:02 +00004800 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004801
Douglas Gregor85dabae2009-12-16 01:38:02 +00004802 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004803 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00004804 // default constructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004805 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Nico Weber337d5aa2015-04-17 08:32:38 +00004806 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4807 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00004808 return;
4809 }
4810
4811 // If the destination type has a lifetime property, zero-initialize it.
4812 if (DestType.getQualifiers().hasObjCLifetime()) {
4813 Sequence.AddZeroInitializationStep(Entity.getType());
4814 return;
4815 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004816}
4817
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004818/// Attempt a user-defined conversion between two types (C++ [dcl.init]),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004819/// which enumerates all conversion functions and performs overload resolution
4820/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004821static void TryUserDefinedConversion(Sema &S,
Richard Smith77be48a2014-07-31 06:31:19 +00004822 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004823 const InitializationKind &Kind,
4824 Expr *Initializer,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004825 InitializationSequence &Sequence,
4826 bool TopLevelOfInitList) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004827 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4828 QualType SourceType = Initializer->getType();
4829 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4830 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004831
Douglas Gregor540c3b02009-12-14 17:27:33 +00004832 // Build the candidate set directly in the initialization sequence
4833 // structure, so that it will persist if we fail.
4834 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
Richard Smith67ef14f2017-09-26 18:37:55 +00004835 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004836
Douglas Gregor540c3b02009-12-14 17:27:33 +00004837 // Determine whether we are allowed to call explicit constructors or
4838 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00004839 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004840
Douglas Gregor540c3b02009-12-14 17:27:33 +00004841 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4842 // The type we're converting to is a class type. Enumerate its constructors
4843 // to see if there is a suitable conversion.
4844 CXXRecordDecl *DestRecordDecl
4845 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004846
Douglas Gregord9848152010-04-26 14:36:57 +00004847 // Try to complete the type we're converting to.
Richard Smithdb0ac552015-12-18 22:40:25 +00004848 if (S.isCompleteType(Kind.getLocation(), DestType)) {
Richard Smith776e9c32017-02-01 03:28:59 +00004849 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
Richard Smithc2bebe92016-05-11 20:37:46 +00004850 auto Info = getConstructorInfo(D);
4851 if (!Info.Constructor)
4852 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004853
Richard Smithc2bebe92016-05-11 20:37:46 +00004854 if (!Info.Constructor->isInvalidDecl() &&
4855 Info.Constructor->isConvertingConstructor(AllowExplicit)) {
4856 if (Info.ConstructorTmpl)
4857 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004858 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004859 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004860 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004861 else
Richard Smithc2bebe92016-05-11 20:37:46 +00004862 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004863 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004864 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004865 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004866 }
Douglas Gregord9848152010-04-26 14:36:57 +00004867 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004868 }
Eli Friedman78275202009-12-19 08:11:05 +00004869
4870 SourceLocation DeclLoc = Initializer->getLocStart();
4871
Douglas Gregor540c3b02009-12-14 17:27:33 +00004872 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4873 // The type we're converting from is a class type, enumerate its conversion
4874 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00004875
Eli Friedman4afe9a32009-12-20 22:12:03 +00004876 // We can only enumerate the conversion functions for a complete type; if
4877 // the type isn't complete, simply skip this step.
Richard Smithdb0ac552015-12-18 22:40:25 +00004878 if (S.isCompleteType(DeclLoc, SourceType)) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004879 CXXRecordDecl *SourceRecordDecl
4880 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004881
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004882 const auto &Conversions =
4883 SourceRecordDecl->getVisibleConversionFunctions();
4884 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004885 NamedDecl *D = *I;
4886 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4887 if (isa<UsingShadowDecl>(D))
4888 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004889
Eli Friedman4afe9a32009-12-20 22:12:03 +00004890 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4891 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00004892 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00004893 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00004894 else
John McCallda4458e2010-03-31 01:36:47 +00004895 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004896
Eli Friedman4afe9a32009-12-20 22:12:03 +00004897 if (AllowExplicit || !Conv->isExplicit()) {
4898 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004899 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004900 ActingDC, Initializer, DestType,
Douglas Gregor68782142013-12-18 21:46:16 +00004901 CandidateSet, AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004902 else
John McCalla0296f72010-03-19 07:35:19 +00004903 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004904 Initializer, DestType, CandidateSet,
4905 AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004906 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004907 }
4908 }
4909 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004910
4911 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004912 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00004913 if (OverloadingResult Result
Richard Smith67ef14f2017-09-26 18:37:55 +00004914 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004915 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004916 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00004917 Result);
4918 return;
4919 }
John McCall0d1da222010-01-12 00:44:57 +00004920
Douglas Gregor540c3b02009-12-14 17:27:33 +00004921 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004922 Function->setReferenced();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004923 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004924
Douglas Gregor540c3b02009-12-14 17:27:33 +00004925 if (isa<CXXConstructorDecl>(Function)) {
4926 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithb24f0672012-02-11 19:22:50 +00004927 // subsumed by the initialization. Per DR5, the created temporary is of the
4928 // cv-unqualified type of the destination.
4929 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4930 DestType.getUnqualifiedType(),
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004931 HadMultipleCandidates);
Richard Smithb8c0f552016-12-09 18:49:13 +00004932
4933 // C++14 and before:
4934 // - if the function is a constructor, the call initializes a temporary
4935 // of the cv-unqualified version of the destination type. The [...]
4936 // temporary [...] is then used to direct-initialize, according to the
4937 // rules above, the object that is the destination of the
4938 // copy-initialization.
4939 // Note that this just performs a simple object copy from the temporary.
4940 //
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004941 // C++17:
Richard Smithb8c0f552016-12-09 18:49:13 +00004942 // - if the function is a constructor, the call is a prvalue of the
4943 // cv-unqualified version of the destination type whose return object
4944 // is initialized by the constructor. The call is used to
4945 // direct-initialize, according to the rules above, the object that
4946 // is the destination of the copy-initialization.
4947 // Therefore we need to do nothing further.
4948 //
4949 // FIXME: Mark this copy as extraneous.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004950 if (!S.getLangOpts().CPlusPlus17)
Richard Smithb8c0f552016-12-09 18:49:13 +00004951 Sequence.AddFinalCopy(DestType);
Richard Smith16d31502016-12-21 01:31:56 +00004952 else if (DestType.hasQualifiers())
4953 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004954 return;
4955 }
4956
4957 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004958 QualType ConvType = Function->getCallResultType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004959 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4960 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004961
Richard Smithb8c0f552016-12-09 18:49:13 +00004962 if (ConvType->getAs<RecordType>()) {
4963 // The call is used to direct-initialize [...] the object that is the
4964 // destination of the copy-initialization.
4965 //
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004966 // In C++17, this does not call a constructor if we enter /17.6.1:
Richard Smithb8c0f552016-12-09 18:49:13 +00004967 // - If the initializer expression is a prvalue and the cv-unqualified
4968 // version of the source type is the same as the class of the
4969 // destination [... do not make an extra copy]
4970 //
4971 // FIXME: Mark this copy as extraneous.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004972 if (!S.getLangOpts().CPlusPlus17 ||
Richard Smithb8c0f552016-12-09 18:49:13 +00004973 Function->getReturnType()->isReferenceType() ||
4974 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
4975 Sequence.AddFinalCopy(DestType);
Richard Smith16d31502016-12-21 01:31:56 +00004976 else if (!S.Context.hasSameType(ConvType, DestType))
4977 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
Richard Smithb8c0f552016-12-09 18:49:13 +00004978 return;
4979 }
4980
Douglas Gregor5ab11652010-04-17 22:01:05 +00004981 // If the conversion following the call to the conversion function
4982 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004983 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4984 Best->FinalConversion.Third) {
4985 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00004986 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00004987 ICS.Standard = Best->FinalConversion;
Richard Smithaaa0ec42013-09-21 21:19:19 +00004988 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004989 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004990}
4991
Richard Smithf032001b2013-06-20 02:18:31 +00004992/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4993/// a function with a pointer return type contains a 'return false;' statement.
4994/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4995/// code using that header.
4996///
4997/// Work around this by treating 'return false;' as zero-initializing the result
4998/// if it's used in a pointer-returning function in a system header.
4999static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
5000 const InitializedEntity &Entity,
5001 const Expr *Init) {
5002 return S.getLangOpts().CPlusPlus11 &&
5003 Entity.getKind() == InitializedEntity::EK_Result &&
5004 Entity.getType()->isPointerType() &&
5005 isa<CXXBoolLiteralExpr>(Init) &&
5006 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
5007 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
5008}
5009
John McCall31168b02011-06-15 23:02:42 +00005010/// The non-zero enum values here are indexes into diagnostic alternatives.
5011enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
5012
5013/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00005014static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005015 bool isAddressOf, bool &isWeakAccess) {
John McCall31168b02011-06-15 23:02:42 +00005016 // Skip parens.
5017 e = e->IgnoreParens();
5018
5019 // Skip address-of nodes.
5020 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
5021 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005022 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
5023 isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00005024
5025 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00005026 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
5027 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00005028 case CK_Dependent:
5029 case CK_BitCast:
5030 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00005031 case CK_NoOp:
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005032 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00005033
5034 case CK_ArrayToPointerDecay:
5035 return IIK_nonscalar;
5036
5037 case CK_NullToPointer:
5038 return IIK_okay;
5039
5040 default:
5041 break;
5042 }
5043
5044 // If we have a declaration reference, it had better be a local variable.
John McCall113bee02012-03-10 09:33:50 +00005045 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005046 // set isWeakAccess to true, to mean that there will be an implicit
5047 // load which requires a cleanup.
5048 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
5049 isWeakAccess = true;
5050
John McCall63f84442011-06-27 23:59:58 +00005051 if (!isAddressOf) return IIK_nonlocal;
5052
John McCall113bee02012-03-10 09:33:50 +00005053 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
5054 if (!var) return IIK_nonlocal;
John McCall63f84442011-06-27 23:59:58 +00005055
5056 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00005057
5058 // If we have a conditional operator, check both sides.
5059 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005060 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
5061 isWeakAccess))
John McCall31168b02011-06-15 23:02:42 +00005062 return iik;
5063
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005064 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00005065
5066 // These are never scalar.
5067 } else if (isa<ArraySubscriptExpr>(e)) {
5068 return IIK_nonscalar;
5069
5070 // Otherwise, it needs to be a null pointer constant.
5071 } else {
5072 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
5073 ? IIK_okay : IIK_nonlocal);
5074 }
5075
5076 return IIK_nonlocal;
5077}
5078
5079/// Check whether the given expression is a valid operand for an
5080/// indirect copy/restore.
5081static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
5082 assert(src->isRValue());
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00005083 bool isWeakAccess = false;
5084 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
5085 // If isWeakAccess to true, there will be an implicit
5086 // load which requires a cleanup.
5087 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
Tim Shen4a05bb82016-06-21 20:29:17 +00005088 S.Cleanup.setExprNeedsCleanups(true);
5089
John McCall31168b02011-06-15 23:02:42 +00005090 if (iik == IIK_okay) return;
5091
5092 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
5093 << ((unsigned) iik - 1) // shift index into diagnostic explanations
5094 << src->getSourceRange();
5095}
5096
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005097/// Determine whether we have compatible array types for the
Douglas Gregore2f943b2011-02-22 18:29:51 +00005098/// purposes of GNU by-copy array initialization.
Larisse Voufod2010992015-01-24 23:09:54 +00005099static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
Douglas Gregore2f943b2011-02-22 18:29:51 +00005100 const ArrayType *Source) {
5101 // If the source and destination array types are equivalent, we're
5102 // done.
5103 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
5104 return true;
5105
5106 // Make sure that the element types are the same.
5107 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
5108 return false;
5109
5110 // The only mismatch we allow is when the destination is an
5111 // incomplete array type and the source is a constant array type.
5112 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
5113}
5114
John McCall31168b02011-06-15 23:02:42 +00005115static bool tryObjCWritebackConversion(Sema &S,
5116 InitializationSequence &Sequence,
5117 const InitializedEntity &Entity,
5118 Expr *Initializer) {
5119 bool ArrayDecay = false;
5120 QualType ArgType = Initializer->getType();
5121 QualType ArgPointee;
5122 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
5123 ArrayDecay = true;
5124 ArgPointee = ArgArrayType->getElementType();
5125 ArgType = S.Context.getPointerType(ArgPointee);
5126 }
5127
5128 // Handle write-back conversion.
5129 QualType ConvertedArgType;
5130 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
5131 ConvertedArgType))
5132 return false;
5133
5134 // We should copy unless we're passing to an argument explicitly
5135 // marked 'out'.
5136 bool ShouldCopy = true;
5137 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5138 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5139
5140 // Do we need an lvalue conversion?
5141 if (ArrayDecay || Initializer->isGLValue()) {
5142 ImplicitConversionSequence ICS;
5143 ICS.setStandard();
5144 ICS.Standard.setAsIdentityConversion();
5145
5146 QualType ResultType;
5147 if (ArrayDecay) {
5148 ICS.Standard.First = ICK_Array_To_Pointer;
5149 ResultType = S.Context.getPointerType(ArgPointee);
5150 } else {
5151 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
5152 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
5153 }
5154
5155 Sequence.AddConversionSequenceStep(ICS, ResultType);
5156 }
5157
5158 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
5159 return true;
5160}
5161
Guy Benyei61054192013-02-07 10:55:47 +00005162static bool TryOCLSamplerInitialization(Sema &S,
5163 InitializationSequence &Sequence,
5164 QualType DestType,
5165 Expr *Initializer) {
5166 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00005167 (!Initializer->isIntegerConstantExpr(S.Context) &&
5168 !Initializer->getType()->isSamplerT()))
Guy Benyei61054192013-02-07 10:55:47 +00005169 return false;
5170
5171 Sequence.AddOCLSamplerInitStep(DestType);
5172 return true;
5173}
5174
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005175//
5176// OpenCL 1.2 spec, s6.12.10
5177//
5178// The event argument can also be used to associate the
5179// async_work_group_copy with a previous async copy allowing
5180// an event to be shared by multiple async copies; otherwise
5181// event should be zero.
5182//
5183static bool TryOCLZeroEventInitialization(Sema &S,
5184 InitializationSequence &Sequence,
5185 QualType DestType,
5186 Expr *Initializer) {
5187 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
5188 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
5189 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
5190 return false;
5191
5192 Sequence.AddOCLZeroEventStep(DestType);
5193 return true;
5194}
5195
Egor Churaev89831422016-12-23 14:55:49 +00005196static bool TryOCLZeroQueueInitialization(Sema &S,
5197 InitializationSequence &Sequence,
5198 QualType DestType,
5199 Expr *Initializer) {
5200 if (!S.getLangOpts().OpenCL || S.getLangOpts().OpenCLVersion < 200 ||
5201 !DestType->isQueueT() ||
5202 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
5203 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
5204 return false;
5205
5206 Sequence.AddOCLZeroQueueStep(DestType);
5207 return true;
5208}
5209
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005210InitializationSequence::InitializationSequence(Sema &S,
5211 const InitializedEntity &Entity,
5212 const InitializationKind &Kind,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005213 MultiExprArg Args,
Manman Ren073db022016-03-10 18:53:19 +00005214 bool TopLevelOfInitList,
5215 bool TreatUnavailableAsInvalid)
Richard Smith100b24a2014-04-17 01:52:14 +00005216 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
Manman Ren073db022016-03-10 18:53:19 +00005217 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
5218 TreatUnavailableAsInvalid);
Richard Smith089c3162013-09-21 21:55:46 +00005219}
5220
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005221/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
5222/// address of that function, this returns true. Otherwise, it returns false.
5223static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
5224 auto *DRE = dyn_cast<DeclRefExpr>(E);
5225 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
5226 return false;
5227
5228 return !S.checkAddressOfFunctionIsAvailable(
5229 cast<FunctionDecl>(DRE->getDecl()));
5230}
5231
Richard Smith410306b2016-12-12 02:53:20 +00005232/// Determine whether we can perform an elementwise array copy for this kind
5233/// of entity.
5234static bool canPerformArrayCopy(const InitializedEntity &Entity) {
5235 switch (Entity.getKind()) {
5236 case InitializedEntity::EK_LambdaCapture:
5237 // C++ [expr.prim.lambda]p24:
5238 // For array members, the array elements are direct-initialized in
5239 // increasing subscript order.
5240 return true;
5241
5242 case InitializedEntity::EK_Variable:
5243 // C++ [dcl.decomp]p1:
5244 // [...] each element is copy-initialized or direct-initialized from the
5245 // corresponding element of the assignment-expression [...]
5246 return isa<DecompositionDecl>(Entity.getDecl());
5247
5248 case InitializedEntity::EK_Member:
5249 // C++ [class.copy.ctor]p14:
5250 // - if the member is an array, each element is direct-initialized with
5251 // the corresponding subobject of x
5252 return Entity.isImplicitMemberInitializer();
5253
5254 case InitializedEntity::EK_ArrayElement:
5255 // All the above cases are intended to apply recursively, even though none
5256 // of them actually say that.
5257 if (auto *E = Entity.getParent())
5258 return canPerformArrayCopy(*E);
5259 break;
5260
5261 default:
5262 break;
5263 }
5264
5265 return false;
5266}
5267
Richard Smith089c3162013-09-21 21:55:46 +00005268void InitializationSequence::InitializeFrom(Sema &S,
5269 const InitializedEntity &Entity,
5270 const InitializationKind &Kind,
5271 MultiExprArg Args,
Manman Ren073db022016-03-10 18:53:19 +00005272 bool TopLevelOfInitList,
5273 bool TreatUnavailableAsInvalid) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005274 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005275
John McCall5e77d762013-04-16 07:28:30 +00005276 // Eliminate non-overload placeholder types in the arguments. We
5277 // need to do this before checking whether types are dependent
5278 // because lowering a pseudo-object expression might well give us
5279 // something of dependent type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005280 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall5e77d762013-04-16 07:28:30 +00005281 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
5282 // FIXME: should we be doing this here?
5283 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
5284 if (result.isInvalid()) {
5285 SetFailed(FK_PlaceholderType);
5286 return;
5287 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005288 Args[I] = result.get();
John McCall5e77d762013-04-16 07:28:30 +00005289 }
5290
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005291 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005292 // The semantics of initializers are as follows. The destination type is
5293 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005294 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005295 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005296 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005297 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005298
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005299 if (DestType->isDependentType() ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005300 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005301 SequenceKind = DependentSequence;
5302 return;
5303 }
5304
Sebastian Redld201edf2011-06-05 13:59:11 +00005305 // Almost everything is a normal sequence.
5306 setSequenceKind(NormalSequence);
5307
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005308 QualType SourceType;
Craig Topperc3ec1492014-05-26 06:22:03 +00005309 Expr *Initializer = nullptr;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005310 if (Args.size() == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005311 Initializer = Args[0];
Fariborz Jahanian283bf892013-12-18 21:04:43 +00005312 if (S.getLangOpts().ObjC1) {
5313 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
5314 DestType, Initializer->getType(),
5315 Initializer) ||
5316 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
5317 Args[0] = Initializer;
Fariborz Jahanian283bf892013-12-18 21:04:43 +00005318 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005319 if (!isa<InitListExpr>(Initializer))
5320 SourceType = Initializer->getType();
5321 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005322
Sebastian Redl0501c632012-02-12 16:37:36 +00005323 // - If the initializer is a (non-parenthesized) braced-init-list, the
5324 // object is list-initialized (8.5.4).
5325 if (Kind.getKind() != InitializationKind::IK_Direct) {
5326 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Manman Ren073db022016-03-10 18:53:19 +00005327 TryListInitialization(S, Entity, Kind, InitList, *this,
5328 TreatUnavailableAsInvalid);
Sebastian Redl0501c632012-02-12 16:37:36 +00005329 return;
5330 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005331 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005332
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005333 // - If the destination type is a reference type, see 8.5.3.
5334 if (DestType->isReferenceType()) {
5335 // C++0x [dcl.init.ref]p1:
5336 // A variable declared to be a T& or T&&, that is, "reference to type T"
5337 // (8.3.2), shall be initialized by an object, or function, of type T or
5338 // by an object that can be converted into a T.
5339 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005340 if (Args.size() != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005341 SetFailed(FK_TooManyInitsForReference);
Richard Smith49a6b6e2017-03-24 01:14:25 +00005342 // C++17 [dcl.init.ref]p5:
5343 // A reference [...] is initialized by an expression [...] as follows:
5344 // If the initializer is not an expression, presumably we should reject,
5345 // but the standard fails to actually say so.
5346 else if (isa<InitListExpr>(Args[0]))
5347 SetFailed(FK_ParenthesizedListInitForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005348 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005349 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005350 return;
5351 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005352
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005353 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00005354 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005355 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005356 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005357 return;
5358 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005359
Douglas Gregor85dabae2009-12-16 01:38:02 +00005360 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00005361 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005362 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005363 return;
5364 }
Douglas Gregore1314a62009-12-18 05:02:21 +00005365
John McCall66884dd2011-02-21 07:22:22 +00005366 // - If the destination type is an array of characters, an array of
5367 // char16_t, an array of char32_t, or an array of wchar_t, and the
5368 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005369 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005370 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00005371 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00005372 if (Initializer && isa<VariableArrayType>(DestAT)) {
5373 SetFailed(FK_VariableLengthArrayHasInitializer);
5374 return;
5375 }
5376
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005377 if (Initializer) {
5378 switch (IsStringInit(Initializer, DestAT, Context)) {
5379 case SIF_None:
5380 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
5381 return;
5382 case SIF_NarrowStringIntoWideChar:
5383 SetFailed(FK_NarrowStringIntoWideCharArray);
5384 return;
5385 case SIF_WideStringIntoChar:
5386 SetFailed(FK_WideStringIntoCharArray);
5387 return;
5388 case SIF_IncompatWideStringIntoWideChar:
5389 SetFailed(FK_IncompatWideStringIntoWideChar);
5390 return;
Richard Smith3a8244d2018-05-01 05:02:45 +00005391 case SIF_PlainStringIntoUTF8Char:
5392 SetFailed(FK_PlainStringIntoUTF8Char);
5393 return;
5394 case SIF_UTF8StringIntoPlainChar:
5395 SetFailed(FK_UTF8StringIntoPlainChar);
5396 return;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005397 case SIF_Other:
5398 break;
5399 }
John McCall66884dd2011-02-21 07:22:22 +00005400 }
5401
Richard Smith410306b2016-12-12 02:53:20 +00005402 // Some kinds of initialization permit an array to be initialized from
5403 // another array of the same type, and perform elementwise initialization.
5404 if (Initializer && isa<ConstantArrayType>(DestAT) &&
5405 S.Context.hasSameUnqualifiedType(Initializer->getType(),
5406 Entity.getType()) &&
5407 canPerformArrayCopy(Entity)) {
5408 // If source is a prvalue, use it directly.
5409 if (Initializer->getValueKind() == VK_RValue) {
Richard Smith378b8c82016-12-14 03:22:16 +00005410 AddArrayInitStep(DestType, /*IsGNUExtension*/false);
Richard Smith410306b2016-12-12 02:53:20 +00005411 return;
5412 }
5413
5414 // Emit element-at-a-time copy loop.
5415 InitializedEntity Element =
5416 InitializedEntity::InitializeElement(S.Context, 0, Entity);
5417 QualType InitEltT =
5418 Context.getAsArrayType(Initializer->getType())->getElementType();
Richard Smith30e304e2016-12-14 00:03:17 +00005419 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
5420 Initializer->getValueKind(),
5421 Initializer->getObjectKind());
Richard Smith410306b2016-12-12 02:53:20 +00005422 Expr *OVEAsExpr = &OVE;
5423 InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
5424 TreatUnavailableAsInvalid);
5425 if (!Failed())
5426 AddArrayInitLoopStep(Entity.getType(), InitEltT);
5427 return;
5428 }
5429
Douglas Gregore2f943b2011-02-22 18:29:51 +00005430 // Note: as an GNU C extension, we allow initialization of an
5431 // array from a compound literal that creates an array of the same
5432 // type, so long as the initializer has no side effects.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005433 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregore2f943b2011-02-22 18:29:51 +00005434 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
5435 Initializer->getType()->isArrayType()) {
5436 const ArrayType *SourceAT
5437 = Context.getAsArrayType(Initializer->getType());
5438 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005439 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005440 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005441 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005442 else {
Richard Smith378b8c82016-12-14 03:22:16 +00005443 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
Douglas Gregore2f943b2011-02-22 18:29:51 +00005444 }
Richard Smithebeed412012-02-15 22:38:09 +00005445 }
Richard Smithd86812d2012-07-05 08:39:21 +00005446 // Note: as a GNU C++ extension, we allow list-initialization of a
5447 // class member of array type from a parenthesized initializer list.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005448 else if (S.getLangOpts().CPlusPlus &&
Richard Smithebeed412012-02-15 22:38:09 +00005449 Entity.getKind() == InitializedEntity::EK_Member &&
5450 Initializer && isa<InitListExpr>(Initializer)) {
5451 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
Manman Ren073db022016-03-10 18:53:19 +00005452 *this, TreatUnavailableAsInvalid);
Richard Smithebeed412012-02-15 22:38:09 +00005453 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005454 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005455 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00005456 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
5457 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005458 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005459 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005460
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005461 return;
5462 }
Eli Friedman78275202009-12-19 08:11:05 +00005463
Larisse Voufod2010992015-01-24 23:09:54 +00005464 // Determine whether we should consider writeback conversions for
John McCall31168b02011-06-15 23:02:42 +00005465 // Objective-C ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005466 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005467 Entity.isParameterKind();
John McCall31168b02011-06-15 23:02:42 +00005468
5469 // We're at the end of the line for C: it's either a write-back conversion
5470 // or it's a C assignment. There's no need to check anything else.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005471 if (!S.getLangOpts().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00005472 // If allowed, check whether this is an Objective-C writeback conversion.
5473 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005474 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00005475 return;
5476 }
Guy Benyei61054192013-02-07 10:55:47 +00005477
5478 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
5479 return;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005480
5481 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
5482 return;
5483
Egor Churaev89831422016-12-23 14:55:49 +00005484 if (TryOCLZeroQueueInitialization(S, *this, DestType, Initializer))
5485 return;
5486
John McCall31168b02011-06-15 23:02:42 +00005487 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005488 AddCAssignmentStep(DestType);
5489 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00005490 return;
5491 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005492
David Blaikiebbafb8a2012-03-11 07:00:24 +00005493 assert(S.getLangOpts().CPlusPlus);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005494
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005495 // - If the destination type is a (possibly cv-qualified) class type:
5496 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005497 // - If the initialization is direct-initialization, or if it is
5498 // copy-initialization where the cv-unqualified version of the
5499 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005500 // class of the destination, constructors are considered. [...]
5501 if (Kind.getKind() == InitializationKind::IK_Direct ||
5502 (Kind.getKind() == InitializationKind::IK_Copy &&
5503 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005504 S.IsDerivedFrom(Initializer->getLocStart(), SourceType, DestType))))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005505 TryConstructorInitialization(S, Entity, Kind, Args,
Richard Smith410306b2016-12-12 02:53:20 +00005506 DestType, DestType, *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005507 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005508 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005509 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005510 // used) to a derived class thereof are enumerated as described in
5511 // 13.3.1.4, and the best one is chosen through overload resolution
5512 // (13.3).
5513 else
Richard Smith77be48a2014-07-31 06:31:19 +00005514 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005515 TopLevelOfInitList);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005516 return;
5517 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005518
Richard Smith49a6b6e2017-03-24 01:14:25 +00005519 assert(Args.size() >= 1 && "Zero-argument case handled above");
5520
5521 // The remaining cases all need a source type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005522 if (Args.size() > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005523 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005524 return;
Richard Smith49a6b6e2017-03-24 01:14:25 +00005525 } else if (isa<InitListExpr>(Args[0])) {
5526 SetFailed(FK_ParenthesizedListInitForScalar);
5527 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00005528 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005529
5530 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005531 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00005532 if (!SourceType.isNull() && SourceType->isRecordType()) {
Richard Smith77be48a2014-07-31 06:31:19 +00005533 // For a conversion to _Atomic(T) from either T or a class type derived
5534 // from T, initialize the T object then convert to _Atomic type.
5535 bool NeedAtomicConversion = false;
5536 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
5537 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005538 S.IsDerivedFrom(Initializer->getLocStart(), SourceType,
5539 Atomic->getValueType())) {
Richard Smith77be48a2014-07-31 06:31:19 +00005540 DestType = Atomic->getValueType();
5541 NeedAtomicConversion = true;
5542 }
5543 }
5544
5545 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005546 TopLevelOfInitList);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005547 MaybeProduceObjCObject(S, *this, Entity);
Richard Smith77be48a2014-07-31 06:31:19 +00005548 if (!Failed() && NeedAtomicConversion)
5549 AddAtomicConversionStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005550 return;
5551 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005552
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005553 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00005554 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005555 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005556 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005557 // destination type; no user-defined conversions are considered.
Richard Smith77be48a2014-07-31 06:31:19 +00005558
John McCall31168b02011-06-15 23:02:42 +00005559 ImplicitConversionSequence ICS
Richard Smith77be48a2014-07-31 06:31:19 +00005560 = S.TryImplicitConversion(Initializer, DestType,
John McCall31168b02011-06-15 23:02:42 +00005561 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00005562 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00005563 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00005564 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5565 allowObjCWritebackConversion);
Richard Smith77be48a2014-07-31 06:31:19 +00005566
5567 if (ICS.isStandard() &&
John McCall31168b02011-06-15 23:02:42 +00005568 ICS.Standard.Second == ICK_Writeback_Conversion) {
5569 // Objective-C ARC writeback conversion.
5570
5571 // We should copy unless we're passing to an argument explicitly
5572 // marked 'out'.
5573 bool ShouldCopy = true;
5574 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5575 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5576
5577 // If there was an lvalue adjustment, add it as a separate conversion.
5578 if (ICS.Standard.First == ICK_Array_To_Pointer ||
5579 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5580 ImplicitConversionSequence LvalueICS;
5581 LvalueICS.setStandard();
5582 LvalueICS.Standard.setAsIdentityConversion();
5583 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
5584 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005585 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00005586 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005587
Richard Smith77be48a2014-07-31 06:31:19 +00005588 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00005589 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00005590 DeclAccessPair dap;
Richard Smithf032001b2013-06-20 02:18:31 +00005591 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
5592 AddZeroInitializationStep(Entity.getType());
5593 } else if (Initializer->getType() == Context.OverloadTy &&
5594 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
5595 false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005596 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005597 else if (Initializer->getType()->isFunctionType() &&
5598 isExprAnUnaddressableFunction(S, Initializer))
5599 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
Douglas Gregore81f58e2010-11-08 03:40:48 +00005600 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005601 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00005602 } else {
Richard Smith77be48a2014-07-31 06:31:19 +00005603 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
John McCallfa272342011-06-16 23:24:51 +00005604
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005605 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00005606 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005607}
5608
5609InitializationSequence::~InitializationSequence() {
Davide Italiano67bb9f72015-07-01 21:51:58 +00005610 for (auto &S : Steps)
5611 S.Destroy();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005612}
5613
5614//===----------------------------------------------------------------------===//
5615// Perform initialization
5616//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005617static Sema::AssignmentAction
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005618getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005619 switch(Entity.getKind()) {
5620 case InitializedEntity::EK_Variable:
5621 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00005622 case InitializedEntity::EK_Exception:
5623 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005624 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00005625 return Sema::AA_Initializing;
5626
5627 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005628 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00005629 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5630 return Sema::AA_Sending;
5631
Douglas Gregore1314a62009-12-18 05:02:21 +00005632 return Sema::AA_Passing;
5633
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005634 case InitializedEntity::EK_Parameter_CF_Audited:
5635 if (Entity.getDecl() &&
5636 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5637 return Sema::AA_Sending;
5638
5639 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
5640
Douglas Gregore1314a62009-12-18 05:02:21 +00005641 case InitializedEntity::EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00005642 case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
Douglas Gregore1314a62009-12-18 05:02:21 +00005643 return Sema::AA_Returning;
5644
Douglas Gregore1314a62009-12-18 05:02:21 +00005645 case InitializedEntity::EK_Temporary:
Fariborz Jahanian14e95412013-07-11 19:13:34 +00005646 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00005647 // FIXME: Can we tell apart casting vs. converting?
5648 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005649
Douglas Gregore1314a62009-12-18 05:02:21 +00005650 case InitializedEntity::EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00005651 case InitializedEntity::EK_Binding:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00005652 case InitializedEntity::EK_ArrayElement:
5653 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005654 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005655 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005656 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005657 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005658 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00005659 return Sema::AA_Initializing;
5660 }
5661
David Blaikie8a40f702012-01-17 06:56:22 +00005662 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00005663}
5664
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005665/// Whether we should bind a created object as a temporary when
Douglas Gregor95562572010-04-24 23:45:46 +00005666/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005667static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005668 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00005669 case InitializedEntity::EK_ArrayElement:
5670 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005671 case InitializedEntity::EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00005672 case InitializedEntity::EK_StmtExprResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00005673 case InitializedEntity::EK_New:
5674 case InitializedEntity::EK_Variable:
5675 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005676 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00005677 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005678 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00005679 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005680 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005681 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005682 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005683 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00005684 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005685
Douglas Gregore1314a62009-12-18 05:02:21 +00005686 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005687 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregore1314a62009-12-18 05:02:21 +00005688 case InitializedEntity::EK_Temporary:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005689 case InitializedEntity::EK_RelatedResult:
Richard Smith7873de02016-08-11 22:25:46 +00005690 case InitializedEntity::EK_Binding:
Douglas Gregore1314a62009-12-18 05:02:21 +00005691 return true;
5692 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005693
Douglas Gregore1314a62009-12-18 05:02:21 +00005694 llvm_unreachable("missed an InitializedEntity kind?");
5695}
5696
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005697/// Whether the given entity, when initialized with an object
Douglas Gregor95562572010-04-24 23:45:46 +00005698/// created for that initialization, requires destruction.
Richard Smithb8c0f552016-12-09 18:49:13 +00005699static bool shouldDestroyEntity(const InitializedEntity &Entity) {
Douglas Gregor95562572010-04-24 23:45:46 +00005700 switch (Entity.getKind()) {
Douglas Gregor95562572010-04-24 23:45:46 +00005701 case InitializedEntity::EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00005702 case InitializedEntity::EK_StmtExprResult:
Douglas Gregor95562572010-04-24 23:45:46 +00005703 case InitializedEntity::EK_New:
5704 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005705 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00005706 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005707 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005708 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005709 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005710 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor95562572010-04-24 23:45:46 +00005711 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005712
Richard Smith27874d62013-01-08 00:08:23 +00005713 case InitializedEntity::EK_Member:
Richard Smith7873de02016-08-11 22:25:46 +00005714 case InitializedEntity::EK_Binding:
Douglas Gregor95562572010-04-24 23:45:46 +00005715 case InitializedEntity::EK_Variable:
5716 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005717 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor95562572010-04-24 23:45:46 +00005718 case InitializedEntity::EK_Temporary:
5719 case InitializedEntity::EK_ArrayElement:
5720 case InitializedEntity::EK_Exception:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005721 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005722 case InitializedEntity::EK_RelatedResult:
Douglas Gregor95562572010-04-24 23:45:46 +00005723 return true;
5724 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005725
5726 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00005727}
5728
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005729/// Get the location at which initialization diagnostics should appear.
Richard Smithc620f552011-10-19 16:55:56 +00005730static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
5731 Expr *Initializer) {
5732 switch (Entity.getKind()) {
5733 case InitializedEntity::EK_Result:
Richard Smith67af95b2018-07-23 19:19:08 +00005734 case InitializedEntity::EK_StmtExprResult:
Richard Smithc620f552011-10-19 16:55:56 +00005735 return Entity.getReturnLoc();
5736
5737 case InitializedEntity::EK_Exception:
5738 return Entity.getThrowLoc();
5739
5740 case InitializedEntity::EK_Variable:
Richard Smith7873de02016-08-11 22:25:46 +00005741 case InitializedEntity::EK_Binding:
Richard Smithc620f552011-10-19 16:55:56 +00005742 return Entity.getDecl()->getLocation();
5743
Douglas Gregor19666fb2012-02-15 16:57:26 +00005744 case InitializedEntity::EK_LambdaCapture:
5745 return Entity.getCaptureLoc();
5746
Richard Smithc620f552011-10-19 16:55:56 +00005747 case InitializedEntity::EK_ArrayElement:
5748 case InitializedEntity::EK_Member:
5749 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005750 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithc620f552011-10-19 16:55:56 +00005751 case InitializedEntity::EK_Temporary:
5752 case InitializedEntity::EK_New:
5753 case InitializedEntity::EK_Base:
5754 case InitializedEntity::EK_Delegating:
5755 case InitializedEntity::EK_VectorElement:
5756 case InitializedEntity::EK_ComplexElement:
5757 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00005758 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005759 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005760 case InitializedEntity::EK_RelatedResult:
Richard Smithc620f552011-10-19 16:55:56 +00005761 return Initializer->getLocStart();
5762 }
5763 llvm_unreachable("missed an InitializedEntity kind?");
5764}
5765
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005766/// Make a (potentially elidable) temporary copy of the object
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005767/// provided by the given initializer by calling the appropriate copy
5768/// constructor.
5769///
5770/// \param S The Sema object used for type-checking.
5771///
Abramo Bagnara92141d22011-01-27 19:55:10 +00005772/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005773/// the type of the initializer expression or a superclass thereof.
5774///
James Dennett634962f2012-06-14 21:40:34 +00005775/// \param Entity The entity being initialized.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005776///
5777/// \param CurInit The initializer expression.
5778///
5779/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5780/// is permitted in C++03 (but not C++0x) when binding a reference to
5781/// an rvalue.
5782///
5783/// \returns An expression that copies the initializer expression into
5784/// a temporary object, or an error expression if a copy could not be
5785/// created.
John McCalldadc5752010-08-24 06:29:42 +00005786static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005787 QualType T,
5788 const InitializedEntity &Entity,
5789 ExprResult CurInit,
5790 bool IsExtraneousCopy) {
Fariborz Jahanian36f7f132015-01-28 22:08:10 +00005791 if (CurInit.isInvalid())
5792 return CurInit;
Douglas Gregor5ab11652010-04-17 22:01:05 +00005793 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00005794 Expr *CurInitExpr = (Expr *)CurInit.get();
Craig Topperc3ec1492014-05-26 06:22:03 +00005795 CXXRecordDecl *Class = nullptr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005796 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005797 Class = cast<CXXRecordDecl>(Record->getDecl());
5798 if (!Class)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005799 return CurInit;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005800
Richard Smithc620f552011-10-19 16:55:56 +00005801 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00005802
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005803 // Make sure that the type we are copying is complete.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005804 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005805 return CurInit;
Douglas Gregord5c231e2010-04-24 21:09:25 +00005806
Richard Smith7c2bcc92016-09-07 02:14:33 +00005807 // Perform overload resolution using the class's constructors. Per
5808 // C++11 [dcl.init]p16, second bullet for class types, this initialization
Richard Smithc620f552011-10-19 16:55:56 +00005809 // is direct-initialization.
Richard Smith100b24a2014-04-17 01:52:14 +00005810 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smith7c2bcc92016-09-07 02:14:33 +00005811 DeclContext::lookup_result Ctors = S.LookupConstructors(Class);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005812
Douglas Gregore1314a62009-12-18 05:02:21 +00005813 OverloadCandidateSet::iterator Best;
Richard Smith7c2bcc92016-09-07 02:14:33 +00005814 switch (ResolveConstructorOverload(
Richard Smith67ef14f2017-09-26 18:37:55 +00005815 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
Richard Smith7c2bcc92016-09-07 02:14:33 +00005816 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
5817 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
5818 /*SecondStepOfCopyInit=*/true)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005819 case OR_Success:
5820 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005821
Douglas Gregore1314a62009-12-18 05:02:21 +00005822 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005823 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
5824 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
5825 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005826 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005827 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005828 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005829 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00005830 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005831 return CurInit;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005832
Douglas Gregore1314a62009-12-18 05:02:21 +00005833 case OR_Ambiguous:
5834 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005835 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005836 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005837 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallfaf5fb42010-08-26 23:41:50 +00005838 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005839
Douglas Gregore1314a62009-12-18 05:02:21 +00005840 case OR_Deleted:
5841 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005842 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005843 << CurInitExpr->getSourceRange();
Richard Smith852265f2012-03-30 20:53:28 +00005844 S.NoteDeletedFunction(Best->Function);
John McCallfaf5fb42010-08-26 23:41:50 +00005845 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005846 }
5847
Richard Smith7c2bcc92016-09-07 02:14:33 +00005848 bool HadMultipleCandidates = CandidateSet.size() > 1;
5849
Douglas Gregor5ab11652010-04-17 22:01:05 +00005850 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramerf0623432012-08-23 22:51:59 +00005851 SmallVector<Expr*, 8> ConstructorArgs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005852 CurInit.get(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005853
Richard Smith5179eb72016-06-28 19:03:57 +00005854 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
5855 IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005856
5857 if (IsExtraneousCopy) {
5858 // If this is a totally extraneous copy for C++03 reference
5859 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00005860 // expression. We don't generate an (elided) copy operation here
5861 // because doing so would require us to pass down a flag to avoid
5862 // infinite recursion, where each step adds another extraneous,
5863 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005864
Douglas Gregor30b52772010-04-18 07:57:34 +00005865 // Instantiate the default arguments of any extra parameters in
5866 // the selected copy constructor, as if we were going to create a
5867 // proper call to the copy constructor.
5868 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5869 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5870 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005871 diag::err_call_incomplete_argument))
Douglas Gregor30b52772010-04-18 07:57:34 +00005872 break;
5873
5874 // Build the default argument expression; we don't actually care
5875 // if this succeeds or not, because this routine will complain
5876 // if there was a problem.
5877 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5878 }
5879
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005880 return CurInitExpr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005881 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005882
Douglas Gregor5ab11652010-04-17 22:01:05 +00005883 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005884 // constructor call (we might have derived-to-base conversions, or
5885 // the copy constructor may have default arguments).
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005886 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005887 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005888
Richard Smith7c2bcc92016-09-07 02:14:33 +00005889 // C++0x [class.copy]p32:
5890 // When certain criteria are met, an implementation is allowed to
5891 // omit the copy/move construction of a class object, even if the
5892 // copy/move constructor and/or destructor for the object have
5893 // side effects. [...]
5894 // - when a temporary class object that has not been bound to a
5895 // reference (12.2) would be copied/moved to a class object
5896 // with the same cv-unqualified type, the copy/move operation
5897 // can be omitted by constructing the temporary object
5898 // directly into the target of the omitted copy/move
5899 //
5900 // Note that the other three bullets are handled elsewhere. Copy
5901 // elision for return statements and throw expressions are handled as part
5902 // of constructor initialization, while copy elision for exception handlers
5903 // is handled by the run-time.
5904 //
5905 // FIXME: If the function parameter is not the same type as the temporary, we
5906 // should still be able to elide the copy, but we don't have a way to
5907 // represent in the AST how much should be elided in this case.
5908 bool Elidable =
5909 CurInitExpr->isTemporaryObject(S.Context, Class) &&
5910 S.Context.hasSameUnqualifiedType(
5911 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
5912 CurInitExpr->getType());
5913
Douglas Gregord0ace022010-04-25 00:55:24 +00005914 // Actually perform the constructor call.
Richard Smithc2bebe92016-05-11 20:37:46 +00005915 CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor,
5916 Elidable,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005917 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005918 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005919 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005920 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005921 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005922 CXXConstructExpr::CK_Complete,
5923 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005924
Douglas Gregord0ace022010-04-25 00:55:24 +00005925 // If we're supposed to bind temporaries, do so.
5926 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005927 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005928 return CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00005929}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005930
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005931/// Check whether elidable copy construction for binding a reference to
Richard Smithc620f552011-10-19 16:55:56 +00005932/// a temporary would have succeeded if we were building in C++98 mode, for
5933/// -Wc++98-compat.
5934static void CheckCXX98CompatAccessibleCopy(Sema &S,
5935 const InitializedEntity &Entity,
5936 Expr *CurInitExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005937 assert(S.getLangOpts().CPlusPlus11);
Richard Smithc620f552011-10-19 16:55:56 +00005938
5939 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5940 if (!Record)
5941 return;
5942
5943 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005944 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
Richard Smithc620f552011-10-19 16:55:56 +00005945 return;
5946
5947 // Find constructors which would have been considered.
Richard Smith100b24a2014-04-17 01:52:14 +00005948 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smith7c2bcc92016-09-07 02:14:33 +00005949 DeclContext::lookup_result Ctors =
5950 S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
Richard Smithc620f552011-10-19 16:55:56 +00005951
5952 // Perform overload resolution.
5953 OverloadCandidateSet::iterator Best;
Richard Smith7c2bcc92016-09-07 02:14:33 +00005954 OverloadingResult OR = ResolveConstructorOverload(
Richard Smith67ef14f2017-09-26 18:37:55 +00005955 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
Richard Smith7c2bcc92016-09-07 02:14:33 +00005956 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
5957 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
5958 /*SecondStepOfCopyInit=*/true);
Richard Smithc620f552011-10-19 16:55:56 +00005959
5960 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5961 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5962 << CurInitExpr->getSourceRange();
5963
5964 switch (OR) {
5965 case OR_Success:
5966 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
Richard Smith5179eb72016-06-28 19:03:57 +00005967 Best->FoundDecl, Entity, Diag);
Richard Smithc620f552011-10-19 16:55:56 +00005968 // FIXME: Check default arguments as far as that's possible.
5969 break;
5970
5971 case OR_No_Viable_Function:
5972 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005973 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005974 break;
5975
5976 case OR_Ambiguous:
5977 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005978 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005979 break;
5980
5981 case OR_Deleted:
5982 S.Diag(Loc, Diag);
Richard Smith852265f2012-03-30 20:53:28 +00005983 S.NoteDeletedFunction(Best->Function);
Richard Smithc620f552011-10-19 16:55:56 +00005984 break;
5985 }
5986}
5987
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005988void InitializationSequence::PrintInitLocationNote(Sema &S,
5989 const InitializedEntity &Entity) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005990 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005991 if (Entity.getDecl()->getLocation().isInvalid())
5992 return;
5993
5994 if (Entity.getDecl()->getDeclName())
5995 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5996 << Entity.getDecl()->getDeclName();
5997 else
5998 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5999 }
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00006000 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
6001 Entity.getMethodDecl())
6002 S.Diag(Entity.getMethodDecl()->getLocation(),
6003 diag::note_method_return_type_change)
6004 << Entity.getMethodDecl()->getDeclName();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006005}
6006
Jordan Rose6c0505e2013-05-06 16:48:12 +00006007/// Returns true if the parameters describe a constructor initialization of
6008/// an explicit temporary object, e.g. "Point(x, y)".
6009static bool isExplicitTemporary(const InitializedEntity &Entity,
6010 const InitializationKind &Kind,
6011 unsigned NumArgs) {
6012 switch (Entity.getKind()) {
6013 case InitializedEntity::EK_Temporary:
6014 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00006015 case InitializedEntity::EK_RelatedResult:
Jordan Rose6c0505e2013-05-06 16:48:12 +00006016 break;
6017 default:
6018 return false;
6019 }
6020
6021 switch (Kind.getKind()) {
6022 case InitializationKind::IK_DirectList:
6023 return true;
6024 // FIXME: Hack to work around cast weirdness.
6025 case InitializationKind::IK_Direct:
6026 case InitializationKind::IK_Value:
6027 return NumArgs != 1;
6028 default:
6029 return false;
6030 }
6031}
6032
Sebastian Redled2e5322011-12-22 14:44:04 +00006033static ExprResult
6034PerformConstructorInitialization(Sema &S,
6035 const InitializedEntity &Entity,
6036 const InitializationKind &Kind,
6037 MultiExprArg Args,
6038 const InitializationSequence::Step& Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006039 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006040 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006041 bool IsStdInitListInitialization,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006042 SourceLocation LBraceLoc,
6043 SourceLocation RBraceLoc) {
Sebastian Redled2e5322011-12-22 14:44:04 +00006044 unsigned NumArgs = Args.size();
6045 CXXConstructorDecl *Constructor
6046 = cast<CXXConstructorDecl>(Step.Function.Function);
6047 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
6048
6049 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00006050 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redled2e5322011-12-22 14:44:04 +00006051 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
6052 ? Kind.getEqualLoc()
6053 : Kind.getLocation();
6054
6055 if (Kind.getKind() == InitializationKind::IK_Default) {
6056 // Force even a trivial, implicit default constructor to be
6057 // semantically checked. We do this explicitly because we don't build
6058 // the definition for completely trivial constructors.
Matt Beaumont-Gay47ff1222012-02-24 08:37:56 +00006059 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redled2e5322011-12-22 14:44:04 +00006060 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregorf704ade2012-02-24 07:48:37 +00006061 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redled2e5322011-12-22 14:44:04 +00006062 S.DefineImplicitDefaultConstructor(Loc, Constructor);
6063 }
6064
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006065 ExprResult CurInit((Expr *)nullptr);
Sebastian Redled2e5322011-12-22 14:44:04 +00006066
Douglas Gregor6073dca2012-02-24 23:56:31 +00006067 // C++ [over.match.copy]p1:
6068 // - When initializing a temporary to be bound to the first parameter
6069 // of a constructor that takes a reference to possibly cv-qualified
6070 // T as its first argument, called with a single argument in the
6071 // context of direct-initialization, explicit conversion functions
6072 // are also considered.
Richard Smith7c2bcc92016-09-07 02:14:33 +00006073 bool AllowExplicitConv =
6074 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
6075 hasCopyOrMoveCtorParam(S.Context,
6076 getConstructorInfo(Step.Function.FoundDecl));
Douglas Gregor6073dca2012-02-24 23:56:31 +00006077
Sebastian Redled2e5322011-12-22 14:44:04 +00006078 // Determine the arguments required to actually perform the constructor
6079 // call.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006080 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregor6073dca2012-02-24 23:56:31 +00006081 Loc, ConstructorArgs,
Richard Smith6b216962013-02-05 05:52:24 +00006082 AllowExplicitConv,
6083 IsListInitialization))
Sebastian Redled2e5322011-12-22 14:44:04 +00006084 return ExprError();
6085
6086
Jordan Rose6c0505e2013-05-06 16:48:12 +00006087 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redled2e5322011-12-22 14:44:04 +00006088 // An explicitly-constructed temporary, e.g., X(1, 2).
Richard Smith22262ab2013-05-04 06:44:46 +00006089 if (S.DiagnoseUseOfDecl(Constructor, Loc))
6090 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00006091
6092 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6093 if (!TSInfo)
6094 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Vedant Kumara14a1f92018-01-17 18:53:51 +00006095 SourceRange ParenOrBraceRange = Kind.getParenOrBraceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006096
Richard Smith5179eb72016-06-28 19:03:57 +00006097 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
Richard Smith80a47022016-06-29 01:10:27 +00006098 Step.Function.FoundDecl.getDecl())) {
Richard Smith5179eb72016-06-28 19:03:57 +00006099 Constructor = S.findInheritingConstructor(Loc, Constructor, Shadow);
Richard Smith80a47022016-06-29 01:10:27 +00006100 if (S.DiagnoseUseOfDecl(Constructor, Loc))
6101 return ExprError();
6102 }
Richard Smith5179eb72016-06-28 19:03:57 +00006103 S.MarkFunctionReferenced(Loc, Constructor);
6104
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006105 CurInit = new (S.Context) CXXTemporaryObjectExpr(
Richard Smith60437622017-02-09 19:17:44 +00006106 S.Context, Constructor,
6107 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
Richard Smithc2bebe92016-05-11 20:37:46 +00006108 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
6109 IsListInitialization, IsStdInitListInitialization,
6110 ConstructorInitRequiresZeroInit);
Sebastian Redled2e5322011-12-22 14:44:04 +00006111 } else {
6112 CXXConstructExpr::ConstructionKind ConstructKind =
6113 CXXConstructExpr::CK_Complete;
6114
6115 if (Entity.getKind() == InitializedEntity::EK_Base) {
6116 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
6117 CXXConstructExpr::CK_VirtualBase :
6118 CXXConstructExpr::CK_NonVirtualBase;
6119 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
6120 ConstructKind = CXXConstructExpr::CK_Delegating;
6121 }
6122
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006123 // Only get the parenthesis or brace range if it is a list initialization or
6124 // direct construction.
6125 SourceRange ParenOrBraceRange;
6126 if (IsListInitialization)
6127 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
6128 else if (Kind.getKind() == InitializationKind::IK_Direct)
Vedant Kumara14a1f92018-01-17 18:53:51 +00006129 ParenOrBraceRange = Kind.getParenOrBraceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006130
6131 // If the entity allows NRVO, mark the construction as elidable
6132 // unconditionally.
6133 if (Entity.allowsNRVO())
Richard Smith410306b2016-12-12 02:53:20 +00006134 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
Richard Smithc2bebe92016-05-11 20:37:46 +00006135 Step.Function.FoundDecl,
Sebastian Redled2e5322011-12-22 14:44:04 +00006136 Constructor, /*Elidable=*/true,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006137 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00006138 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006139 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006140 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00006141 ConstructorInitRequiresZeroInit,
6142 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006143 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00006144 else
Richard Smith410306b2016-12-12 02:53:20 +00006145 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
Richard Smithc2bebe92016-05-11 20:37:46 +00006146 Step.Function.FoundDecl,
Sebastian Redled2e5322011-12-22 14:44:04 +00006147 Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006148 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00006149 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006150 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006151 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00006152 ConstructorInitRequiresZeroInit,
6153 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00006154 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00006155 }
6156 if (CurInit.isInvalid())
6157 return ExprError();
6158
6159 // Only check access if all of that succeeded.
Richard Smith5179eb72016-06-28 19:03:57 +00006160 S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
Richard Smith22262ab2013-05-04 06:44:46 +00006161 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
6162 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00006163
6164 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006165 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redled2e5322011-12-22 14:44:04 +00006166
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006167 return CurInit;
Sebastian Redled2e5322011-12-22 14:44:04 +00006168}
6169
Richard Smithd87aab92018-07-17 22:24:09 +00006170namespace {
6171enum LifetimeKind {
6172 /// The lifetime of a temporary bound to this entity ends at the end of the
6173 /// full-expression, and that's (probably) fine.
6174 LK_FullExpression,
6175
6176 /// The lifetime of a temporary bound to this entity is extended to the
6177 /// lifeitme of the entity itself.
6178 LK_Extended,
6179
6180 /// The lifetime of a temporary bound to this entity probably ends too soon,
6181 /// because the entity is allocated in a new-expression.
6182 LK_New,
6183
6184 /// The lifetime of a temporary bound to this entity ends too soon, because
6185 /// the entity is a return object.
6186 LK_Return,
6187
Richard Smith67af95b2018-07-23 19:19:08 +00006188 /// The lifetime of a temporary bound to this entity ends too soon, because
6189 /// the entity is the result of a statement expression.
6190 LK_StmtExprResult,
6191
Richard Smithd87aab92018-07-17 22:24:09 +00006192 /// This is a mem-initializer: if it would extend a temporary (other than via
6193 /// a default member initializer), the program is ill-formed.
6194 LK_MemInitializer,
6195};
6196using LifetimeResult =
6197 llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>;
6198}
6199
Richard Smithe6c01442013-06-05 00:46:14 +00006200/// Determine the declaration which an initialized entity ultimately refers to,
6201/// for the purpose of lifetime-extending a temporary bound to a reference in
6202/// the initialization of \p Entity.
Richard Smithca975b22018-07-23 18:50:26 +00006203static LifetimeResult getEntityLifetime(
David Majnemerdaff3702014-05-01 17:50:17 +00006204 const InitializedEntity *Entity,
Richard Smithd87aab92018-07-17 22:24:09 +00006205 const InitializedEntity *InitField = nullptr) {
Richard Smithe6c01442013-06-05 00:46:14 +00006206 // C++11 [class.temporary]p5:
David Majnemerdaff3702014-05-01 17:50:17 +00006207 switch (Entity->getKind()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006208 case InitializedEntity::EK_Variable:
6209 // The temporary [...] persists for the lifetime of the reference
Richard Smithd87aab92018-07-17 22:24:09 +00006210 return {Entity, LK_Extended};
Richard Smithe6c01442013-06-05 00:46:14 +00006211
6212 case InitializedEntity::EK_Member:
6213 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00006214 if (Entity->getParent())
Richard Smithca975b22018-07-23 18:50:26 +00006215 return getEntityLifetime(Entity->getParent(), Entity);
Richard Smithe6c01442013-06-05 00:46:14 +00006216
6217 // except:
Richard Smithd87aab92018-07-17 22:24:09 +00006218 // C++17 [class.base.init]p8:
6219 // A temporary expression bound to a reference member in a
6220 // mem-initializer is ill-formed.
6221 // C++17 [class.base.init]p11:
6222 // A temporary expression bound to a reference member from a
6223 // default member initializer is ill-formed.
6224 //
6225 // The context of p11 and its example suggest that it's only the use of a
6226 // default member initializer from a constructor that makes the program
6227 // ill-formed, not its mere existence, and that it can even be used by
6228 // aggregate initialization.
6229 return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended
6230 : LK_MemInitializer};
Richard Smithe6c01442013-06-05 00:46:14 +00006231
Richard Smith7873de02016-08-11 22:25:46 +00006232 case InitializedEntity::EK_Binding:
Richard Smith3997b1b2016-08-12 01:55:21 +00006233 // Per [dcl.decomp]p3, the binding is treated as a variable of reference
6234 // type.
Richard Smithd87aab92018-07-17 22:24:09 +00006235 return {Entity, LK_Extended};
Richard Smith7873de02016-08-11 22:25:46 +00006236
Richard Smithe6c01442013-06-05 00:46:14 +00006237 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006238 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithe6c01442013-06-05 00:46:14 +00006239 // -- A temporary bound to a reference parameter in a function call
6240 // persists until the completion of the full-expression containing
6241 // the call.
Richard Smithd87aab92018-07-17 22:24:09 +00006242 return {nullptr, LK_FullExpression};
6243
Richard Smithe6c01442013-06-05 00:46:14 +00006244 case InitializedEntity::EK_Result:
6245 // -- The lifetime of a temporary bound to the returned value in a
6246 // function return statement is not extended; the temporary is
6247 // destroyed at the end of the full-expression in the return statement.
Richard Smithd87aab92018-07-17 22:24:09 +00006248 return {nullptr, LK_Return};
6249
Richard Smith67af95b2018-07-23 19:19:08 +00006250 case InitializedEntity::EK_StmtExprResult:
6251 // FIXME: Should we lifetime-extend through the result of a statement
6252 // expression?
6253 return {nullptr, LK_StmtExprResult};
6254
Richard Smithe6c01442013-06-05 00:46:14 +00006255 case InitializedEntity::EK_New:
6256 // -- A temporary bound to a reference in a new-initializer persists
6257 // until the completion of the full-expression containing the
6258 // new-initializer.
Richard Smithd87aab92018-07-17 22:24:09 +00006259 return {nullptr, LK_New};
Richard Smithe6c01442013-06-05 00:46:14 +00006260
6261 case InitializedEntity::EK_Temporary:
6262 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00006263 case InitializedEntity::EK_RelatedResult:
Richard Smithe6c01442013-06-05 00:46:14 +00006264 // We don't yet know the storage duration of the surrounding temporary.
6265 // Assume it's got full-expression duration for now, it will patch up our
6266 // storage duration if that's not correct.
Richard Smithd87aab92018-07-17 22:24:09 +00006267 return {nullptr, LK_FullExpression};
Richard Smithe6c01442013-06-05 00:46:14 +00006268
6269 case InitializedEntity::EK_ArrayElement:
6270 // For subobjects, we look at the complete object.
Richard Smithca975b22018-07-23 18:50:26 +00006271 return getEntityLifetime(Entity->getParent(), InitField);
Richard Smithe6c01442013-06-05 00:46:14 +00006272
6273 case InitializedEntity::EK_Base:
Richard Smith872307e2016-03-08 22:17:41 +00006274 // For subobjects, we look at the complete object.
6275 if (Entity->getParent())
Richard Smithca975b22018-07-23 18:50:26 +00006276 return getEntityLifetime(Entity->getParent(), InitField);
Richard Smithd87aab92018-07-17 22:24:09 +00006277 return {InitField, LK_MemInitializer};
6278
Richard Smithe6c01442013-06-05 00:46:14 +00006279 case InitializedEntity::EK_Delegating:
6280 // We can reach this case for aggregate initialization in a constructor:
6281 // struct A { int &&r; };
6282 // struct B : A { B() : A{0} {} };
Richard Smithd87aab92018-07-17 22:24:09 +00006283 // In this case, use the outermost field decl as the context.
6284 return {InitField, LK_MemInitializer};
Richard Smithe6c01442013-06-05 00:46:14 +00006285
6286 case InitializedEntity::EK_BlockElement:
Alex Lorenzb4791c72017-04-06 12:53:43 +00006287 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
Richard Smithe6c01442013-06-05 00:46:14 +00006288 case InitializedEntity::EK_LambdaCapture:
Richard Smithe6c01442013-06-05 00:46:14 +00006289 case InitializedEntity::EK_VectorElement:
6290 case InitializedEntity::EK_ComplexElement:
Richard Smithd87aab92018-07-17 22:24:09 +00006291 return {nullptr, LK_FullExpression};
Richard Smithca975b22018-07-23 18:50:26 +00006292
6293 case InitializedEntity::EK_Exception:
6294 // FIXME: Can we diagnose lifetime problems with exceptions?
6295 return {nullptr, LK_FullExpression};
Richard Smithe6c01442013-06-05 00:46:14 +00006296 }
Benjamin Kramercabc8822013-06-05 15:37:50 +00006297 llvm_unreachable("unknown entity kind");
Richard Smithe6c01442013-06-05 00:46:14 +00006298}
6299
Richard Smithd87aab92018-07-17 22:24:09 +00006300namespace {
Richard Smithca975b22018-07-23 18:50:26 +00006301enum ReferenceKind {
Richard Smithd87aab92018-07-17 22:24:09 +00006302 /// Lifetime would be extended by a reference binding to a temporary.
Richard Smithca975b22018-07-23 18:50:26 +00006303 RK_ReferenceBinding,
Richard Smithd87aab92018-07-17 22:24:09 +00006304 /// Lifetime would be extended by a std::initializer_list object binding to
6305 /// its backing array.
Richard Smithca975b22018-07-23 18:50:26 +00006306 RK_StdInitializerList,
Richard Smithd87aab92018-07-17 22:24:09 +00006307};
Richard Smithca975b22018-07-23 18:50:26 +00006308
Richard Smithafe48f92018-07-23 21:21:22 +00006309/// A temporary or local variable. This will be one of:
6310/// * A MaterializeTemporaryExpr.
6311/// * A DeclRefExpr whose declaration is a local.
6312/// * An AddrLabelExpr.
6313/// * A BlockExpr for a block with captures.
6314using Local = Expr*;
Richard Smithca975b22018-07-23 18:50:26 +00006315
6316/// Expressions we stepped over when looking for the local state. Any steps
6317/// that would inhibit lifetime extension or take us out of subexpressions of
6318/// the initializer are included.
6319struct IndirectLocalPathEntry {
Richard Smithafe48f92018-07-23 21:21:22 +00006320 enum EntryKind {
Richard Smithca975b22018-07-23 18:50:26 +00006321 DefaultInit,
6322 AddressOf,
Richard Smithafe48f92018-07-23 21:21:22 +00006323 VarInit,
6324 LValToRVal,
Richard Smithca975b22018-07-23 18:50:26 +00006325 } Kind;
6326 Expr *E;
Richard Smithafe48f92018-07-23 21:21:22 +00006327 Decl *D = nullptr;
6328 IndirectLocalPathEntry() {}
6329 IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {}
6330 IndirectLocalPathEntry(EntryKind K, Expr *E, Decl *D) : Kind(K), E(E), D(D) {}
Richard Smithca975b22018-07-23 18:50:26 +00006331};
6332
6333using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>;
Richard Smithe6c01442013-06-05 00:46:14 +00006334
Richard Smithd87aab92018-07-17 22:24:09 +00006335struct RevertToOldSizeRAII {
Richard Smithca975b22018-07-23 18:50:26 +00006336 IndirectLocalPath &Path;
Richard Smithd87aab92018-07-17 22:24:09 +00006337 unsigned OldSize = Path.size();
Richard Smithca975b22018-07-23 18:50:26 +00006338 RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {}
Richard Smithd87aab92018-07-17 22:24:09 +00006339 ~RevertToOldSizeRAII() { Path.resize(OldSize); }
6340};
Richard Smithafe48f92018-07-23 21:21:22 +00006341
6342using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L,
6343 ReferenceKind RK)>;
Richard Smithd87aab92018-07-17 22:24:09 +00006344}
6345
Richard Smithafe48f92018-07-23 21:21:22 +00006346static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD) {
6347 for (auto E : Path)
6348 if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD)
6349 return true;
6350 return false;
6351}
6352
Richard Smith0e3102d2018-07-24 00:55:08 +00006353static bool pathContainsInit(IndirectLocalPath &Path) {
6354 return std::any_of(Path.begin(), Path.end(), [=](IndirectLocalPathEntry E) {
6355 return E.Kind == IndirectLocalPathEntry::DefaultInit ||
6356 E.Kind == IndirectLocalPathEntry::VarInit;
6357 });
6358}
6359
Richard Smithca975b22018-07-23 18:50:26 +00006360static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
6361 Expr *Init, LocalVisitor Visit,
6362 bool RevisitSubinits);
Richard Smithd87aab92018-07-17 22:24:09 +00006363
Richard Smithca975b22018-07-23 18:50:26 +00006364/// Visit the locals that would be reachable through a reference bound to the
6365/// glvalue expression \c Init.
Richard Smithca975b22018-07-23 18:50:26 +00006366static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
6367 Expr *Init, ReferenceKind RK,
6368 LocalVisitor Visit) {
Richard Smithd87aab92018-07-17 22:24:09 +00006369 RevertToOldSizeRAII RAII(Path);
6370
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006371 // Walk past any constructs which we can lifetime-extend across.
6372 Expr *Old;
6373 do {
6374 Old = Init;
6375
Richard Smithafe48f92018-07-23 21:21:22 +00006376 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
6377 Init = EWC->getSubExpr();
6378
Richard Smithdbc82492015-01-10 01:28:13 +00006379 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithd87aab92018-07-17 22:24:09 +00006380 // If this is just redundant braces around an initializer, step over it.
6381 if (ILE->isTransparent())
Richard Smithdbc82492015-01-10 01:28:13 +00006382 Init = ILE->getInit(0);
Richard Smithdbc82492015-01-10 01:28:13 +00006383 }
6384
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006385 // Step over any subobject adjustments; we may have a materialized
6386 // temporary inside them.
Richard Smith4baaa5a2016-12-03 01:14:32 +00006387 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006388
6389 // Per current approach for DR1376, look through casts to reference type
6390 // when performing lifetime extension.
6391 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
6392 if (CE->getSubExpr()->isGLValue())
6393 Init = CE->getSubExpr();
6394
Richard Smithb3189a12016-12-05 07:49:14 +00006395 // Per the current approach for DR1299, look through array element access
Richard Smithca975b22018-07-23 18:50:26 +00006396 // on array glvalues when performing lifetime extension.
6397 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) {
Richard Smithafe48f92018-07-23 21:21:22 +00006398 Init = ASE->getBase();
6399 auto *ICE = dyn_cast<ImplicitCastExpr>(Init);
6400 if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay)
6401 Init = ICE->getSubExpr();
6402 else
6403 // We can't lifetime extend through this but we might still find some
6404 // retained temporaries.
6405 return visitLocalsRetainedByInitializer(Path, Init, Visit, true);
Richard Smithca975b22018-07-23 18:50:26 +00006406 }
Richard Smithd87aab92018-07-17 22:24:09 +00006407
6408 // Step into CXXDefaultInitExprs so we can diagnose cases where a
6409 // constructor inherits one as an implicit mem-initializer.
6410 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
Richard Smithafe48f92018-07-23 21:21:22 +00006411 Path.push_back(
6412 {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
Richard Smithd87aab92018-07-17 22:24:09 +00006413 Init = DIE->getExpr();
Richard Smithd87aab92018-07-17 22:24:09 +00006414 }
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006415 } while (Init != Old);
6416
Richard Smithd87aab92018-07-17 22:24:09 +00006417 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) {
Richard Smithca975b22018-07-23 18:50:26 +00006418 if (Visit(Path, Local(MTE), RK))
6419 visitLocalsRetainedByInitializer(Path, MTE->GetTemporaryExpr(), Visit,
6420 true);
6421 }
6422
Richard Smithafe48f92018-07-23 21:21:22 +00006423 switch (Init->getStmtClass()) {
6424 case Stmt::DeclRefExprClass: {
6425 // If we find the name of a local non-reference parameter, we could have a
6426 // lifetime problem.
6427 auto *DRE = cast<DeclRefExpr>(Init);
Richard Smithca975b22018-07-23 18:50:26 +00006428 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
6429 if (VD && VD->hasLocalStorage() &&
6430 !DRE->refersToEnclosingVariableOrCapture()) {
Richard Smithafe48f92018-07-23 21:21:22 +00006431 if (!VD->getType()->isReferenceType()) {
6432 Visit(Path, Local(DRE), RK);
6433 } else if (isa<ParmVarDecl>(DRE->getDecl())) {
6434 // The lifetime of a reference parameter is unknown; assume it's OK
6435 // for now.
6436 break;
6437 } else if (VD->getInit() && !isVarOnPath(Path, VD)) {
6438 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
6439 visitLocalsRetainedByReferenceBinding(Path, VD->getInit(),
6440 RK_ReferenceBinding, Visit);
6441 }
Richard Smithca975b22018-07-23 18:50:26 +00006442 }
Richard Smithafe48f92018-07-23 21:21:22 +00006443 break;
6444 }
6445
6446 case Stmt::UnaryOperatorClass: {
6447 // The only unary operator that make sense to handle here
6448 // is Deref. All others don't resolve to a "name." This includes
6449 // handling all sorts of rvalues passed to a unary operator.
6450 const UnaryOperator *U = cast<UnaryOperator>(Init);
6451 if (U->getOpcode() == UO_Deref)
6452 visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true);
6453 break;
6454 }
6455
6456 case Stmt::OMPArraySectionExprClass: {
6457 visitLocalsRetainedByInitializer(
6458 Path, cast<OMPArraySectionExpr>(Init)->getBase(), Visit, true);
6459 break;
6460 }
6461
6462 case Stmt::ConditionalOperatorClass:
6463 case Stmt::BinaryConditionalOperatorClass: {
6464 auto *C = cast<AbstractConditionalOperator>(Init);
6465 if (!C->getTrueExpr()->getType()->isVoidType())
6466 visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit);
6467 if (!C->getFalseExpr()->getType()->isVoidType())
6468 visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit);
6469 break;
6470 }
6471
6472 // FIXME: Visit the left-hand side of an -> or ->*.
6473
6474 default:
6475 break;
Richard Smithe6c01442013-06-05 00:46:14 +00006476 }
6477}
6478
Richard Smithca975b22018-07-23 18:50:26 +00006479/// Visit the locals that would be reachable through an object initialized by
6480/// the prvalue expression \c Init.
Richard Smithca975b22018-07-23 18:50:26 +00006481static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
6482 Expr *Init, LocalVisitor Visit,
6483 bool RevisitSubinits) {
Richard Smithd87aab92018-07-17 22:24:09 +00006484 RevertToOldSizeRAII RAII(Path);
6485
6486 // Step into CXXDefaultInitExprs so we can diagnose cases where a
6487 // constructor inherits one as an implicit mem-initializer.
6488 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
Richard Smithafe48f92018-07-23 21:21:22 +00006489 Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
Richard Smithd87aab92018-07-17 22:24:09 +00006490 Init = DIE->getExpr();
Richard Smithd87aab92018-07-17 22:24:09 +00006491 }
6492
Richard Smithafe48f92018-07-23 21:21:22 +00006493 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
6494 Init = EWC->getSubExpr();
6495
Richard Smithe6c01442013-06-05 00:46:14 +00006496 // Dig out the expression which constructs the extended temporary.
Richard Smith4baaa5a2016-12-03 01:14:32 +00006497 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
Richard Smithe6c01442013-06-05 00:46:14 +00006498
Richard Smith736a9472013-06-12 20:42:33 +00006499 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
6500 Init = BTE->getSubExpr();
6501
Richard Smithd87aab92018-07-17 22:24:09 +00006502 // C++17 [dcl.init.list]p6:
6503 // initializing an initializer_list object from the array extends the
6504 // lifetime of the array exactly like binding a reference to a temporary.
6505 if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Init))
Richard Smithca975b22018-07-23 18:50:26 +00006506 return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(),
6507 RK_StdInitializerList, Visit);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006508
Richard Smithe6c01442013-06-05 00:46:14 +00006509 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithca975b22018-07-23 18:50:26 +00006510 // We already visited the elements of this initializer list while
6511 // performing the initialization. Don't visit them again unless we've
6512 // changed the lifetime of the initialized entity.
6513 if (!RevisitSubinits)
6514 return;
6515
Richard Smithd87aab92018-07-17 22:24:09 +00006516 if (ILE->isTransparent())
Richard Smithca975b22018-07-23 18:50:26 +00006517 return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit,
6518 RevisitSubinits);
Richard Smithd87aab92018-07-17 22:24:09 +00006519
Richard Smithcc1b96d2013-06-12 22:31:48 +00006520 if (ILE->getType()->isArrayType()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006521 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
Richard Smithca975b22018-07-23 18:50:26 +00006522 visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit,
6523 RevisitSubinits);
Richard Smithe6c01442013-06-05 00:46:14 +00006524 return;
6525 }
6526
Richard Smithcc1b96d2013-06-12 22:31:48 +00006527 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00006528 assert(RD->isAggregate() && "aggregate init on non-aggregate");
6529
6530 // If we lifetime-extend a braced initializer which is initializing an
6531 // aggregate, and that aggregate contains reference members which are
6532 // bound to temporaries, those temporaries are also lifetime-extended.
6533 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
6534 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
Richard Smithca975b22018-07-23 18:50:26 +00006535 visitLocalsRetainedByReferenceBinding(Path, ILE->getInit(0),
6536 RK_ReferenceBinding, Visit);
Richard Smithe6c01442013-06-05 00:46:14 +00006537 else {
6538 unsigned Index = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006539 for (const auto *I : RD->fields()) {
Richard Smith0bca59d2013-07-01 06:08:20 +00006540 if (Index >= ILE->getNumInits())
6541 break;
Richard Smithe6c01442013-06-05 00:46:14 +00006542 if (I->isUnnamedBitfield())
6543 continue;
Richard Smith8d7f11d2013-06-27 22:54:33 +00006544 Expr *SubInit = ILE->getInit(Index);
Richard Smithe6c01442013-06-05 00:46:14 +00006545 if (I->getType()->isReferenceType())
Richard Smithca975b22018-07-23 18:50:26 +00006546 visitLocalsRetainedByReferenceBinding(Path, SubInit,
6547 RK_ReferenceBinding, Visit);
Richard Smithd87aab92018-07-17 22:24:09 +00006548 else
6549 // This might be either aggregate-initialization of a member or
6550 // initialization of a std::initializer_list object. Regardless,
Richard Smithe6c01442013-06-05 00:46:14 +00006551 // we should recursively lifetime-extend that initializer.
Richard Smithca975b22018-07-23 18:50:26 +00006552 visitLocalsRetainedByInitializer(Path, SubInit, Visit,
6553 RevisitSubinits);
Richard Smithe6c01442013-06-05 00:46:14 +00006554 ++Index;
6555 }
6556 }
6557 }
Richard Smithca975b22018-07-23 18:50:26 +00006558 return;
6559 }
6560
Richard Smithafe48f92018-07-23 21:21:22 +00006561 // Step over value-preserving rvalue casts.
6562 while (auto *CE = dyn_cast<CastExpr>(Init)) {
6563 switch (CE->getCastKind()) {
6564 case CK_LValueToRValue:
6565 // If we can match the lvalue to a const object, we can look at its
6566 // initializer.
6567 Path.push_back({IndirectLocalPathEntry::LValToRVal, CE});
6568 return visitLocalsRetainedByReferenceBinding(
6569 Path, Init, RK_ReferenceBinding,
6570 [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool {
6571 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
6572 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
6573 if (VD && VD->getType().isConstQualified() && VD->getInit()) {
6574 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
6575 visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true);
6576 }
6577 } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) {
6578 if (MTE->getType().isConstQualified())
6579 visitLocalsRetainedByInitializer(Path, MTE->GetTemporaryExpr(),
6580 Visit, true);
6581 }
6582 return false;
6583 });
6584
6585 // We assume that objects can be retained by pointers cast to integers,
6586 // but not if the integer is cast to floating-point type or to _Complex.
6587 // We assume that casts to 'bool' do not preserve enough information to
6588 // retain a local object.
6589 case CK_NoOp:
6590 case CK_BitCast:
6591 case CK_BaseToDerived:
6592 case CK_DerivedToBase:
6593 case CK_UncheckedDerivedToBase:
6594 case CK_Dynamic:
6595 case CK_ToUnion:
6596 case CK_IntegralToPointer:
6597 case CK_PointerToIntegral:
6598 case CK_VectorSplat:
6599 case CK_IntegralCast:
6600 case CK_CPointerToObjCPointerCast:
6601 case CK_BlockPointerToObjCPointerCast:
6602 case CK_AnyPointerToBlockPointerCast:
6603 case CK_AddressSpaceConversion:
6604 break;
6605
6606 case CK_ArrayToPointerDecay:
6607 // Model array-to-pointer decay as taking the address of the array
6608 // lvalue.
6609 Path.push_back({IndirectLocalPathEntry::AddressOf, CE});
6610 return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(),
Richard Smithca975b22018-07-23 18:50:26 +00006611 RK_ReferenceBinding, Visit);
Richard Smithafe48f92018-07-23 21:21:22 +00006612
6613 default:
6614 return;
Richard Smithca975b22018-07-23 18:50:26 +00006615 }
Richard Smithafe48f92018-07-23 21:21:22 +00006616
6617 Init = CE->getSubExpr();
6618 }
6619
6620 Init = Init->IgnoreParens();
6621 switch (Init->getStmtClass()) {
6622 case Stmt::UnaryOperatorClass: {
6623 auto *UO = cast<UnaryOperator>(Init);
6624 // If the initializer is the address of a local, we could have a lifetime
6625 // problem.
6626 if (UO->getOpcode() == UO_AddrOf) {
Richard Smith0e3102d2018-07-24 00:55:08 +00006627 // If this is &rvalue, then it's ill-formed and we have already diagnosed
6628 // it. Don't produce a redundant warning about the lifetime of the
6629 // temporary.
6630 if (isa<MaterializeTemporaryExpr>(UO->getSubExpr()))
6631 return;
6632
Richard Smithafe48f92018-07-23 21:21:22 +00006633 Path.push_back({IndirectLocalPathEntry::AddressOf, UO});
6634 visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(),
6635 RK_ReferenceBinding, Visit);
6636 }
6637 break;
6638 }
6639
6640 case Stmt::BinaryOperatorClass: {
6641 // Handle pointer arithmetic.
6642 auto *BO = cast<BinaryOperator>(Init);
6643 BinaryOperatorKind BOK = BO->getOpcode();
6644 if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub))
6645 break;
6646
6647 if (BO->getLHS()->getType()->isPointerType())
6648 visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true);
6649 else if (BO->getRHS()->getType()->isPointerType())
6650 visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true);
6651 break;
6652 }
6653
6654 case Stmt::ConditionalOperatorClass:
6655 case Stmt::BinaryConditionalOperatorClass: {
6656 auto *C = cast<AbstractConditionalOperator>(Init);
6657 // In C++, we can have a throw-expression operand, which has 'void' type
6658 // and isn't interesting from a lifetime perspective.
6659 if (!C->getTrueExpr()->getType()->isVoidType())
6660 visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true);
6661 if (!C->getFalseExpr()->getType()->isVoidType())
6662 visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true);
6663 break;
6664 }
6665
6666 case Stmt::BlockExprClass:
6667 if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) {
6668 // This is a local block, whose lifetime is that of the function.
6669 Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding);
6670 }
6671 break;
6672
6673 case Stmt::AddrLabelExprClass:
6674 // We want to warn if the address of a label would escape the function.
6675 Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding);
6676 break;
6677
6678 default:
6679 break;
Richard Smithe6c01442013-06-05 00:46:14 +00006680 }
6681}
6682
Richard Smithd87aab92018-07-17 22:24:09 +00006683/// Determine whether this is an indirect path to a temporary that we are
6684/// supposed to lifetime-extend along (but don't).
Richard Smithca975b22018-07-23 18:50:26 +00006685static bool shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) {
Richard Smithd87aab92018-07-17 22:24:09 +00006686 for (auto Elem : Path) {
Richard Smithf66e4f72018-07-23 22:56:45 +00006687 if (Elem.Kind != IndirectLocalPathEntry::DefaultInit)
Richard Smithd87aab92018-07-17 22:24:09 +00006688 return false;
6689 }
6690 return true;
6691}
6692
Richard Smith6a32c052018-07-23 21:21:24 +00006693/// Find the range for the first interesting entry in the path at or after I.
6694static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I,
6695 Expr *E) {
6696 for (unsigned N = Path.size(); I != N; ++I) {
6697 switch (Path[I].Kind) {
6698 case IndirectLocalPathEntry::AddressOf:
6699 case IndirectLocalPathEntry::LValToRVal:
Richard Smith6a32c052018-07-23 21:21:24 +00006700 // These exist primarily to mark the path as not permitting or
6701 // supporting lifetime extension.
6702 break;
6703
6704 case IndirectLocalPathEntry::DefaultInit:
6705 case IndirectLocalPathEntry::VarInit:
6706 return Path[I].E->getSourceRange();
6707 }
6708 }
6709 return E->getSourceRange();
6710}
6711
Richard Smithd87aab92018-07-17 22:24:09 +00006712void Sema::checkInitializerLifetime(const InitializedEntity &Entity,
6713 Expr *Init) {
Richard Smithca975b22018-07-23 18:50:26 +00006714 LifetimeResult LR = getEntityLifetime(&Entity);
Richard Smithd87aab92018-07-17 22:24:09 +00006715 LifetimeKind LK = LR.getInt();
6716 const InitializedEntity *ExtendingEntity = LR.getPointer();
6717
6718 // If this entity doesn't have an interesting lifetime, don't bother looking
6719 // for temporaries within its initializer.
6720 if (LK == LK_FullExpression)
6721 return;
6722
Richard Smithca975b22018-07-23 18:50:26 +00006723 auto TemporaryVisitor = [&](IndirectLocalPath &Path, Local L,
6724 ReferenceKind RK) -> bool {
Richard Smith6a32c052018-07-23 21:21:24 +00006725 SourceRange DiagRange = nextPathEntryRange(Path, 0, L);
6726 SourceLocation DiagLoc = DiagRange.getBegin();
Richard Smithca975b22018-07-23 18:50:26 +00006727
Richard Smithd87aab92018-07-17 22:24:09 +00006728 switch (LK) {
6729 case LK_FullExpression:
6730 llvm_unreachable("already handled this");
6731
Richard Smithafe48f92018-07-23 21:21:22 +00006732 case LK_Extended: {
6733 auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L);
Richard Smith0e3102d2018-07-24 00:55:08 +00006734 if (!MTE) {
6735 // The initialized entity has lifetime beyond the full-expression,
6736 // and the local entity does too, so don't warn.
6737 //
6738 // FIXME: We should consider warning if a static / thread storage
6739 // duration variable retains an automatic storage duration local.
Richard Smithafe48f92018-07-23 21:21:22 +00006740 return false;
Richard Smith0e3102d2018-07-24 00:55:08 +00006741 }
Richard Smithafe48f92018-07-23 21:21:22 +00006742
Richard Smithd87aab92018-07-17 22:24:09 +00006743 // Lifetime-extend the temporary.
6744 if (Path.empty()) {
6745 // Update the storage duration of the materialized temporary.
6746 // FIXME: Rebuild the expression instead of mutating it.
6747 MTE->setExtendingDecl(ExtendingEntity->getDecl(),
6748 ExtendingEntity->allocateManglingNumber());
6749 // Also visit the temporaries lifetime-extended by this initializer.
6750 return true;
6751 }
6752
6753 if (shouldLifetimeExtendThroughPath(Path)) {
6754 // We're supposed to lifetime-extend the temporary along this path (per
6755 // the resolution of DR1815), but we don't support that yet.
6756 //
Richard Smith0e3102d2018-07-24 00:55:08 +00006757 // FIXME: Properly handle this situation. Perhaps the easiest approach
Richard Smithd87aab92018-07-17 22:24:09 +00006758 // would be to clone the initializer expression on each use that would
6759 // lifetime extend its temporaries.
Richard Smith0e3102d2018-07-24 00:55:08 +00006760 Diag(DiagLoc, diag::warn_unsupported_lifetime_extension)
6761 << RK << DiagRange;
Richard Smithd87aab92018-07-17 22:24:09 +00006762 } else {
Richard Smith0e3102d2018-07-24 00:55:08 +00006763 // If the path goes through the initialization of a variable or field,
6764 // it can't possibly reach a temporary created in this full-expression.
6765 // We will have already diagnosed any problems with the initializer.
6766 if (pathContainsInit(Path))
6767 return false;
6768
6769 Diag(DiagLoc, diag::warn_dangling_variable)
6770 << RK << !Entity.getParent() << ExtendingEntity->getDecl()
6771 << Init->isGLValue() << DiagRange;
Richard Smithd87aab92018-07-17 22:24:09 +00006772 }
6773 break;
Richard Smithafe48f92018-07-23 21:21:22 +00006774 }
Richard Smithd87aab92018-07-17 22:24:09 +00006775
Richard Smithafe48f92018-07-23 21:21:22 +00006776 case LK_MemInitializer: {
George Burgess IV06df2292018-07-24 02:10:53 +00006777 if (isa<MaterializeTemporaryExpr>(L)) {
Richard Smithafe48f92018-07-23 21:21:22 +00006778 // Under C++ DR1696, if a mem-initializer (or a default member
6779 // initializer used by the absence of one) would lifetime-extend a
6780 // temporary, the program is ill-formed.
6781 if (auto *ExtendingDecl =
6782 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
6783 bool IsSubobjectMember = ExtendingEntity != &Entity;
Richard Smith0e3102d2018-07-24 00:55:08 +00006784 Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path)
6785 ? diag::err_dangling_member
6786 : diag::warn_dangling_member)
Richard Smithafe48f92018-07-23 21:21:22 +00006787 << ExtendingDecl << IsSubobjectMember << RK << DiagRange;
6788 // Don't bother adding a note pointing to the field if we're inside
6789 // its default member initializer; our primary diagnostic points to
6790 // the same place in that case.
6791 if (Path.empty() ||
6792 Path.back().Kind != IndirectLocalPathEntry::DefaultInit) {
6793 Diag(ExtendingDecl->getLocation(),
6794 diag::note_lifetime_extending_member_declared_here)
6795 << RK << IsSubobjectMember;
6796 }
6797 } else {
6798 // We have a mem-initializer but no particular field within it; this
6799 // is either a base class or a delegating initializer directly
6800 // initializing the base-class from something that doesn't live long
6801 // enough.
6802 //
6803 // FIXME: Warn on this.
6804 return false;
Richard Smithd87aab92018-07-17 22:24:09 +00006805 }
6806 } else {
Richard Smithafe48f92018-07-23 21:21:22 +00006807 // Paths via a default initializer can only occur during error recovery
6808 // (there's no other way that a default initializer can refer to a
6809 // local). Don't produce a bogus warning on those cases.
Richard Smith0e3102d2018-07-24 00:55:08 +00006810 if (pathContainsInit(Path))
Richard Smithafe48f92018-07-23 21:21:22 +00006811 return false;
6812
6813 auto *DRE = dyn_cast<DeclRefExpr>(L);
6814 auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr;
6815 if (!VD) {
6816 // A member was initialized to a local block.
6817 // FIXME: Warn on this.
6818 return false;
6819 }
6820
6821 if (auto *Member =
6822 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
6823 bool IsPointer = Member->getType()->isAnyPointerType();
6824 Diag(DiagLoc, IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
6825 : diag::warn_bind_ref_member_to_parameter)
6826 << Member << VD << isa<ParmVarDecl>(VD) << DiagRange;
6827 Diag(Member->getLocation(),
6828 diag::note_ref_or_ptr_member_declared_here)
6829 << (unsigned)IsPointer;
6830 }
Richard Smithd87aab92018-07-17 22:24:09 +00006831 }
6832 break;
Richard Smithafe48f92018-07-23 21:21:22 +00006833 }
Richard Smithd87aab92018-07-17 22:24:09 +00006834
6835 case LK_New:
George Burgess IV06df2292018-07-24 02:10:53 +00006836 if (isa<MaterializeTemporaryExpr>(L)) {
Richard Smithafe48f92018-07-23 21:21:22 +00006837 Diag(DiagLoc, RK == RK_ReferenceBinding
6838 ? diag::warn_new_dangling_reference
6839 : diag::warn_new_dangling_initializer_list)
Richard Smith0e3102d2018-07-24 00:55:08 +00006840 << !Entity.getParent() << DiagRange;
Richard Smithd87aab92018-07-17 22:24:09 +00006841 } else {
Richard Smithafe48f92018-07-23 21:21:22 +00006842 // We can't determine if the allocation outlives the local declaration.
6843 return false;
Richard Smithd87aab92018-07-17 22:24:09 +00006844 }
6845 break;
6846
6847 case LK_Return:
Richard Smith67af95b2018-07-23 19:19:08 +00006848 case LK_StmtExprResult:
Richard Smithafe48f92018-07-23 21:21:22 +00006849 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
6850 // We can't determine if the local variable outlives the statement
6851 // expression.
6852 if (LK == LK_StmtExprResult)
6853 return false;
6854 Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
6855 << Entity.getType()->isReferenceType() << DRE->getDecl()
6856 << isa<ParmVarDecl>(DRE->getDecl()) << DiagRange;
6857 } else if (isa<BlockExpr>(L)) {
6858 Diag(DiagLoc, diag::err_ret_local_block) << DiagRange;
6859 } else if (isa<AddrLabelExpr>(L)) {
6860 Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange;
6861 } else {
6862 Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref)
6863 << Entity.getType()->isReferenceType() << DiagRange;
6864 }
6865 break;
Florian Hahn0aa117d2018-07-17 09:23:31 +00006866 }
6867
Richard Smithafe48f92018-07-23 21:21:22 +00006868 for (unsigned I = 0; I != Path.size(); ++I) {
6869 auto Elem = Path[I];
6870
Richard Smithca975b22018-07-23 18:50:26 +00006871 switch (Elem.Kind) {
Richard Smithafe48f92018-07-23 21:21:22 +00006872 case IndirectLocalPathEntry::AddressOf:
6873 case IndirectLocalPathEntry::LValToRVal:
Richard Smith6a32c052018-07-23 21:21:24 +00006874 // These exist primarily to mark the path as not permitting or
6875 // supporting lifetime extension.
Richard Smithca975b22018-07-23 18:50:26 +00006876 break;
6877
Richard Smithafe48f92018-07-23 21:21:22 +00006878 case IndirectLocalPathEntry::DefaultInit: {
6879 auto *FD = cast<FieldDecl>(Elem.D);
6880 Diag(FD->getLocation(), diag::note_init_with_default_member_initalizer)
Richard Smith6a32c052018-07-23 21:21:24 +00006881 << FD << nextPathEntryRange(Path, I + 1, L);
Richard Smithafe48f92018-07-23 21:21:22 +00006882 break;
6883 }
6884
6885 case IndirectLocalPathEntry::VarInit:
6886 const VarDecl *VD = cast<VarDecl>(Elem.D);
6887 Diag(VD->getLocation(), diag::note_local_var_initializer)
Richard Smith6a32c052018-07-23 21:21:24 +00006888 << VD->getType()->isReferenceType() << VD->getDeclName()
6889 << nextPathEntryRange(Path, I + 1, L);
Richard Smithca975b22018-07-23 18:50:26 +00006890 break;
Florian Hahn0aa117d2018-07-17 09:23:31 +00006891 }
6892 }
Richard Smithd87aab92018-07-17 22:24:09 +00006893
6894 // We didn't lifetime-extend, so don't go any further; we don't need more
6895 // warnings or errors on inner temporaries within this one's initializer.
6896 return false;
6897 };
6898
Richard Smithca975b22018-07-23 18:50:26 +00006899 llvm::SmallVector<IndirectLocalPathEntry, 8> Path;
Richard Smithd87aab92018-07-17 22:24:09 +00006900 if (Init->isGLValue())
Richard Smithca975b22018-07-23 18:50:26 +00006901 visitLocalsRetainedByReferenceBinding(Path, Init, RK_ReferenceBinding,
6902 TemporaryVisitor);
Richard Smithd87aab92018-07-17 22:24:09 +00006903 else
Richard Smithca975b22018-07-23 18:50:26 +00006904 visitLocalsRetainedByInitializer(Path, Init, TemporaryVisitor, false);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006905}
6906
Richard Smithaaa0ec42013-09-21 21:19:19 +00006907static void DiagnoseNarrowingInInitList(Sema &S,
6908 const ImplicitConversionSequence &ICS,
6909 QualType PreNarrowingType,
6910 QualType EntityType,
6911 const Expr *PostInit);
6912
Richard Trieuac3eca52015-04-29 01:52:17 +00006913/// Provide warnings when std::move is used on construction.
6914static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
6915 bool IsReturnStmt) {
6916 if (!InitExpr)
6917 return;
6918
Richard Smith51ec0cf2017-02-21 01:17:38 +00006919 if (S.inTemplateInstantiation())
Richard Trieu6093d142015-07-29 17:03:34 +00006920 return;
6921
Richard Trieuac3eca52015-04-29 01:52:17 +00006922 QualType DestType = InitExpr->getType();
6923 if (!DestType->isRecordType())
6924 return;
6925
6926 unsigned DiagID = 0;
6927 if (IsReturnStmt) {
6928 const CXXConstructExpr *CCE =
6929 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
6930 if (!CCE || CCE->getNumArgs() != 1)
6931 return;
6932
6933 if (!CCE->getConstructor()->isCopyOrMoveConstructor())
6934 return;
6935
6936 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
Richard Trieuac3eca52015-04-29 01:52:17 +00006937 }
6938
6939 // Find the std::move call and get the argument.
6940 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
Nico Weber192184c2018-06-20 15:57:38 +00006941 if (!CE || !CE->isCallToStdMove())
Richard Trieuac3eca52015-04-29 01:52:17 +00006942 return;
6943
6944 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
6945
6946 if (IsReturnStmt) {
6947 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
6948 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
6949 return;
6950
6951 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
6952 if (!VD || !VD->hasLocalStorage())
6953 return;
6954
Alex Lorenzbbe51d82017-11-07 21:40:11 +00006955 // __block variables are not moved implicitly.
6956 if (VD->hasAttr<BlocksAttr>())
6957 return;
6958
Richard Trieu8d4006a2015-07-28 19:06:16 +00006959 QualType SourceType = VD->getType();
6960 if (!SourceType->isRecordType())
Richard Trieu1d4911bc2015-05-18 19:54:08 +00006961 return;
6962
Richard Trieu8d4006a2015-07-28 19:06:16 +00006963 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
Richard Trieu1993dc82015-07-29 23:47:19 +00006964 return;
Richard Trieu8d4006a2015-07-28 19:06:16 +00006965 }
6966
Davide Italiano7842c3f2015-07-18 01:15:19 +00006967 // If we're returning a function parameter, copy elision
6968 // is not possible.
6969 if (isa<ParmVarDecl>(VD))
6970 DiagID = diag::warn_redundant_move_on_return;
Richard Trieu1993dc82015-07-29 23:47:19 +00006971 else
6972 DiagID = diag::warn_pessimizing_move_on_return;
Richard Trieuac3eca52015-04-29 01:52:17 +00006973 } else {
6974 DiagID = diag::warn_pessimizing_move_on_initialization;
6975 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
6976 if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType())
6977 return;
6978 }
6979
6980 S.Diag(CE->getLocStart(), DiagID);
6981
6982 // Get all the locations for a fix-it. Don't emit the fix-it if any location
6983 // is within a macro.
6984 SourceLocation CallBegin = CE->getCallee()->getLocStart();
6985 if (CallBegin.isMacroID())
6986 return;
6987 SourceLocation RParen = CE->getRParenLoc();
6988 if (RParen.isMacroID())
6989 return;
6990 SourceLocation LParen;
6991 SourceLocation ArgLoc = Arg->getLocStart();
6992
6993 // Special testing for the argument location. Since the fix-it needs the
6994 // location right before the argument, the argument location can be in a
6995 // macro only if it is at the beginning of the macro.
6996 while (ArgLoc.isMacroID() &&
6997 S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
Richard Smithb5f81712018-04-30 05:25:48 +00006998 ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).getBegin();
Richard Trieuac3eca52015-04-29 01:52:17 +00006999 }
7000
7001 if (LParen.isMacroID())
7002 return;
7003
7004 LParen = ArgLoc.getLocWithOffset(-1);
7005
7006 S.Diag(CE->getLocStart(), diag::note_remove_move)
7007 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
7008 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
7009}
7010
Nick Lewycky2eeddfb2016-05-14 17:44:14 +00007011static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
7012 // Check to see if we are dereferencing a null pointer. If so, this is
7013 // undefined behavior, so warn about it. This only handles the pattern
7014 // "*null", which is a very syntactic check.
7015 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
7016 if (UO->getOpcode() == UO_Deref &&
7017 UO->getSubExpr()->IgnoreParenCasts()->
7018 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
7019 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7020 S.PDiag(diag::warn_binding_null_to_reference)
7021 << UO->getSubExpr()->getSourceRange());
7022 }
7023}
7024
Tim Shen4a05bb82016-06-21 20:29:17 +00007025MaterializeTemporaryExpr *
7026Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
7027 bool BoundToLvalueReference) {
7028 auto MTE = new (Context)
7029 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
7030
7031 // Order an ExprWithCleanups for lifetime marks.
7032 //
7033 // TODO: It'll be good to have a single place to check the access of the
7034 // destructor and generate ExprWithCleanups for various uses. Currently these
7035 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
7036 // but there may be a chance to merge them.
7037 Cleanup.setExprNeedsCleanups(false);
7038 return MTE;
7039}
7040
Richard Smith4baaa5a2016-12-03 01:14:32 +00007041ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {
7042 // In C++98, we don't want to implicitly create an xvalue.
7043 // FIXME: This means that AST consumers need to deal with "prvalues" that
7044 // denote materialized temporaries. Maybe we should add another ValueKind
7045 // for "xvalue pretending to be a prvalue" for C++98 support.
7046 if (!E->isRValue() || !getLangOpts().CPlusPlus11)
7047 return E;
7048
7049 // C++1z [conv.rval]/1: T shall be a complete type.
Richard Smith81f5ade2016-12-15 02:28:18 +00007050 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
7051 // If so, we should check for a non-abstract class type here too.
Richard Smith4baaa5a2016-12-03 01:14:32 +00007052 QualType T = E->getType();
7053 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
7054 return ExprError();
7055
7056 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
7057}
7058
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007059ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007060InitializationSequence::Perform(Sema &S,
7061 const InitializedEntity &Entity,
7062 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00007063 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00007064 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00007065 if (Failed()) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007066 Diagnose(S, Entity, Kind, Args);
John McCallfaf5fb42010-08-26 23:41:50 +00007067 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007068 }
Nico Weber337d5aa2015-04-17 08:32:38 +00007069 if (!ZeroInitializationFixit.empty()) {
7070 unsigned DiagID = diag::err_default_init_const;
7071 if (Decl *D = Entity.getDecl())
7072 if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>())
7073 DiagID = diag::ext_default_init_const;
7074
7075 // The initialization would have succeeded with this fixit. Since the fixit
7076 // is on the error, we need to build a valid AST in this case, so this isn't
7077 // handled in the Failed() branch above.
7078 QualType DestType = Entity.getType();
7079 S.Diag(Kind.getLocation(), DiagID)
7080 << DestType << (bool)DestType->getAs<RecordType>()
7081 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
7082 ZeroInitializationFixit);
7083 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007084
Sebastian Redld201edf2011-06-05 13:59:11 +00007085 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00007086 // If the declaration is a non-dependent, incomplete array type
7087 // that has an initializer, then its type will be completed once
7088 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00007089 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00007090 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00007091 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00007092 if (const IncompleteArrayType *ArrayT
7093 = S.Context.getAsIncompleteArrayType(DeclType)) {
7094 // FIXME: We don't currently have the ability to accurately
7095 // compute the length of an initializer list without
7096 // performing full type-checking of the initializer list
7097 // (since we have to determine where braces are implicitly
7098 // introduced and such). So, we fall back to making the array
7099 // type a dependently-sized array type with no specified
7100 // bound.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007101 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00007102 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00007103
Douglas Gregor51e77d52009-12-10 17:56:55 +00007104 // Scavange the location of the brackets from the entity, if we can.
Richard Smith7873de02016-08-11 22:25:46 +00007105 if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
Douglas Gregor1b303932009-12-22 15:35:07 +00007106 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
7107 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00007108 if (IncompleteArrayTypeLoc ArrayLoc =
7109 TL.getAs<IncompleteArrayTypeLoc>())
7110 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregor1b303932009-12-22 15:35:07 +00007111 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00007112 }
7113
7114 *ResultType
7115 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00007116 /*NumElts=*/nullptr,
Douglas Gregor51e77d52009-12-10 17:56:55 +00007117 ArrayT->getSizeModifier(),
7118 ArrayT->getIndexTypeCVRQualifiers(),
7119 Brackets);
7120 }
7121
7122 }
7123 }
Sebastian Redla9351792012-02-11 23:51:47 +00007124 if (Kind.getKind() == InitializationKind::IK_Direct &&
7125 !Kind.isExplicitCast()) {
7126 // Rebuild the ParenListExpr.
Vedant Kumara14a1f92018-01-17 18:53:51 +00007127 SourceRange ParenRange = Kind.getParenOrBraceRange();
Sebastian Redla9351792012-02-11 23:51:47 +00007128 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007129 Args);
Sebastian Redla9351792012-02-11 23:51:47 +00007130 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00007131 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregorbf138952012-04-04 04:06:51 +00007132 Kind.isExplicitCast() ||
7133 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007134 return ExprResult(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007135 }
7136
Sebastian Redld201edf2011-06-05 13:59:11 +00007137 // No steps means no initialization.
7138 if (Steps.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007139 return ExprResult((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007140
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007141 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007142 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00007143 !Entity.isParameterKind()) {
Richard Smith2b349ae2012-04-19 06:58:00 +00007144 // Produce a C++98 compatibility warning if we are initializing a reference
7145 // from an initializer list. For parameters, we produce a better warning
7146 // elsewhere.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007147 Expr *Init = Args[0];
Richard Smith2b349ae2012-04-19 06:58:00 +00007148 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
7149 << Init->getSourceRange();
7150 }
7151
Egor Churaev3bccec52017-04-05 12:47:10 +00007152 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
7153 QualType ETy = Entity.getType();
7154 Qualifiers TyQualifiers = ETy.getQualifiers();
7155 bool HasGlobalAS = TyQualifiers.hasAddressSpace() &&
7156 TyQualifiers.getAddressSpace() == LangAS::opencl_global;
7157
7158 if (S.getLangOpts().OpenCLVersion >= 200 &&
7159 ETy->isAtomicType() && !HasGlobalAS &&
7160 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
7161 S.Diag(Args[0]->getLocStart(), diag::err_opencl_atomic_init) << 1 <<
7162 SourceRange(Entity.getDecl()->getLocStart(), Args[0]->getLocEnd());
7163 return ExprError();
7164 }
7165
Douglas Gregor1b303932009-12-22 15:35:07 +00007166 QualType DestType = Entity.getType().getNonReferenceType();
7167 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00007168 // the same as Entity.getDecl()->getType() in cases involving type merging,
7169 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00007170 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00007171 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00007172 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007173
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007174 ExprResult CurInit((Expr *)nullptr);
Richard Smith410306b2016-12-12 02:53:20 +00007175 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007176
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007177 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00007178 // grab the only argument out the Args and place it into the "current"
7179 // initializer.
7180 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00007181 case SK_ResolveAddressOfOverloadedFunction:
7182 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007183 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00007184 case SK_CastDerivedToBaseLValue:
7185 case SK_BindReference:
7186 case SK_BindReferenceToTemporary:
Richard Smithb8c0f552016-12-09 18:49:13 +00007187 case SK_FinalCopy:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00007188 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00007189 case SK_UserConversion:
7190 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007191 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00007192 case SK_QualificationConversionRValue:
Richard Smith77be48a2014-07-31 06:31:19 +00007193 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00007194 case SK_LValueToRValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00007195 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00007196 case SK_ConversionSequenceNoNarrowing:
Douglas Gregore1314a62009-12-18 05:02:21 +00007197 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00007198 case SK_UnwrapInitList:
7199 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00007200 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00007201 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00007202 case SK_ObjCObjectConversion:
Richard Smith410306b2016-12-12 02:53:20 +00007203 case SK_ArrayLoopIndex:
7204 case SK_ArrayLoopInit:
John McCall31168b02011-06-15 23:02:42 +00007205 case SK_ArrayInit:
Richard Smith378b8c82016-12-14 03:22:16 +00007206 case SK_GNUArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00007207 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00007208 case SK_PassByIndirectCopyRestore:
7209 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00007210 case SK_ProduceObjCObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007211 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00007212 case SK_OCLSamplerInit:
Egor Churaev89831422016-12-23 14:55:49 +00007213 case SK_OCLZeroEvent:
7214 case SK_OCLZeroQueue: {
Douglas Gregore1314a62009-12-18 05:02:21 +00007215 assert(Args.size() == 1);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007216 CurInit = Args[0];
John Wiegley01296292011-04-08 18:41:53 +00007217 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00007218 break;
John McCall34376a62010-12-04 03:47:34 +00007219 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007220
Douglas Gregore1314a62009-12-18 05:02:21 +00007221 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00007222 case SK_ConstructorInitializationFromList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00007223 case SK_StdInitializerListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00007224 case SK_ZeroInitialization:
7225 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007226 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007227
Richard Smithd6a15082017-01-07 00:48:55 +00007228 // Promote from an unevaluated context to an unevaluated list context in
7229 // C++11 list-initialization; we need to instantiate entities usable in
7230 // constant expressions here in order to perform narrowing checks =(
7231 EnterExpressionEvaluationContext Evaluated(
7232 S, EnterExpressionEvaluationContext::InitList,
7233 CurInit.get() && isa<InitListExpr>(CurInit.get()));
7234
Richard Smith81f5ade2016-12-15 02:28:18 +00007235 // C++ [class.abstract]p2:
7236 // no objects of an abstract class can be created except as subobjects
7237 // of a class derived from it
7238 auto checkAbstractType = [&](QualType T) -> bool {
7239 if (Entity.getKind() == InitializedEntity::EK_Base ||
7240 Entity.getKind() == InitializedEntity::EK_Delegating)
7241 return false;
7242 return S.RequireNonAbstractType(Kind.getLocation(), T,
7243 diag::err_allocation_of_abstract_type);
7244 };
7245
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007246 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007247 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007248 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007249 for (step_iterator Step = step_begin(), StepEnd = step_end();
7250 Step != StepEnd; ++Step) {
7251 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007252 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007253
John Wiegley01296292011-04-08 18:41:53 +00007254 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007255
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007256 switch (Step->Kind) {
7257 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007258 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007259 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00007260 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +00007261 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
7262 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007263 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall16df1e52010-03-30 21:47:33 +00007264 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00007265 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007266 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007267
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007268 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007269 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007270 case SK_CastDerivedToBaseLValue: {
7271 // We have a derived-to-base cast that produces either an rvalue or an
7272 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007273
John McCallcf142162010-08-07 06:22:56 +00007274 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00007275
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007276 // Casts to inaccessible base classes are allowed with C-style casts.
7277 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
7278 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00007279 CurInit.get()->getLocStart(),
7280 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00007281 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00007282 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007283
John McCall2536c6d2010-08-25 10:28:54 +00007284 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007285 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00007286 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007287 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00007288 VK_XValue :
7289 VK_RValue);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007290 CurInit =
7291 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
7292 CurInit.get(), &BasePath, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007293 break;
7294 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007295
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007296 case SK_BindReference:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007297 // Reference binding does not have any corresponding ASTs.
7298
7299 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00007300 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00007301 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00007302
George Burgess IVcfd48d92017-04-13 23:47:08 +00007303 // We don't check for e.g. function pointers here, since address
7304 // availability checks should only occur when the function first decays
7305 // into a pointer or reference.
7306 if (CurInit.get()->getType()->isFunctionProtoType()) {
7307 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
7308 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
7309 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
7310 DRE->getLocStart()))
7311 return ExprError();
7312 }
7313 }
7314 }
7315
Nick Lewycky2eeddfb2016-05-14 17:44:14 +00007316 CheckForNullPointerDereference(S, CurInit.get());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007317 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00007318
Richard Smithe6c01442013-06-05 00:46:14 +00007319 case SK_BindReferenceToTemporary: {
Jordan Roseb1312a52013-04-11 00:58:58 +00007320 // Make sure the "temporary" is actually an rvalue.
7321 assert(CurInit.get()->isRValue() && "not a temporary");
7322
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007323 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00007324 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00007325 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007326
Douglas Gregorfe314812011-06-21 17:03:29 +00007327 // Materialize the temporary into memory.
Tim Shen4a05bb82016-06-21 20:29:17 +00007328 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
Richard Smithb8c0f552016-12-09 18:49:13 +00007329 Step->Type, CurInit.get(), Entity.getType()->isLValueReferenceType());
Richard Smithd87aab92018-07-17 22:24:09 +00007330 CurInit = MTE;
David Majnemerdaff3702014-05-01 17:50:17 +00007331
Brian Kelley762f9282017-03-29 18:16:38 +00007332 // If we're extending this temporary to automatic storage duration -- we
7333 // need to register its cleanup during the full-expression's cleanups.
7334 if (MTE->getStorageDuration() == SD_Automatic &&
7335 MTE->getType().isDestructedType())
Tim Shen4a05bb82016-06-21 20:29:17 +00007336 S.Cleanup.setExprNeedsCleanups(true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007337 break;
Richard Smithe6c01442013-06-05 00:46:14 +00007338 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007339
Richard Smithb8c0f552016-12-09 18:49:13 +00007340 case SK_FinalCopy:
Richard Smith81f5ade2016-12-15 02:28:18 +00007341 if (checkAbstractType(Step->Type))
7342 return ExprError();
7343
Richard Smithb8c0f552016-12-09 18:49:13 +00007344 // If the overall initialization is initializing a temporary, we already
7345 // bound our argument if it was necessary to do so. If not (if we're
7346 // ultimately initializing a non-temporary), our argument needs to be
7347 // bound since it's initializing a function parameter.
7348 // FIXME: This is a mess. Rationalize temporary destruction.
7349 if (!shouldBindAsTemporary(Entity))
7350 CurInit = S.MaybeBindToTemporary(CurInit.get());
7351 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
7352 /*IsExtraneousCopy=*/false);
7353 break;
7354
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00007355 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007356 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00007357 /*IsExtraneousCopy=*/true);
7358 break;
7359
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007360 case SK_UserConversion: {
7361 // We have a user-defined conversion that invokes either a constructor
7362 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00007363 CastKind CastKind;
John McCalla0296f72010-03-19 07:35:19 +00007364 FunctionDecl *Fn = Step->Function.Function;
7365 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007366 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00007367 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00007368 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007369 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00007370 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley01296292011-04-08 18:41:53 +00007371 SourceLocation Loc = CurInit.get()->getLocStart();
John McCall760af172010-02-01 03:16:54 +00007372
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007373 // Determine the arguments required to actually perform the constructor
7374 // call.
John Wiegley01296292011-04-08 18:41:53 +00007375 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007376 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00007377 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007378 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00007379 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007380
Richard Smithb24f0672012-02-11 19:22:50 +00007381 // Build an expression that constructs a temporary.
Richard Smithc2bebe92016-05-11 20:37:46 +00007382 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type,
7383 FoundFn, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007384 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007385 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00007386 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00007387 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00007388 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00007389 CXXConstructExpr::CK_Complete,
7390 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007391 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007392 return ExprError();
John McCall760af172010-02-01 03:16:54 +00007393
Richard Smith5179eb72016-06-28 19:03:57 +00007394 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
7395 Entity);
Richard Smith22262ab2013-05-04 06:44:46 +00007396 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
7397 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007398
John McCalle3027922010-08-25 11:45:40 +00007399 CastKind = CK_ConstructorConversion;
Douglas Gregor95562572010-04-24 23:45:46 +00007400 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007401 } else {
7402 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00007403 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Craig Topperc3ec1492014-05-26 06:22:03 +00007404 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
John McCalla0296f72010-03-19 07:35:19 +00007405 FoundFn);
Richard Smith22262ab2013-05-04 06:44:46 +00007406 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
7407 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007408
7409 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007410 // derived-to-base conversion? I believe the answer is "no", because
7411 // we don't want to turn off access control here for c-style casts.
Richard Smithb8c0f552016-12-09 18:49:13 +00007412 CurInit = S.PerformObjectArgumentInitialization(CurInit.get(),
7413 /*Qualifier=*/nullptr,
7414 FoundFn, Conversion);
7415 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007416 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007417
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007418 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007419 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
7420 HadMultipleCandidates);
Richard Smithb8c0f552016-12-09 18:49:13 +00007421 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007422 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007423
John McCalle3027922010-08-25 11:45:40 +00007424 CastKind = CK_UserDefinedConversion;
Alp Toker314cc812014-01-25 16:55:45 +00007425 CreatedObject = Conversion->getReturnType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007426 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007427
Richard Smith81f5ade2016-12-15 02:28:18 +00007428 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
7429 return ExprError();
7430
Richard Smithb8c0f552016-12-09 18:49:13 +00007431 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
7432 CastKind, CurInit.get(), nullptr,
7433 CurInit.get()->getValueKind());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00007434
Richard Smithb8c0f552016-12-09 18:49:13 +00007435 if (shouldBindAsTemporary(Entity))
7436 // The overall entity is temporary, so this expression should be
7437 // destroyed at the end of its full-expression.
7438 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
7439 else if (CreatedObject && shouldDestroyEntity(Entity)) {
7440 // The object outlasts the full-expression, but we need to prepare for
7441 // a destructor being run on it.
7442 // FIXME: It makes no sense to do this here. This should happen
7443 // regardless of how we initialized the entity.
John Wiegley01296292011-04-08 18:41:53 +00007444 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00007445 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007446 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00007447 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00007448 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00007449 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00007450 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith22262ab2013-05-04 06:44:46 +00007451 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
7452 return ExprError();
Douglas Gregor95562572010-04-24 23:45:46 +00007453 }
7454 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007455 break;
7456 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007457
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007458 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007459 case SK_QualificationConversionXValue:
7460 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007461 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00007462 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007463 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00007464 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007465 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00007466 VK_XValue :
7467 VK_RValue);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007468 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007469 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007470 }
7471
Richard Smith77be48a2014-07-31 06:31:19 +00007472 case SK_AtomicConversion: {
7473 assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
7474 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7475 CK_NonAtomicToAtomic, VK_RValue);
7476 break;
7477 }
7478
Jordan Roseb1312a52013-04-11 00:58:58 +00007479 case SK_LValueToRValue: {
7480 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007481 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
7482 CK_LValueToRValue, CurInit.get(),
7483 /*BasePath=*/nullptr, VK_RValue);
Jordan Roseb1312a52013-04-11 00:58:58 +00007484 break;
7485 }
7486
Richard Smithaaa0ec42013-09-21 21:19:19 +00007487 case SK_ConversionSequence:
7488 case SK_ConversionSequenceNoNarrowing: {
7489 Sema::CheckedConversionKind CCK
John McCall31168b02011-06-15 23:02:42 +00007490 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
7491 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00007492 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00007493 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00007494 ExprResult CurInitExprRes =
7495 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00007496 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00007497 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007498 return ExprError();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00007499
7500 S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get());
7501
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007502 CurInit = CurInitExprRes;
Richard Smithaaa0ec42013-09-21 21:19:19 +00007503
7504 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
Richard Smith52e624f2016-12-21 21:42:57 +00007505 S.getLangOpts().CPlusPlus)
Richard Smithaaa0ec42013-09-21 21:19:19 +00007506 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
7507 CurInit.get());
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00007508
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007509 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00007510 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007511
Douglas Gregor51e77d52009-12-10 17:56:55 +00007512 case SK_ListInitialization: {
Richard Smith81f5ade2016-12-15 02:28:18 +00007513 if (checkAbstractType(Step->Type))
7514 return ExprError();
7515
John Wiegley01296292011-04-08 18:41:53 +00007516 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smithcc1b96d2013-06-12 22:31:48 +00007517 // If we're not initializing the top-level entity, we need to create an
7518 // InitializeTemporary entity for our target type.
7519 QualType Ty = Step->Type;
7520 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl29526f02011-11-27 16:50:07 +00007521 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smithd712d0d2013-02-02 01:13:06 +00007522 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
7523 InitListChecker PerformInitList(S, InitEntity,
Manman Ren073db022016-03-10 18:53:19 +00007524 InitList, Ty, /*VerifyOnly=*/false,
7525 /*TreatUnavailableAsInvalid=*/false);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007526 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00007527 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00007528
Richard Smithcc1b96d2013-06-12 22:31:48 +00007529 // Hack: We must update *ResultType if available in order to set the
7530 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
7531 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
7532 if (ResultType &&
7533 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00007534 if ((*ResultType)->isRValueReferenceType())
7535 Ty = S.Context.getRValueReferenceType(Ty);
7536 else if ((*ResultType)->isLValueReferenceType())
7537 Ty = S.Context.getLValueReferenceType(Ty,
7538 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
7539 *ResultType = Ty;
7540 }
7541
7542 InitListExpr *StructuredInitList =
7543 PerformInitList.getFullyStructuredList();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007544 CurInit.get();
Richard Smithd712d0d2013-02-02 01:13:06 +00007545 CurInit = shouldBindAsTemporary(InitEntity)
7546 ? S.MaybeBindToTemporary(StructuredInitList)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007547 : StructuredInitList;
Douglas Gregor51e77d52009-12-10 17:56:55 +00007548 break;
7549 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007550
Richard Smith53324112014-07-16 21:33:43 +00007551 case SK_ConstructorInitializationFromList: {
Richard Smith81f5ade2016-12-15 02:28:18 +00007552 if (checkAbstractType(Step->Type))
7553 return ExprError();
7554
Sebastian Redl5a41f682012-02-12 16:37:24 +00007555 // When an initializer list is passed for a parameter of type "reference
7556 // to object", we don't get an EK_Temporary entity, but instead an
7557 // EK_Parameter entity with reference type.
Sebastian Redl99f66162012-02-19 12:27:56 +00007558 // FIXME: This is a hack. What we really should do is create a user
7559 // conversion step for this case, but this makes it considerably more
7560 // complicated. For now, this will do.
Sebastian Redl5a41f682012-02-12 16:37:24 +00007561 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
7562 Entity.getType().getNonReferenceType());
7563 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithd86812d2012-07-05 08:39:21 +00007564 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007565 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith2b349ae2012-04-19 06:58:00 +00007566 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
7567 << InitList->getSourceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00007568 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl5a41f682012-02-12 16:37:24 +00007569 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
7570 Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007571 Kind, Arg, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00007572 ConstructorInitRequiresZeroInit,
Richard Smith53324112014-07-16 21:33:43 +00007573 /*IsListInitialization*/true,
Richard Smithf8adcdc2014-07-17 05:12:35 +00007574 /*IsStdInitListInit*/false,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00007575 InitList->getLBraceLoc(),
7576 InitList->getRBraceLoc());
Sebastian Redled2e5322011-12-22 14:44:04 +00007577 break;
7578 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007579
Sebastian Redl29526f02011-11-27 16:50:07 +00007580 case SK_UnwrapInitList:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007581 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
Sebastian Redl29526f02011-11-27 16:50:07 +00007582 break;
7583
7584 case SK_RewrapInitList: {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007585 Expr *E = CurInit.get();
Sebastian Redl29526f02011-11-27 16:50:07 +00007586 InitListExpr *Syntactic = Step->WrappingSyntacticList;
7587 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramerc215e762012-08-24 11:54:20 +00007588 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl29526f02011-11-27 16:50:07 +00007589 ILE->setSyntacticForm(Syntactic);
7590 ILE->setType(E->getType());
7591 ILE->setValueKind(E->getValueKind());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007592 CurInit = ILE;
Sebastian Redl29526f02011-11-27 16:50:07 +00007593 break;
7594 }
7595
Richard Smith53324112014-07-16 21:33:43 +00007596 case SK_ConstructorInitialization:
Richard Smithf8adcdc2014-07-17 05:12:35 +00007597 case SK_StdInitializerListConstructorCall: {
Richard Smith81f5ade2016-12-15 02:28:18 +00007598 if (checkAbstractType(Step->Type))
7599 return ExprError();
7600
Sebastian Redl99f66162012-02-19 12:27:56 +00007601 // When an initializer list is passed for a parameter of type "reference
7602 // to object", we don't get an EK_Temporary entity, but instead an
7603 // EK_Parameter entity with reference type.
7604 // FIXME: This is a hack. What we really should do is create a user
7605 // conversion step for this case, but this makes it considerably more
7606 // complicated. For now, this will do.
7607 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
7608 Entity.getType().getNonReferenceType());
7609 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf8adcdc2014-07-17 05:12:35 +00007610 bool IsStdInitListInit =
7611 Step->Kind == SK_StdInitializerListConstructorCall;
Richard Smith410306b2016-12-12 02:53:20 +00007612 Expr *Source = CurInit.get();
Vedant Kumara14a1f92018-01-17 18:53:51 +00007613 SourceRange Range = Kind.hasParenOrBraceRange()
7614 ? Kind.getParenOrBraceRange()
7615 : SourceRange();
Richard Smith53324112014-07-16 21:33:43 +00007616 CurInit = PerformConstructorInitialization(
Richard Smith410306b2016-12-12 02:53:20 +00007617 S, UseTemporary ? TempEntity : Entity, Kind,
7618 Source ? MultiExprArg(Source) : Args, *Step,
Richard Smith53324112014-07-16 21:33:43 +00007619 ConstructorInitRequiresZeroInit,
Richard Smith410306b2016-12-12 02:53:20 +00007620 /*IsListInitialization*/ IsStdInitListInit,
7621 /*IsStdInitListInitialization*/ IsStdInitListInit,
Vedant Kumara14a1f92018-01-17 18:53:51 +00007622 /*LBraceLoc*/ Range.getBegin(),
7623 /*RBraceLoc*/ Range.getEnd());
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007624 break;
Sebastian Redl99f66162012-02-19 12:27:56 +00007625 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007626
Douglas Gregor7dc42e52009-12-15 00:01:57 +00007627 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007628 step_iterator NextStep = Step;
7629 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007630 if (NextStep != StepEnd &&
Richard Smithd86812d2012-07-05 08:39:21 +00007631 (NextStep->Kind == SK_ConstructorInitialization ||
Richard Smith53324112014-07-16 21:33:43 +00007632 NextStep->Kind == SK_ConstructorInitializationFromList)) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007633 // The need for zero-initialization is recorded directly into
7634 // the call to the object's constructor within the next step.
7635 ConstructorInitRequiresZeroInit = true;
7636 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007637 S.getLangOpts().CPlusPlus &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007638 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00007639 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7640 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007641 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00007642 Kind.getRange().getBegin());
7643
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007644 CurInit = new (S.Context) CXXScalarValueInitExpr(
Richard Smith60437622017-02-09 19:17:44 +00007645 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007646 Kind.getRange().getEnd());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007647 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007648 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007649 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00007650 break;
7651 }
Douglas Gregore1314a62009-12-18 05:02:21 +00007652
7653 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00007654 QualType SourceType = CurInit.get()->getType();
George Burgess IV5f21c712015-10-12 19:57:04 +00007655 // Save off the initial CurInit in case we need to emit a diagnostic
7656 ExprResult InitialCurInit = CurInit;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007657 ExprResult Result = CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00007658 Sema::AssignConvertType ConvTy =
Fariborz Jahanian25eef192013-07-31 21:40:51 +00007659 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
7660 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley01296292011-04-08 18:41:53 +00007661 if (Result.isInvalid())
7662 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007663 CurInit = Result;
Douglas Gregor96596c92009-12-22 07:24:36 +00007664
7665 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007666 ExprResult CurInitExprRes = CurInit;
Douglas Gregor96596c92009-12-22 07:24:36 +00007667 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00007668 Entity.isParameterKind() &&
John Wiegley01296292011-04-08 18:41:53 +00007669 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00007670 == Sema::Compatible)
7671 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00007672 if (CurInitExprRes.isInvalid())
7673 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007674 CurInit = CurInitExprRes;
Douglas Gregor96596c92009-12-22 07:24:36 +00007675
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007676 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00007677 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
7678 Step->Type, SourceType,
George Burgess IV5f21c712015-10-12 19:57:04 +00007679 InitialCurInit.get(),
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00007680 getAssignmentAction(Entity, true),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007681 &Complained)) {
7682 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00007683 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007684 } else if (Complained)
7685 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00007686 break;
7687 }
Eli Friedman78275202009-12-19 08:11:05 +00007688
7689 case SK_StringInit: {
7690 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00007691 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00007692 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00007693 break;
7694 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007695
7696 case SK_ObjCObjectConversion:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007697 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00007698 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00007699 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007700 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007701
Richard Smith410306b2016-12-12 02:53:20 +00007702 case SK_ArrayLoopIndex: {
7703 Expr *Cur = CurInit.get();
7704 Expr *BaseExpr = new (S.Context)
7705 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
7706 Cur->getValueKind(), Cur->getObjectKind(), Cur);
7707 Expr *IndexExpr =
7708 new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());
7709 CurInit = S.CreateBuiltinArraySubscriptExpr(
7710 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
7711 ArrayLoopCommonExprs.push_back(BaseExpr);
7712 break;
7713 }
7714
7715 case SK_ArrayLoopInit: {
7716 assert(!ArrayLoopCommonExprs.empty() &&
7717 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
7718 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
7719 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
7720 CurInit.get());
7721 break;
7722 }
7723
Richard Smith378b8c82016-12-14 03:22:16 +00007724 case SK_GNUArrayInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00007725 // Okay: we checked everything before creating this step. Note that
7726 // this is a GNU extension.
7727 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00007728 << Step->Type << CurInit.get()->getType()
7729 << CurInit.get()->getSourceRange();
Richard Smith378b8c82016-12-14 03:22:16 +00007730 LLVM_FALLTHROUGH;
7731 case SK_ArrayInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00007732 // If the destination type is an incomplete array type, update the
7733 // type accordingly.
7734 if (ResultType) {
7735 if (const IncompleteArrayType *IncompleteDest
7736 = S.Context.getAsIncompleteArrayType(Step->Type)) {
7737 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00007738 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00007739 *ResultType = S.Context.getConstantArrayType(
7740 IncompleteDest->getElementType(),
7741 ConstantSource->getSize(),
7742 ArrayType::Normal, 0);
7743 }
7744 }
7745 }
John McCall31168b02011-06-15 23:02:42 +00007746 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007747
Richard Smithebeed412012-02-15 22:38:09 +00007748 case SK_ParenthesizedArrayInit:
7749 // Okay: we checked everything before creating this step. Note that
7750 // this is a GNU extension.
7751 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
7752 << CurInit.get()->getSourceRange();
7753 break;
7754
John McCall31168b02011-06-15 23:02:42 +00007755 case SK_PassByIndirectCopyRestore:
7756 case SK_PassByIndirectRestore:
7757 checkIndirectCopyRestoreSource(S, CurInit.get());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007758 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
7759 CurInit.get(), Step->Type,
7760 Step->Kind == SK_PassByIndirectCopyRestore);
John McCall31168b02011-06-15 23:02:42 +00007761 break;
7762
7763 case SK_ProduceObjCObject:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007764 CurInit =
7765 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
7766 CurInit.get(), nullptr, VK_RValue);
Douglas Gregore2f943b2011-02-22 18:29:51 +00007767 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00007768
7769 case SK_StdInitializerList: {
Richard Smithcc1b96d2013-06-12 22:31:48 +00007770 S.Diag(CurInit.get()->getExprLoc(),
7771 diag::warn_cxx98_compat_initializer_list_init)
7772 << CurInit.get()->getSourceRange();
Sebastian Redl249dee52012-03-05 19:35:43 +00007773
Richard Smithcc1b96d2013-06-12 22:31:48 +00007774 // Materialize the temporary into memory.
Tim Shen4a05bb82016-06-21 20:29:17 +00007775 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
7776 CurInit.get()->getType(), CurInit.get(),
7777 /*BoundToLvalueReference=*/false);
David Majnemerdaff3702014-05-01 17:50:17 +00007778
Florian Hahn0aa117d2018-07-17 09:23:31 +00007779 // Wrap it in a construction of a std::initializer_list<T>.
7780 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
Richard Smith0a9969b2018-07-17 00:11:41 +00007781
Richard Smithcc1b96d2013-06-12 22:31:48 +00007782 // Bind the result, in case the library has given initializer_list a
7783 // non-trivial destructor.
7784 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007785 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redlc1839b12012-01-17 22:49:42 +00007786 break;
7787 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00007788
Guy Benyei61054192013-02-07 10:55:47 +00007789 case SK_OCLSamplerInit: {
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007790 // Sampler initialzation have 5 cases:
7791 // 1. function argument passing
7792 // 1a. argument is a file-scope variable
7793 // 1b. argument is a function-scope variable
7794 // 1c. argument is one of caller function's parameters
7795 // 2. variable initialization
7796 // 2a. initializing a file-scope variable
7797 // 2b. initializing a function-scope variable
7798 //
7799 // For file-scope variables, since they cannot be initialized by function
7800 // call of __translate_sampler_initializer in LLVM IR, their references
7801 // need to be replaced by a cast from their literal initializers to
7802 // sampler type. Since sampler variables can only be used in function
7803 // calls as arguments, we only need to replace them when handling the
7804 // argument passing.
7805 assert(Step->Type->isSamplerT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00007806 "Sampler initialization on non-sampler type.");
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007807 Expr *Init = CurInit.get();
7808 QualType SourceType = Init->getType();
7809 // Case 1
Fariborz Jahanian131996b2013-07-31 18:21:45 +00007810 if (Entity.isParameterKind()) {
Egor Churaeva8d24512017-04-05 09:02:56 +00007811 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
Guy Benyei61054192013-02-07 10:55:47 +00007812 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
7813 << SourceType;
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007814 break;
7815 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
7816 auto Var = cast<VarDecl>(DRE->getDecl());
7817 // Case 1b and 1c
7818 // No cast from integer to sampler is needed.
7819 if (!Var->hasGlobalStorage()) {
7820 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
7821 CK_LValueToRValue, Init,
7822 /*BasePath=*/nullptr, VK_RValue);
7823 break;
7824 }
7825 // Case 1a
7826 // For function call with a file-scope sampler variable as argument,
7827 // get the integer literal.
7828 // Do not diagnose if the file-scope variable does not have initializer
7829 // since this has already been diagnosed when parsing the variable
7830 // declaration.
7831 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
7832 break;
7833 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
7834 Var->getInit()))->getSubExpr();
7835 SourceType = Init->getType();
7836 }
7837 } else {
7838 // Case 2
7839 // Check initializer is 32 bit integer constant.
7840 // If the initializer is taken from global variable, do not diagnose since
7841 // this has already been done when parsing the variable declaration.
7842 if (!Init->isConstantInitializer(S.Context, false))
7843 break;
7844
7845 if (!SourceType->isIntegerType() ||
7846 32 != S.Context.getIntWidth(SourceType)) {
7847 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
7848 << SourceType;
7849 break;
7850 }
7851
7852 llvm::APSInt Result;
7853 Init->EvaluateAsInt(Result, S.Context);
7854 const uint64_t SamplerValue = Result.getLimitedValue();
7855 // 32-bit value of sampler's initializer is interpreted as
7856 // bit-field with the following structure:
7857 // |unspecified|Filter|Addressing Mode| Normalized Coords|
7858 // |31 6|5 4|3 1| 0|
7859 // This structure corresponds to enum values of sampler properties
7860 // defined in SPIR spec v1.2 and also opencl-c.h
7861 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
7862 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
7863 if (FilterMode != 1 && FilterMode != 2)
7864 S.Diag(Kind.getLocation(),
7865 diag::warn_sampler_initializer_invalid_bits)
7866 << "Filter Mode";
7867 if (AddressingMode > 4)
7868 S.Diag(Kind.getLocation(),
7869 diag::warn_sampler_initializer_invalid_bits)
7870 << "Addressing Mode";
Guy Benyei61054192013-02-07 10:55:47 +00007871 }
7872
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007873 // Cases 1a, 2a and 2b
7874 // Insert cast from integer to sampler.
7875 CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy,
7876 CK_IntToOCLSampler);
Guy Benyei61054192013-02-07 10:55:47 +00007877 break;
7878 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007879 case SK_OCLZeroEvent: {
7880 assert(Step->Type->isEventT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00007881 "Event initialization on non-event type.");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007882
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007883 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007884 CK_ZeroToOCLEvent,
7885 CurInit.get()->getValueKind());
7886 break;
7887 }
Egor Churaev89831422016-12-23 14:55:49 +00007888 case SK_OCLZeroQueue: {
7889 assert(Step->Type->isQueueT() &&
7890 "Event initialization on non queue type.");
7891
7892 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7893 CK_ZeroToOCLQueue,
7894 CurInit.get()->getValueKind());
7895 break;
7896 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007897 }
7898 }
John McCall1f425642010-11-11 03:21:53 +00007899
Richard Smithca975b22018-07-23 18:50:26 +00007900 // Check whether the initializer has a shorter lifetime than the initialized
7901 // entity, and if not, either lifetime-extend or warn as appropriate.
7902 if (auto *Init = CurInit.get())
7903 S.checkInitializerLifetime(Entity, Init);
7904
John McCall1f425642010-11-11 03:21:53 +00007905 // Diagnose non-fatal problems with the completed initialization.
7906 if (Entity.getKind() == InitializedEntity::EK_Member &&
7907 cast<FieldDecl>(Entity.getDecl())->isBitField())
7908 S.CheckBitFieldInitialization(Kind.getLocation(),
7909 cast<FieldDecl>(Entity.getDecl()),
7910 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007911
Richard Trieuac3eca52015-04-29 01:52:17 +00007912 // Check for std::move on construction.
7913 if (const Expr *E = CurInit.get()) {
7914 CheckMoveOnConstruction(S, E,
7915 Entity.getKind() == InitializedEntity::EK_Result);
7916 }
7917
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007918 return CurInit;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007919}
7920
Richard Smith593f9932012-12-08 02:01:17 +00007921/// Somewhere within T there is an uninitialized reference subobject.
7922/// Dig it out and diagnose it.
Benjamin Kramer3e350262013-02-15 12:30:38 +00007923static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
7924 QualType T) {
Richard Smith593f9932012-12-08 02:01:17 +00007925 if (T->isReferenceType()) {
7926 S.Diag(Loc, diag::err_reference_without_init)
7927 << T.getNonReferenceType();
7928 return true;
7929 }
7930
7931 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7932 if (!RD || !RD->hasUninitializedReferenceMember())
7933 return false;
7934
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007935 for (const auto *FI : RD->fields()) {
Richard Smith593f9932012-12-08 02:01:17 +00007936 if (FI->isUnnamedBitfield())
7937 continue;
7938
7939 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
7940 S.Diag(Loc, diag::note_value_initialization_here) << RD;
7941 return true;
7942 }
7943 }
7944
Aaron Ballman574705e2014-03-13 15:41:46 +00007945 for (const auto &BI : RD->bases()) {
7946 if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
Richard Smith593f9932012-12-08 02:01:17 +00007947 S.Diag(Loc, diag::note_value_initialization_here) << RD;
7948 return true;
7949 }
7950 }
7951
7952 return false;
7953}
7954
7955
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007956//===----------------------------------------------------------------------===//
7957// Diagnose initialization failures
7958//===----------------------------------------------------------------------===//
John McCall5ec7e7d2013-03-19 07:04:25 +00007959
7960/// Emit notes associated with an initialization that failed due to a
7961/// "simple" conversion failure.
7962static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
7963 Expr *op) {
7964 QualType destType = entity.getType();
7965 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
7966 op->getType()->isObjCObjectPointerType()) {
7967
7968 // Emit a possible note about the conversion failing because the
7969 // operand is a message send with a related result type.
7970 S.EmitRelatedResultTypeNote(op);
7971
7972 // Emit a possible note about a return failing because we're
7973 // expecting a related result type.
7974 if (entity.getKind() == InitializedEntity::EK_Result)
7975 S.EmitRelatedResultTypeNoteForReturn(destType);
7976 }
7977}
7978
Richard Smith0449aaf2013-11-21 23:30:57 +00007979static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
7980 InitListExpr *InitList) {
7981 QualType DestType = Entity.getType();
7982
7983 QualType E;
7984 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
7985 QualType ArrayType = S.Context.getConstantArrayType(
7986 E.withConst(),
7987 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
7988 InitList->getNumInits()),
7989 clang::ArrayType::Normal, 0);
7990 InitializedEntity HiddenArray =
7991 InitializedEntity::InitializeTemporary(ArrayType);
7992 return diagnoseListInit(S, HiddenArray, InitList);
7993 }
7994
Richard Smith8d082d12014-09-04 22:13:39 +00007995 if (DestType->isReferenceType()) {
7996 // A list-initialization failure for a reference means that we tried to
7997 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
7998 // inner initialization failed.
7999 QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
8000 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
8001 SourceLocation Loc = InitList->getLocStart();
8002 if (auto *D = Entity.getDecl())
8003 Loc = D->getLocation();
8004 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
8005 return;
8006 }
8007
Richard Smith0449aaf2013-11-21 23:30:57 +00008008 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
Manman Ren073db022016-03-10 18:53:19 +00008009 /*VerifyOnly=*/false,
8010 /*TreatUnavailableAsInvalid=*/false);
Richard Smith0449aaf2013-11-21 23:30:57 +00008011 assert(DiagnoseInitList.HadError() &&
8012 "Inconsistent init list check result.");
8013}
8014
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008015bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008016 const InitializedEntity &Entity,
8017 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008018 ArrayRef<Expr *> Args) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00008019 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008020 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008021
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008022 // When we want to diagnose only one element of a braced-init-list,
8023 // we need to factor it out.
8024 Expr *OnlyArg;
8025 if (Args.size() == 1) {
8026 auto *List = dyn_cast<InitListExpr>(Args[0]);
8027 if (List && List->getNumInits() == 1)
8028 OnlyArg = List->getInit(0);
8029 else
8030 OnlyArg = Args[0];
8031 }
8032 else
8033 OnlyArg = nullptr;
8034
Douglas Gregor1b303932009-12-22 15:35:07 +00008035 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008036 switch (Failure) {
8037 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008038 // FIXME: Customize for the initialized entity?
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008039 if (Args.empty()) {
Richard Smith593f9932012-12-08 02:01:17 +00008040 // Dig out the reference subobject which is uninitialized and diagnose it.
8041 // If this is value-initialization, this could be nested some way within
8042 // the target type.
8043 assert(Kind.getKind() == InitializationKind::IK_Value ||
8044 DestType->isReferenceType());
8045 bool Diagnosed =
8046 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
8047 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
8048 (void)Diagnosed;
8049 } else // FIXME: diagnostic below could be better!
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008050 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008051 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008052 break;
Richard Smith49a6b6e2017-03-24 01:14:25 +00008053 case FK_ParenthesizedListInitForReference:
8054 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
8055 << 1 << Entity.getType() << Args[0]->getSourceRange();
8056 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008057
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008058 case FK_ArrayNeedsInitList:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00008059 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008060 break;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00008061 case FK_ArrayNeedsInitListOrStringLiteral:
8062 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
8063 break;
8064 case FK_ArrayNeedsInitListOrWideStringLiteral:
8065 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
8066 break;
8067 case FK_NarrowStringIntoWideCharArray:
8068 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
8069 break;
8070 case FK_WideStringIntoCharArray:
8071 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
8072 break;
8073 case FK_IncompatWideStringIntoWideChar:
8074 S.Diag(Kind.getLocation(),
8075 diag::err_array_init_incompat_wide_string_into_wchar);
8076 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00008077 case FK_PlainStringIntoUTF8Char:
8078 S.Diag(Kind.getLocation(),
8079 diag::err_array_init_plain_string_into_char8_t);
8080 S.Diag(Args.front()->getLocStart(),
8081 diag::note_array_init_plain_string_into_char8_t)
8082 << FixItHint::CreateInsertion(Args.front()->getLocStart(), "u8");
8083 break;
8084 case FK_UTF8StringIntoPlainChar:
8085 S.Diag(Kind.getLocation(),
8086 diag::err_array_init_utf8_string_into_char);
8087 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00008088 case FK_ArrayTypeMismatch:
8089 case FK_NonConstantArrayInit:
Richard Smith0449aaf2013-11-21 23:30:57 +00008090 S.Diag(Kind.getLocation(),
Douglas Gregore2f943b2011-02-22 18:29:51 +00008091 (Failure == FK_ArrayTypeMismatch
8092 ? diag::err_array_init_different_type
8093 : diag::err_array_init_non_constant_array))
8094 << DestType.getNonReferenceType()
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008095 << OnlyArg->getType()
Douglas Gregore2f943b2011-02-22 18:29:51 +00008096 << Args[0]->getSourceRange();
8097 break;
8098
John McCalla59dc2f2012-01-05 00:13:19 +00008099 case FK_VariableLengthArrayHasInitializer:
8100 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
8101 << Args[0]->getSourceRange();
8102 break;
8103
John McCall16df1e52010-03-30 21:47:33 +00008104 case FK_AddressOfOverloadFailed: {
8105 DeclAccessPair Found;
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008106 S.ResolveAddressOfOverloadedFunction(OnlyArg,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008107 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00008108 true,
8109 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008110 break;
John McCall16df1e52010-03-30 21:47:33 +00008111 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008112
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008113 case FK_AddressOfUnaddressableFunction: {
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008114 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008115 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008116 OnlyArg->getLocStart());
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008117 break;
8118 }
8119
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008120 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00008121 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008122 switch (FailedOverloadResult) {
8123 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00008124 if (Failure == FK_UserConversionOverloadFailed)
8125 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008126 << OnlyArg->getType() << DestType
Douglas Gregore1314a62009-12-18 05:02:21 +00008127 << Args[0]->getSourceRange();
8128 else
8129 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008130 << DestType << OnlyArg->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00008131 << Args[0]->getSourceRange();
8132
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008133 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008134 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008135
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008136 case OR_No_Viable_Function:
Larisse Voufo70bb43a2013-06-27 03:36:30 +00008137 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00008138 DestType.getNonReferenceType(),
8139 diag::err_typecheck_nonviable_condition_incomplete,
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008140 OnlyArg->getType(), Args[0]->getSourceRange()))
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00008141 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00008142 << (Entity.getKind() == InitializedEntity::EK_Result)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008143 << OnlyArg->getType() << Args[0]->getSourceRange()
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00008144 << DestType.getNonReferenceType();
8145
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008146 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008147 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008148
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008149 case OR_Deleted: {
8150 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008151 << OnlyArg->getType() << DestType.getNonReferenceType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008152 << Args[0]->getSourceRange();
8153 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008154 OverloadingResult Ovl
Richard Smith67ef14f2017-09-26 18:37:55 +00008155 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008156 if (Ovl == OR_Deleted) {
Richard Smith852265f2012-03-30 20:53:28 +00008157 S.NoteDeletedFunction(Best->Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008158 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00008159 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008160 }
8161 break;
8162 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008163
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008164 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00008165 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008166 }
8167 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008168
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008169 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00008170 if (isa<InitListExpr>(Args[0])) {
8171 S.Diag(Kind.getLocation(),
8172 diag::err_lvalue_reference_bind_to_initlist)
8173 << DestType.getNonReferenceType().isVolatileQualified()
8174 << DestType.getNonReferenceType()
8175 << Args[0]->getSourceRange();
8176 break;
8177 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008178 LLVM_FALLTHROUGH;
Sebastian Redl29526f02011-11-27 16:50:07 +00008179
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008180 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008181 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008182 Failure == FK_NonConstLValueReferenceBindingToTemporary
8183 ? diag::err_lvalue_reference_bind_to_temporary
8184 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00008185 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008186 << DestType.getNonReferenceType()
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008187 << OnlyArg->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008188 << Args[0]->getSourceRange();
8189 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008190
Richard Smithb8c0f552016-12-09 18:49:13 +00008191 case FK_NonConstLValueReferenceBindingToBitfield: {
8192 // We don't necessarily have an unambiguous source bit-field.
8193 FieldDecl *BitField = Args[0]->getSourceBitField();
8194 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
8195 << DestType.isVolatileQualified()
8196 << (BitField ? BitField->getDeclName() : DeclarationName())
8197 << (BitField != nullptr)
8198 << Args[0]->getSourceRange();
8199 if (BitField)
8200 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
8201 break;
8202 }
8203
8204 case FK_NonConstLValueReferenceBindingToVectorElement:
8205 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
8206 << DestType.isVolatileQualified()
8207 << Args[0]->getSourceRange();
8208 break;
8209
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008210 case FK_RValueReferenceBindingToLValue:
8211 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008212 << DestType.getNonReferenceType() << OnlyArg->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008213 << Args[0]->getSourceRange();
8214 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008215
Richard Trieuf956a492015-05-16 01:27:03 +00008216 case FK_ReferenceInitDropsQualifiers: {
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008217 QualType SourceType = OnlyArg->getType();
Richard Trieuf956a492015-05-16 01:27:03 +00008218 QualType NonRefType = DestType.getNonReferenceType();
8219 Qualifiers DroppedQualifiers =
8220 SourceType.getQualifiers() - NonRefType.getQualifiers();
8221
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008222 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
Richard Trieuf956a492015-05-16 01:27:03 +00008223 << SourceType
8224 << NonRefType
8225 << DroppedQualifiers.getCVRQualifiers()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008226 << Args[0]->getSourceRange();
8227 break;
Richard Trieuf956a492015-05-16 01:27:03 +00008228 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008229
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008230 case FK_ReferenceInitFailed:
8231 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
8232 << DestType.getNonReferenceType()
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008233 << OnlyArg->isLValue()
8234 << OnlyArg->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008235 << Args[0]->getSourceRange();
John McCall5ec7e7d2013-03-19 07:04:25 +00008236 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008237 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008238
Douglas Gregorb491ed32011-02-19 21:32:49 +00008239 case FK_ConversionFailed: {
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008240 QualType FromType = OnlyArg->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00008241 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00008242 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008243 << DestType
Nicolas Lesser8217a2a2018-07-12 17:43:49 +00008244 << OnlyArg->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00008245 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008246 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008247 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
8248 S.Diag(Kind.getLocation(), PDiag);
John McCall5ec7e7d2013-03-19 07:04:25 +00008249 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00008250 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008251 }
John Wiegley01296292011-04-08 18:41:53 +00008252
8253 case FK_ConversionFromPropertyFailed:
8254 // No-op. This error has already been reported.
8255 break;
8256
Douglas Gregor51e77d52009-12-10 17:56:55 +00008257 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00008258 SourceRange R;
8259
David Majnemerbd385442015-04-10 04:52:06 +00008260 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
Benjamin Kramerc4284e32015-09-23 16:03:53 +00008261 if (InitList && InitList->getNumInits() >= 1) {
David Majnemerbd385442015-04-10 04:52:06 +00008262 R = SourceRange(InitList->getInit(0)->getLocEnd(), InitList->getLocEnd());
Benjamin Kramerc4284e32015-09-23 16:03:53 +00008263 } else {
8264 assert(Args.size() > 1 && "Expected multiple initializers!");
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008265 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Benjamin Kramerc4284e32015-09-23 16:03:53 +00008266 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00008267
Alp Tokerb6cc5922014-05-03 03:45:55 +00008268 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
Douglas Gregor8ec51732010-09-08 21:40:08 +00008269 if (Kind.isCStyleOrFunctionalCast())
8270 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
8271 << R;
8272 else
8273 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
8274 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00008275 break;
8276 }
8277
Richard Smith49a6b6e2017-03-24 01:14:25 +00008278 case FK_ParenthesizedListInitForScalar:
8279 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
8280 << 0 << Entity.getType() << Args[0]->getSourceRange();
8281 break;
8282
Douglas Gregor51e77d52009-12-10 17:56:55 +00008283 case FK_ReferenceBindingToInitList:
8284 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
8285 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
8286 break;
8287
8288 case FK_InitListBadDestinationType:
8289 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
8290 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
8291 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008292
Sebastian Redl6901c0d2011-12-22 18:58:38 +00008293 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008294 case FK_ConstructorOverloadFailed: {
8295 SourceRange ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008296 if (Args.size())
8297 ArgsRange = SourceRange(Args.front()->getLocStart(),
8298 Args.back()->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008299
Sebastian Redl6901c0d2011-12-22 18:58:38 +00008300 if (Failure == FK_ListConstructorOverloadFailed) {
Nico Weber9709ebf2014-07-08 23:54:25 +00008301 assert(Args.size() == 1 &&
8302 "List construction from other than 1 argument.");
Sebastian Redl6901c0d2011-12-22 18:58:38 +00008303 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008304 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00008305 }
8306
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008307 // FIXME: Using "DestType" for the entity we're printing is probably
8308 // bad.
8309 switch (FailedOverloadResult) {
8310 case OR_Ambiguous:
8311 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
8312 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008313 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008314 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008315
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008316 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008317 if (Kind.getKind() == InitializationKind::IK_Default &&
8318 (Entity.getKind() == InitializedEntity::EK_Base ||
8319 Entity.getKind() == InitializedEntity::EK_Member) &&
8320 isa<CXXConstructorDecl>(S.CurContext)) {
8321 // This is implicit default initialization of a member or
8322 // base within a constructor. If no viable function was
Nico Webera6916892016-06-10 18:53:04 +00008323 // found, notify the user that they need to explicitly
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008324 // initialize this base/member.
8325 CXXConstructorDecl *Constructor
8326 = cast<CXXConstructorDecl>(S.CurContext);
Richard Smith5179eb72016-06-28 19:03:57 +00008327 const CXXRecordDecl *InheritedFrom = nullptr;
8328 if (auto Inherited = Constructor->getInheritedConstructor())
8329 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008330 if (Entity.getKind() == InitializedEntity::EK_Base) {
8331 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith5179eb72016-06-28 19:03:57 +00008332 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008333 << S.Context.getTypeDeclType(Constructor->getParent())
8334 << /*base=*/0
Richard Smith5179eb72016-06-28 19:03:57 +00008335 << Entity.getType()
8336 << InheritedFrom;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008337
8338 RecordDecl *BaseDecl
8339 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
8340 ->getDecl();
8341 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
8342 << S.Context.getTagDeclType(BaseDecl);
8343 } else {
8344 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith5179eb72016-06-28 19:03:57 +00008345 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008346 << S.Context.getTypeDeclType(Constructor->getParent())
8347 << /*member=*/1
Richard Smith5179eb72016-06-28 19:03:57 +00008348 << Entity.getName()
8349 << InheritedFrom;
Alp Toker2afa8782014-05-28 12:20:14 +00008350 S.Diag(Entity.getDecl()->getLocation(),
8351 diag::note_member_declared_at);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008352
8353 if (const RecordType *Record
8354 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008355 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008356 diag::note_previous_decl)
8357 << S.Context.getTagDeclType(Record->getDecl());
8358 }
8359 break;
8360 }
8361
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008362 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
8363 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008364 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008365 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008366
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008367 case OR_Deleted: {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008368 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008369 OverloadingResult Ovl
8370 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor74f7d502012-02-15 19:33:52 +00008371 if (Ovl != OR_Deleted) {
8372 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
8373 << true << DestType << ArgsRange;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008374 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor74f7d502012-02-15 19:33:52 +00008375 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008376 }
Douglas Gregor74f7d502012-02-15 19:33:52 +00008377
8378 // If this is a defaulted or implicitly-declared function, then
8379 // it was implicitly deleted. Make it clear that the deletion was
8380 // implicit.
Richard Smith852265f2012-03-30 20:53:28 +00008381 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00008382 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith852265f2012-03-30 20:53:28 +00008383 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00008384 << DestType << ArgsRange;
Richard Smith852265f2012-03-30 20:53:28 +00008385 else
8386 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
8387 << true << DestType << ArgsRange;
8388
8389 S.NoteDeletedFunction(Best->Function);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008390 break;
8391 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008392
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008393 case OR_Success:
8394 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008395 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00008396 }
David Blaikie60deeee2012-01-17 08:24:58 +00008397 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008398
Douglas Gregor85dabae2009-12-16 01:38:02 +00008399 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008400 if (Entity.getKind() == InitializedEntity::EK_Member &&
8401 isa<CXXConstructorDecl>(S.CurContext)) {
8402 // This is implicit default-initialization of a const member in
8403 // a constructor. Complain that it needs to be explicitly
8404 // initialized.
8405 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
8406 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00008407 << (Constructor->getInheritedConstructor() ? 2 :
8408 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008409 << S.Context.getTypeDeclType(Constructor->getParent())
8410 << /*const=*/1
8411 << Entity.getName();
8412 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
8413 << Entity.getName();
8414 } else {
8415 S.Diag(Kind.getLocation(), diag::err_default_init_const)
Nico Weber9386c822014-07-23 05:16:10 +00008416 << DestType << (bool)DestType->getAs<RecordType>();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008417 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00008418 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008419
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008420 case FK_Incomplete:
Douglas Gregor85f34232012-04-10 20:43:46 +00008421 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008422 diag::err_init_incomplete_type);
8423 break;
8424
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008425 case FK_ListInitializationFailed: {
8426 // Run the init list checker again to emit diagnostics.
Richard Smith0449aaf2013-11-21 23:30:57 +00008427 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
8428 diagnoseListInit(S, Entity, InitList);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008429 break;
8430 }
John McCall4124c492011-10-17 18:40:02 +00008431
8432 case FK_PlaceholderType: {
8433 // FIXME: Already diagnosed!
8434 break;
8435 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00008436
Sebastian Redl048a6d72012-04-01 19:54:59 +00008437 case FK_ExplicitConstructor: {
8438 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
8439 << Args[0]->getSourceRange();
8440 OverloadCandidateSet::iterator Best;
8441 OverloadingResult Ovl
8442 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gay5dcce092012-04-02 19:05:35 +00008443 (void)Ovl;
Sebastian Redl048a6d72012-04-01 19:54:59 +00008444 assert(Ovl == OR_Success && "Inconsistent overload resolution");
8445 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
Richard Smith60437622017-02-09 19:17:44 +00008446 S.Diag(CtorDecl->getLocation(),
8447 diag::note_explicit_ctor_deduction_guide_here) << false;
Sebastian Redl048a6d72012-04-01 19:54:59 +00008448 break;
8449 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008450 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008451
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008452 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008453 return true;
8454}
Douglas Gregore1314a62009-12-18 05:02:21 +00008455
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008456void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008457 switch (SequenceKind) {
8458 case FailedSequence: {
8459 OS << "Failed sequence: ";
8460 switch (Failure) {
8461 case FK_TooManyInitsForReference:
8462 OS << "too many initializers for reference";
8463 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008464
Richard Smith49a6b6e2017-03-24 01:14:25 +00008465 case FK_ParenthesizedListInitForReference:
8466 OS << "parenthesized list init for reference";
8467 break;
8468
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008469 case FK_ArrayNeedsInitList:
8470 OS << "array requires initializer list";
8471 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008472
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008473 case FK_AddressOfUnaddressableFunction:
8474 OS << "address of unaddressable function was taken";
8475 break;
8476
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008477 case FK_ArrayNeedsInitListOrStringLiteral:
8478 OS << "array requires initializer list or string literal";
8479 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008480
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00008481 case FK_ArrayNeedsInitListOrWideStringLiteral:
8482 OS << "array requires initializer list or wide string literal";
8483 break;
8484
8485 case FK_NarrowStringIntoWideCharArray:
8486 OS << "narrow string into wide char array";
8487 break;
8488
8489 case FK_WideStringIntoCharArray:
8490 OS << "wide string into char array";
8491 break;
8492
8493 case FK_IncompatWideStringIntoWideChar:
8494 OS << "incompatible wide string into wide char array";
8495 break;
8496
Richard Smith3a8244d2018-05-01 05:02:45 +00008497 case FK_PlainStringIntoUTF8Char:
8498 OS << "plain string literal into char8_t array";
8499 break;
8500
8501 case FK_UTF8StringIntoPlainChar:
8502 OS << "u8 string literal into char array";
8503 break;
8504
Douglas Gregore2f943b2011-02-22 18:29:51 +00008505 case FK_ArrayTypeMismatch:
8506 OS << "array type mismatch";
8507 break;
8508
8509 case FK_NonConstantArrayInit:
8510 OS << "non-constant array initializer";
8511 break;
8512
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008513 case FK_AddressOfOverloadFailed:
8514 OS << "address of overloaded function failed";
8515 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008516
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008517 case FK_ReferenceInitOverloadFailed:
8518 OS << "overload resolution for reference initialization failed";
8519 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008520
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008521 case FK_NonConstLValueReferenceBindingToTemporary:
8522 OS << "non-const lvalue reference bound to temporary";
8523 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008524
Richard Smithb8c0f552016-12-09 18:49:13 +00008525 case FK_NonConstLValueReferenceBindingToBitfield:
8526 OS << "non-const lvalue reference bound to bit-field";
8527 break;
8528
8529 case FK_NonConstLValueReferenceBindingToVectorElement:
8530 OS << "non-const lvalue reference bound to vector element";
8531 break;
8532
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008533 case FK_NonConstLValueReferenceBindingToUnrelated:
8534 OS << "non-const lvalue reference bound to unrelated type";
8535 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008536
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008537 case FK_RValueReferenceBindingToLValue:
8538 OS << "rvalue reference bound to an lvalue";
8539 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008540
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008541 case FK_ReferenceInitDropsQualifiers:
8542 OS << "reference initialization drops qualifiers";
8543 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008544
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008545 case FK_ReferenceInitFailed:
8546 OS << "reference initialization failed";
8547 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008548
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008549 case FK_ConversionFailed:
8550 OS << "conversion failed";
8551 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008552
John Wiegley01296292011-04-08 18:41:53 +00008553 case FK_ConversionFromPropertyFailed:
8554 OS << "conversion from property failed";
8555 break;
8556
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008557 case FK_TooManyInitsForScalar:
8558 OS << "too many initializers for scalar";
8559 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008560
Richard Smith49a6b6e2017-03-24 01:14:25 +00008561 case FK_ParenthesizedListInitForScalar:
8562 OS << "parenthesized list init for reference";
8563 break;
8564
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008565 case FK_ReferenceBindingToInitList:
8566 OS << "referencing binding to initializer list";
8567 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008568
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008569 case FK_InitListBadDestinationType:
8570 OS << "initializer list for non-aggregate, non-scalar type";
8571 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008572
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008573 case FK_UserConversionOverloadFailed:
8574 OS << "overloading failed for user-defined conversion";
8575 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008576
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008577 case FK_ConstructorOverloadFailed:
8578 OS << "constructor overloading failed";
8579 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008580
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008581 case FK_DefaultInitOfConst:
8582 OS << "default initialization of a const variable";
8583 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008584
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00008585 case FK_Incomplete:
8586 OS << "initialization of incomplete type";
8587 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008588
8589 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008590 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00008591 break;
8592
John McCalla59dc2f2012-01-05 00:13:19 +00008593 case FK_VariableLengthArrayHasInitializer:
8594 OS << "variable length array has an initializer";
8595 break;
8596
John McCall4124c492011-10-17 18:40:02 +00008597 case FK_PlaceholderType:
8598 OS << "initializer expression isn't contextually valid";
8599 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00008600
8601 case FK_ListConstructorOverloadFailed:
8602 OS << "list constructor overloading failed";
8603 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00008604
Sebastian Redl048a6d72012-04-01 19:54:59 +00008605 case FK_ExplicitConstructor:
8606 OS << "list copy initialization chose explicit constructor";
8607 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008608 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008609 OS << '\n';
8610 return;
8611 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008612
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008613 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00008614 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008615 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008616
Sebastian Redld201edf2011-06-05 13:59:11 +00008617 case NormalSequence:
8618 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008619 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008620 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008621
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008622 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
8623 if (S != step_begin()) {
8624 OS << " -> ";
8625 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008626
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008627 switch (S->Kind) {
8628 case SK_ResolveAddressOfOverloadedFunction:
8629 OS << "resolve address of overloaded function";
8630 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008631
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008632 case SK_CastDerivedToBaseRValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00008633 OS << "derived-to-base (rvalue)";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008634 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008635
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008636 case SK_CastDerivedToBaseXValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00008637 OS << "derived-to-base (xvalue)";
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008638 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008639
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008640 case SK_CastDerivedToBaseLValue:
Richard Smithb8c0f552016-12-09 18:49:13 +00008641 OS << "derived-to-base (lvalue)";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008642 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008643
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008644 case SK_BindReference:
8645 OS << "bind reference to lvalue";
8646 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008647
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008648 case SK_BindReferenceToTemporary:
8649 OS << "bind reference to a temporary";
8650 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008651
Richard Smithb8c0f552016-12-09 18:49:13 +00008652 case SK_FinalCopy:
8653 OS << "final copy in class direct-initialization";
8654 break;
8655
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00008656 case SK_ExtraneousCopyToTemporary:
8657 OS << "extraneous C++03 copy to temporary";
8658 break;
8659
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008660 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00008661 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008662 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008663
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008664 case SK_QualificationConversionRValue:
8665 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00008666 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008667
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008668 case SK_QualificationConversionXValue:
8669 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00008670 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00008671
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008672 case SK_QualificationConversionLValue:
8673 OS << "qualification conversion (lvalue)";
8674 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008675
Richard Smith77be48a2014-07-31 06:31:19 +00008676 case SK_AtomicConversion:
8677 OS << "non-atomic-to-atomic conversion";
8678 break;
8679
Jordan Roseb1312a52013-04-11 00:58:58 +00008680 case SK_LValueToRValue:
8681 OS << "load (lvalue to rvalue)";
8682 break;
8683
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008684 case SK_ConversionSequence:
8685 OS << "implicit conversion sequence (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00008686 S->ICS->dump(); // FIXME: use OS
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008687 OS << ")";
8688 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008689
Richard Smithaaa0ec42013-09-21 21:19:19 +00008690 case SK_ConversionSequenceNoNarrowing:
8691 OS << "implicit conversion sequence with narrowing prohibited (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00008692 S->ICS->dump(); // FIXME: use OS
Richard Smithaaa0ec42013-09-21 21:19:19 +00008693 OS << ")";
8694 break;
8695
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008696 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00008697 OS << "list aggregate initialization";
8698 break;
8699
Sebastian Redl29526f02011-11-27 16:50:07 +00008700 case SK_UnwrapInitList:
8701 OS << "unwrap reference initializer list";
8702 break;
8703
8704 case SK_RewrapInitList:
8705 OS << "rewrap reference initializer list";
8706 break;
8707
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008708 case SK_ConstructorInitialization:
8709 OS << "constructor initialization";
8710 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008711
Richard Smith53324112014-07-16 21:33:43 +00008712 case SK_ConstructorInitializationFromList:
8713 OS << "list initialization via constructor";
8714 break;
8715
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008716 case SK_ZeroInitialization:
8717 OS << "zero initialization";
8718 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008719
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008720 case SK_CAssignment:
8721 OS << "C assignment";
8722 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008723
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008724 case SK_StringInit:
8725 OS << "string initialization";
8726 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008727
8728 case SK_ObjCObjectConversion:
8729 OS << "Objective-C object conversion";
8730 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00008731
Richard Smith410306b2016-12-12 02:53:20 +00008732 case SK_ArrayLoopIndex:
8733 OS << "indexing for array initialization loop";
8734 break;
8735
8736 case SK_ArrayLoopInit:
8737 OS << "array initialization loop";
8738 break;
8739
Douglas Gregore2f943b2011-02-22 18:29:51 +00008740 case SK_ArrayInit:
8741 OS << "array initialization";
8742 break;
John McCall31168b02011-06-15 23:02:42 +00008743
Richard Smith378b8c82016-12-14 03:22:16 +00008744 case SK_GNUArrayInit:
8745 OS << "array initialization (GNU extension)";
8746 break;
8747
Richard Smithebeed412012-02-15 22:38:09 +00008748 case SK_ParenthesizedArrayInit:
8749 OS << "parenthesized array initialization";
8750 break;
8751
John McCall31168b02011-06-15 23:02:42 +00008752 case SK_PassByIndirectCopyRestore:
8753 OS << "pass by indirect copy and restore";
8754 break;
8755
8756 case SK_PassByIndirectRestore:
8757 OS << "pass by indirect restore";
8758 break;
8759
8760 case SK_ProduceObjCObject:
8761 OS << "Objective-C object retension";
8762 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00008763
8764 case SK_StdInitializerList:
8765 OS << "std::initializer_list from initializer list";
8766 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008767
Richard Smithf8adcdc2014-07-17 05:12:35 +00008768 case SK_StdInitializerListConstructorCall:
8769 OS << "list initialization from std::initializer_list";
8770 break;
8771
Guy Benyei61054192013-02-07 10:55:47 +00008772 case SK_OCLSamplerInit:
8773 OS << "OpenCL sampler_t from integer constant";
8774 break;
8775
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008776 case SK_OCLZeroEvent:
8777 OS << "OpenCL event_t from zero";
8778 break;
Egor Churaev89831422016-12-23 14:55:49 +00008779
8780 case SK_OCLZeroQueue:
8781 OS << "OpenCL queue_t from zero";
8782 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008783 }
Richard Smith6b216962013-02-05 05:52:24 +00008784
8785 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008786 }
Richard Smith6b216962013-02-05 05:52:24 +00008787
8788 OS << '\n';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00008789}
8790
8791void InitializationSequence::dump() const {
8792 dump(llvm::errs());
8793}
8794
Nico Weber3d7f00d2018-06-19 23:19:34 +00008795static bool NarrowingErrs(const LangOptions &L) {
8796 return L.CPlusPlus11 &&
8797 (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015));
8798}
8799
Richard Smithaaa0ec42013-09-21 21:19:19 +00008800static void DiagnoseNarrowingInInitList(Sema &S,
8801 const ImplicitConversionSequence &ICS,
8802 QualType PreNarrowingType,
Richard Smith66e05fe2012-01-18 05:21:49 +00008803 QualType EntityType,
Richard Smith66e05fe2012-01-18 05:21:49 +00008804 const Expr *PostInit) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008805 const StandardConversionSequence *SCS = nullptr;
Richard Smith66e05fe2012-01-18 05:21:49 +00008806 switch (ICS.getKind()) {
8807 case ImplicitConversionSequence::StandardConversion:
8808 SCS = &ICS.Standard;
8809 break;
8810 case ImplicitConversionSequence::UserDefinedConversion:
8811 SCS = &ICS.UserDefined.After;
8812 break;
8813 case ImplicitConversionSequence::AmbiguousConversion:
8814 case ImplicitConversionSequence::EllipsisConversion:
8815 case ImplicitConversionSequence::BadConversion:
8816 return;
8817 }
8818
Richard Smith66e05fe2012-01-18 05:21:49 +00008819 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
8820 APValue ConstantValue;
Richard Smith5614ca72012-03-23 23:55:39 +00008821 QualType ConstantType;
8822 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
8823 ConstantType)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00008824 case NK_Not_Narrowing:
Richard Smith52e624f2016-12-21 21:42:57 +00008825 case NK_Dependent_Narrowing:
Richard Smith66e05fe2012-01-18 05:21:49 +00008826 // No narrowing occurred.
8827 return;
8828
8829 case NK_Type_Narrowing:
8830 // This was a floating-to-integer conversion, which is always considered a
8831 // narrowing conversion even if the value is a constant and can be
8832 // represented exactly as an integer.
Nico Weber3d7f00d2018-06-19 23:19:34 +00008833 S.Diag(PostInit->getLocStart(), NarrowingErrs(S.getLangOpts())
8834 ? diag::ext_init_list_type_narrowing
8835 : diag::warn_init_list_type_narrowing)
8836 << PostInit->getSourceRange()
8837 << PreNarrowingType.getLocalUnqualifiedType()
8838 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00008839 break;
8840
8841 case NK_Constant_Narrowing:
8842 // A constant value was narrowed.
8843 S.Diag(PostInit->getLocStart(),
Nico Weber3d7f00d2018-06-19 23:19:34 +00008844 NarrowingErrs(S.getLangOpts())
8845 ? diag::ext_init_list_constant_narrowing
8846 : diag::warn_init_list_constant_narrowing)
8847 << PostInit->getSourceRange()
8848 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
8849 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00008850 break;
8851
8852 case NK_Variable_Narrowing:
8853 // A variable's value may have been narrowed.
8854 S.Diag(PostInit->getLocStart(),
Nico Weber3d7f00d2018-06-19 23:19:34 +00008855 NarrowingErrs(S.getLangOpts())
8856 ? diag::ext_init_list_variable_narrowing
8857 : diag::warn_init_list_variable_narrowing)
8858 << PostInit->getSourceRange()
8859 << PreNarrowingType.getLocalUnqualifiedType()
8860 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00008861 break;
8862 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008863
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008864 SmallString<128> StaticCast;
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008865 llvm::raw_svector_ostream OS(StaticCast);
8866 OS << "static_cast<";
8867 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
8868 // It's important to use the typedef's name if there is one so that the
8869 // fixit doesn't break code using types like int64_t.
8870 //
8871 // FIXME: This will break if the typedef requires qualification. But
8872 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00008873 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008874 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikiebbafb8a2012-03-11 07:00:24 +00008875 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008876 else {
8877 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
8878 // with a broken cast.
8879 return;
8880 }
8881 OS << ">(";
Alp Tokerb0869032014-05-17 01:13:18 +00008882 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence)
Alp Tokerb6cc5922014-05-03 03:45:55 +00008883 << PostInit->getSourceRange()
8884 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
8885 << FixItHint::CreateInsertion(
8886 S.getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008887}
8888
Douglas Gregore1314a62009-12-18 05:02:21 +00008889//===----------------------------------------------------------------------===//
8890// Initialization helper functions
8891//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00008892bool
8893Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
8894 ExprResult Init) {
8895 if (Init.isInvalid())
8896 return false;
8897
8898 Expr *InitE = Init.get();
8899 assert(InitE && "No initialization expression");
8900
Douglas Gregorf4cc61d2012-07-31 22:15:04 +00008901 InitializationKind Kind
8902 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008903 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00008904 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00008905}
8906
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008907ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00008908Sema::PerformCopyInitialization(const InitializedEntity &Entity,
8909 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008910 ExprResult Init,
Douglas Gregor6073dca2012-02-24 23:56:31 +00008911 bool TopLevelOfInitList,
8912 bool AllowExplicit) {
Douglas Gregore1314a62009-12-18 05:02:21 +00008913 if (Init.isInvalid())
8914 return ExprError();
8915
John McCall1f425642010-11-11 03:21:53 +00008916 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00008917 assert(InitE && "No initialization expression?");
8918
8919 if (EqualLoc.isInvalid())
8920 EqualLoc = InitE->getLocStart();
8921
8922 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00008923 EqualLoc,
8924 AllowExplicit);
Richard Smithaaa0ec42013-09-21 21:19:19 +00008925 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
Jeffrey Yasskina6667812011-07-26 23:20:30 +00008926
Alex Lorenzde69ff92017-05-16 10:23:58 +00008927 // Prevent infinite recursion when performing parameter copy-initialization.
8928 const bool ShouldTrackCopy =
8929 Entity.isParameterKind() && Seq.isConstructorInitialization();
8930 if (ShouldTrackCopy) {
8931 if (llvm::find(CurrentParameterCopyTypes, Entity.getType()) !=
8932 CurrentParameterCopyTypes.end()) {
8933 Seq.SetOverloadFailure(
8934 InitializationSequence::FK_ConstructorOverloadFailed,
8935 OR_No_Viable_Function);
8936
8937 // Try to give a meaningful diagnostic note for the problematic
8938 // constructor.
8939 const auto LastStep = Seq.step_end() - 1;
8940 assert(LastStep->Kind ==
8941 InitializationSequence::SK_ConstructorInitialization);
8942 const FunctionDecl *Function = LastStep->Function.Function;
8943 auto Candidate =
8944 llvm::find_if(Seq.getFailedCandidateSet(),
8945 [Function](const OverloadCandidate &Candidate) -> bool {
8946 return Candidate.Viable &&
8947 Candidate.Function == Function &&
8948 Candidate.Conversions.size() > 0;
8949 });
8950 if (Candidate != Seq.getFailedCandidateSet().end() &&
8951 Function->getNumParams() > 0) {
8952 Candidate->Viable = false;
8953 Candidate->FailureKind = ovl_fail_bad_conversion;
8954 Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion,
8955 InitE,
8956 Function->getParamDecl(0)->getType());
8957 }
8958 }
8959 CurrentParameterCopyTypes.push_back(Entity.getType());
8960 }
8961
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008962 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith66e05fe2012-01-18 05:21:49 +00008963
Alex Lorenzde69ff92017-05-16 10:23:58 +00008964 if (ShouldTrackCopy)
8965 CurrentParameterCopyTypes.pop_back();
8966
Richard Smith66e05fe2012-01-18 05:21:49 +00008967 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00008968}
Richard Smith60437622017-02-09 19:17:44 +00008969
Richard Smith1363e8f2017-09-07 07:22:36 +00008970/// Determine whether RD is, or is derived from, a specialization of CTD.
8971static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD,
8972 ClassTemplateDecl *CTD) {
8973 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
8974 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
8975 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
8976 };
8977 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
8978}
8979
Richard Smith60437622017-02-09 19:17:44 +00008980QualType Sema::DeduceTemplateSpecializationFromInitializer(
8981 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
8982 const InitializationKind &Kind, MultiExprArg Inits) {
8983 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
8984 TSInfo->getType()->getContainedDeducedType());
8985 assert(DeducedTST && "not a deduced template specialization type");
8986
8987 // We can only perform deduction for class templates.
8988 auto TemplateName = DeducedTST->getTemplateName();
8989 auto *Template =
8990 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
8991 if (!Template) {
8992 Diag(Kind.getLocation(),
8993 diag::err_deduced_non_class_template_specialization_type)
8994 << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName;
8995 if (auto *TD = TemplateName.getAsTemplateDecl())
8996 Diag(TD->getLocation(), diag::note_template_decl_here);
8997 return QualType();
8998 }
8999
Richard Smith32918772017-02-14 00:25:28 +00009000 // Can't deduce from dependent arguments.
9001 if (Expr::hasAnyTypeDependentArguments(Inits))
9002 return Context.DependentTy;
9003
Richard Smith60437622017-02-09 19:17:44 +00009004 // FIXME: Perform "exact type" matching first, per CWG discussion?
9005 // Or implement this via an implied 'T(T) -> T' deduction guide?
9006
9007 // FIXME: Do we need/want a std::initializer_list<T> special case?
9008
Richard Smith32918772017-02-14 00:25:28 +00009009 // Look up deduction guides, including those synthesized from constructors.
9010 //
Richard Smith60437622017-02-09 19:17:44 +00009011 // C++1z [over.match.class.deduct]p1:
9012 // A set of functions and function templates is formed comprising:
Richard Smith32918772017-02-14 00:25:28 +00009013 // - For each constructor of the class template designated by the
9014 // template-name, a function template [...]
Richard Smith60437622017-02-09 19:17:44 +00009015 // - For each deduction-guide, a function or function template [...]
9016 DeclarationNameInfo NameInfo(
9017 Context.DeclarationNames.getCXXDeductionGuideName(Template),
9018 TSInfo->getTypeLoc().getEndLoc());
9019 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
9020 LookupQualifiedName(Guides, Template->getDeclContext());
Richard Smith60437622017-02-09 19:17:44 +00009021
9022 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
9023 // clear on this, but they're not found by name so access does not apply.
9024 Guides.suppressDiagnostics();
9025
9026 // Figure out if this is list-initialization.
9027 InitListExpr *ListInit =
9028 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
9029 ? dyn_cast<InitListExpr>(Inits[0])
9030 : nullptr;
9031
9032 // C++1z [over.match.class.deduct]p1:
9033 // Initialization and overload resolution are performed as described in
9034 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
9035 // (as appropriate for the type of initialization performed) for an object
9036 // of a hypothetical class type, where the selected functions and function
9037 // templates are considered to be the constructors of that class type
9038 //
9039 // Since we know we're initializing a class type of a type unrelated to that
9040 // of the initializer, this reduces to something fairly reasonable.
9041 OverloadCandidateSet Candidates(Kind.getLocation(),
9042 OverloadCandidateSet::CSK_Normal);
9043 OverloadCandidateSet::iterator Best;
9044 auto tryToResolveOverload =
9045 [&](bool OnlyListConstructors) -> OverloadingResult {
Richard Smith67ef14f2017-09-26 18:37:55 +00009046 Candidates.clear(OverloadCandidateSet::CSK_Normal);
Richard Smith32918772017-02-14 00:25:28 +00009047 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
9048 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smith60437622017-02-09 19:17:44 +00009049 if (D->isInvalidDecl())
9050 continue;
9051
Richard Smithbc491202017-02-17 20:05:37 +00009052 auto *TD = dyn_cast<FunctionTemplateDecl>(D);
9053 auto *GD = dyn_cast_or_null<CXXDeductionGuideDecl>(
9054 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
9055 if (!GD)
Richard Smith60437622017-02-09 19:17:44 +00009056 continue;
9057
9058 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
9059 // For copy-initialization, the candidate functions are all the
9060 // converting constructors (12.3.1) of that class.
9061 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
9062 // The converting constructors of T are candidate functions.
9063 if (Kind.isCopyInit() && !ListInit) {
Richard Smithafe4aa82017-02-10 02:19:05 +00009064 // Only consider converting constructors.
Richard Smithbc491202017-02-17 20:05:37 +00009065 if (GD->isExplicit())
Richard Smithafe4aa82017-02-10 02:19:05 +00009066 continue;
Richard Smith60437622017-02-09 19:17:44 +00009067
9068 // When looking for a converting constructor, deduction guides that
Richard Smithafe4aa82017-02-10 02:19:05 +00009069 // could never be called with one argument are not interesting to
9070 // check or note.
Richard Smithbc491202017-02-17 20:05:37 +00009071 if (GD->getMinRequiredArguments() > 1 ||
9072 (GD->getNumParams() == 0 && !GD->isVariadic()))
Richard Smith60437622017-02-09 19:17:44 +00009073 continue;
9074 }
9075
9076 // C++ [over.match.list]p1.1: (first phase list initialization)
9077 // Initially, the candidate functions are the initializer-list
9078 // constructors of the class T
Richard Smithbc491202017-02-17 20:05:37 +00009079 if (OnlyListConstructors && !isInitListConstructor(GD))
Richard Smith60437622017-02-09 19:17:44 +00009080 continue;
9081
9082 // C++ [over.match.list]p1.2: (second phase list initialization)
9083 // the candidate functions are all the constructors of the class T
9084 // C++ [over.match.ctor]p1: (all other cases)
9085 // the candidate functions are all the constructors of the class of
9086 // the object being initialized
9087
9088 // C++ [over.best.ics]p4:
9089 // When [...] the constructor [...] is a candidate by
9090 // - [over.match.copy] (in all cases)
9091 // FIXME: The "second phase of [over.match.list] case can also
9092 // theoretically happen here, but it's not clear whether we can
9093 // ever have a parameter of the right type.
9094 bool SuppressUserConversions = Kind.isCopyInit();
9095
Richard Smith60437622017-02-09 19:17:44 +00009096 if (TD)
Richard Smith32918772017-02-14 00:25:28 +00009097 AddTemplateOverloadCandidate(TD, I.getPair(), /*ExplicitArgs*/ nullptr,
9098 Inits, Candidates,
9099 SuppressUserConversions);
Richard Smith60437622017-02-09 19:17:44 +00009100 else
Richard Smithbc491202017-02-17 20:05:37 +00009101 AddOverloadCandidate(GD, I.getPair(), Inits, Candidates,
Richard Smith60437622017-02-09 19:17:44 +00009102 SuppressUserConversions);
9103 }
9104 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
9105 };
9106
9107 OverloadingResult Result = OR_No_Viable_Function;
9108
9109 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
9110 // try initializer-list constructors.
9111 if (ListInit) {
Richard Smith32918772017-02-14 00:25:28 +00009112 bool TryListConstructors = true;
9113
9114 // Try list constructors unless the list is empty and the class has one or
9115 // more default constructors, in which case those constructors win.
9116 if (!ListInit->getNumInits()) {
9117 for (NamedDecl *D : Guides) {
9118 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
9119 if (FD && FD->getMinRequiredArguments() == 0) {
9120 TryListConstructors = false;
9121 break;
9122 }
9123 }
Richard Smith1363e8f2017-09-07 07:22:36 +00009124 } else if (ListInit->getNumInits() == 1) {
9125 // C++ [over.match.class.deduct]:
9126 // As an exception, the first phase in [over.match.list] (considering
9127 // initializer-list constructors) is omitted if the initializer list
9128 // consists of a single expression of type cv U, where U is a
9129 // specialization of C or a class derived from a specialization of C.
9130 Expr *E = ListInit->getInit(0);
9131 auto *RD = E->getType()->getAsCXXRecordDecl();
9132 if (!isa<InitListExpr>(E) && RD &&
Erik Pilkingtondd0b3442018-07-26 23:40:42 +00009133 isCompleteType(Kind.getLocation(), E->getType()) &&
Richard Smith1363e8f2017-09-07 07:22:36 +00009134 isOrIsDerivedFromSpecializationOf(RD, Template))
9135 TryListConstructors = false;
Richard Smith32918772017-02-14 00:25:28 +00009136 }
9137
9138 if (TryListConstructors)
Richard Smith60437622017-02-09 19:17:44 +00009139 Result = tryToResolveOverload(/*OnlyListConstructor*/true);
9140 // Then unwrap the initializer list and try again considering all
9141 // constructors.
9142 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
9143 }
9144
9145 // If list-initialization fails, or if we're doing any other kind of
9146 // initialization, we (eventually) consider constructors.
9147 if (Result == OR_No_Viable_Function)
9148 Result = tryToResolveOverload(/*OnlyListConstructor*/false);
9149
9150 switch (Result) {
9151 case OR_Ambiguous:
9152 Diag(Kind.getLocation(), diag::err_deduced_class_template_ctor_ambiguous)
9153 << TemplateName;
9154 // FIXME: For list-initialization candidates, it'd usually be better to
9155 // list why they were not viable when given the initializer list itself as
9156 // an argument.
9157 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Inits);
9158 return QualType();
9159
Richard Smith32918772017-02-14 00:25:28 +00009160 case OR_No_Viable_Function: {
9161 CXXRecordDecl *Primary =
9162 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
9163 bool Complete =
9164 isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
Richard Smith60437622017-02-09 19:17:44 +00009165 Diag(Kind.getLocation(),
9166 Complete ? diag::err_deduced_class_template_ctor_no_viable
9167 : diag::err_deduced_class_template_incomplete)
Richard Smith32918772017-02-14 00:25:28 +00009168 << TemplateName << !Guides.empty();
Richard Smith60437622017-02-09 19:17:44 +00009169 Candidates.NoteCandidates(*this, OCD_AllCandidates, Inits);
9170 return QualType();
Richard Smith32918772017-02-14 00:25:28 +00009171 }
Richard Smith60437622017-02-09 19:17:44 +00009172
9173 case OR_Deleted: {
9174 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
9175 << TemplateName;
9176 NoteDeletedFunction(Best->Function);
9177 return QualType();
9178 }
9179
9180 case OR_Success:
9181 // C++ [over.match.list]p1:
9182 // In copy-list-initialization, if an explicit constructor is chosen, the
9183 // initialization is ill-formed.
Richard Smithbc491202017-02-17 20:05:37 +00009184 if (Kind.isCopyInit() && ListInit &&
9185 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
Richard Smith60437622017-02-09 19:17:44 +00009186 bool IsDeductionGuide = !Best->Function->isImplicit();
9187 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
9188 << TemplateName << IsDeductionGuide;
9189 Diag(Best->Function->getLocation(),
9190 diag::note_explicit_ctor_deduction_guide_here)
9191 << IsDeductionGuide;
9192 return QualType();
9193 }
9194
9195 // Make sure we didn't select an unusable deduction guide, and mark it
9196 // as referenced.
9197 DiagnoseUseOfDecl(Best->Function, Kind.getLocation());
9198 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
9199 break;
9200 }
9201
9202 // C++ [dcl.type.class.deduct]p1:
9203 // The placeholder is replaced by the return type of the function selected
9204 // by overload resolution for class template deduction.
9205 return SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());
9206}