blob: 9feb9e060a438d8e44663f8b4685c2ad9d5adc77 [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
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000014#include "clang/Sema/Initialization.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000015#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000016#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000017#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000018#include "clang/AST/ExprObjC.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"
22#include "clang/Sema/Lookup.h"
23#include "clang/Sema/SemaInternal.h"
Sebastian Redlc1839b12012-01-17 22:49:42 +000024#include "llvm/ADT/APInt.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000025#include "llvm/ADT/SmallString.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskina6667812011-07-26 23:20:30 +000027#include "llvm/Support/raw_ostream.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000028#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000029using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000030
Chris Lattner0cb78032009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000035/// \brief Check whether T is compatible with a wide character type (wchar_t,
36/// char16_t or char32_t).
37static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
38 if (Context.typesAreCompatible(Context.getWideCharType(), T))
39 return true;
40 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
41 return Context.typesAreCompatible(Context.Char16Ty, T) ||
42 Context.typesAreCompatible(Context.Char32Ty, T);
43 }
44 return false;
45}
46
47enum StringInitFailureKind {
48 SIF_None,
49 SIF_NarrowStringIntoWideChar,
50 SIF_WideStringIntoChar,
51 SIF_IncompatWideStringIntoWideChar,
52 SIF_Other
53};
54
55/// \brief Check whether the array of type AT can be initialized by the Init
56/// expression by means of string initialization. Returns SIF_None if so,
57/// otherwise returns a StringInitFailureKind that describes why the
58/// initialization would not work.
59static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
60 ASTContext &Context) {
Eli Friedman893abe42009-05-29 18:22:49 +000061 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000062 return SIF_Other;
Eli Friedman893abe42009-05-29 18:22:49 +000063
Chris Lattnera9196812009-02-26 23:26:43 +000064 // See if this is a string literal or @encode.
65 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000066
Chris Lattnera9196812009-02-26 23:26:43 +000067 // Handle @encode, which is a narrow string.
68 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000069 return SIF_None;
Chris Lattnera9196812009-02-26 23:26:43 +000070
71 // Otherwise we can only handle string literals.
72 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Craig Topperc3ec1492014-05-26 06:22:03 +000073 if (!SL)
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000074 return SIF_Other;
Eli Friedman42a84652009-05-31 10:54:53 +000075
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000076 const QualType ElemTy =
77 Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
Douglas Gregorfb65e592011-07-27 05:40:30 +000078
79 switch (SL->getKind()) {
80 case StringLiteral::Ascii:
81 case StringLiteral::UTF8:
82 // char array can be initialized with a narrow string.
83 // Only allow char x[] = "foo"; not char x[] = L"foo";
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000084 if (ElemTy->isCharType())
85 return SIF_None;
86 if (IsWideCharCompatible(ElemTy, Context))
87 return SIF_NarrowStringIntoWideChar;
88 return SIF_Other;
89 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
90 // "An array with element type compatible with a qualified or unqualified
91 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
92 // string literal with the corresponding encoding prefix (L, u, or U,
93 // respectively), optionally enclosed in braces.
Douglas Gregorfb65e592011-07-27 05:40:30 +000094 case StringLiteral::UTF16:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000095 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
96 return SIF_None;
97 if (ElemTy->isCharType())
98 return SIF_WideStringIntoChar;
99 if (IsWideCharCompatible(ElemTy, Context))
100 return SIF_IncompatWideStringIntoWideChar;
101 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000102 case StringLiteral::UTF32:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000103 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
104 return SIF_None;
105 if (ElemTy->isCharType())
106 return SIF_WideStringIntoChar;
107 if (IsWideCharCompatible(ElemTy, Context))
108 return SIF_IncompatWideStringIntoWideChar;
109 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000110 case StringLiteral::Wide:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000111 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
112 return SIF_None;
113 if (ElemTy->isCharType())
114 return SIF_WideStringIntoChar;
115 if (IsWideCharCompatible(ElemTy, Context))
116 return SIF_IncompatWideStringIntoWideChar;
117 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000118 }
Mike Stump11289f42009-09-09 15:08:12 +0000119
Douglas Gregorfb65e592011-07-27 05:40:30 +0000120 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattner0cb78032009-02-24 22:27:37 +0000121}
122
Hans Wennborg950f3182013-05-16 09:22:40 +0000123static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
124 ASTContext &Context) {
John McCall66884dd2011-02-21 07:22:22 +0000125 const ArrayType *arrayType = Context.getAsArrayType(declType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000126 if (!arrayType)
Hans Wennborg950f3182013-05-16 09:22:40 +0000127 return SIF_Other;
128 return IsStringInit(init, arrayType, Context);
John McCall66884dd2011-02-21 07:22:22 +0000129}
130
Richard Smith430c23b2013-05-05 16:40:13 +0000131/// Update the type of a string literal, including any surrounding parentheses,
132/// to match the type of the object which it is initializing.
133static void updateStringLiteralType(Expr *E, QualType Ty) {
Richard Smithd74b16062013-05-06 00:35:47 +0000134 while (true) {
Richard Smith430c23b2013-05-05 16:40:13 +0000135 E->setType(Ty);
Richard Smithd74b16062013-05-06 00:35:47 +0000136 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
137 break;
138 else if (ParenExpr *PE = dyn_cast<ParenExpr>(E))
139 E = PE->getSubExpr();
140 else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
141 E = UO->getSubExpr();
142 else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E))
143 E = GSE->getResultExpr();
144 else
145 llvm_unreachable("unexpected expr in string literal init");
Richard Smith430c23b2013-05-05 16:40:13 +0000146 }
Richard Smith430c23b2013-05-05 16:40:13 +0000147}
148
John McCall5decec92011-02-21 07:57:55 +0000149static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
150 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000151 // Get the length of the string as parsed.
152 uint64_t StrLength =
153 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
154
Mike Stump11289f42009-09-09 15:08:12 +0000155
Chris Lattner0cb78032009-02-24 22:27:37 +0000156 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +0000157 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +0000158 // being initialized to a string literal.
Benjamin Kramere0731772012-08-04 17:00:46 +0000159 llvm::APInt ConstVal(32, StrLength);
Chris Lattner0cb78032009-02-24 22:27:37 +0000160 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +0000161 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
162 ConstVal,
163 ArrayType::Normal, 0);
Richard Smith430c23b2013-05-05 16:40:13 +0000164 updateStringLiteralType(Str, DeclT);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000165 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000166 }
Mike Stump11289f42009-09-09 15:08:12 +0000167
Eli Friedman893abe42009-05-29 18:22:49 +0000168 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000169
Eli Friedman554eba92011-04-11 00:23:45 +0000170 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +0000171 // the size may be smaller or larger than the string we are initializing.
172 // FIXME: Avoid truncation for 64-bit length strings.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000173 if (S.getLangOpts().CPlusPlus) {
Richard Smith430c23b2013-05-05 16:40:13 +0000174 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
Anders Carlssond162fb82011-04-14 00:41:11 +0000175 // For Pascal strings it's OK to strip off the terminating null character,
176 // so the example below is valid:
177 //
178 // unsigned char a[2] = "\pa";
179 if (SL->isPascal())
180 StrLength--;
181 }
182
Eli Friedman554eba92011-04-11 00:23:45 +0000183 // [dcl.init.string]p2
184 if (StrLength > CAT->getSize().getZExtValue())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000185 S.Diag(Str->getLocStart(),
Eli Friedman554eba92011-04-11 00:23:45 +0000186 diag::err_initializer_string_for_char_array_too_long)
187 << Str->getSourceRange();
188 } else {
189 // C99 6.7.8p14.
190 if (StrLength-1 > CAT->getSize().getZExtValue())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000191 S.Diag(Str->getLocStart(),
Eli Friedman554eba92011-04-11 00:23:45 +0000192 diag::warn_initializer_string_for_char_array_too_long)
193 << Str->getSourceRange();
194 }
Mike Stump11289f42009-09-09 15:08:12 +0000195
Eli Friedman893abe42009-05-29 18:22:49 +0000196 // Set the type to the actual size that we are initializing. If we have
197 // something like:
198 // char x[1] = "foo";
199 // then this will set the string literal's type to char[1].
Richard Smith430c23b2013-05-05 16:40:13 +0000200 updateStringLiteralType(Str, DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000201}
202
Chris Lattner0cb78032009-02-24 22:27:37 +0000203//===----------------------------------------------------------------------===//
204// Semantic checking for initializer lists.
205//===----------------------------------------------------------------------===//
206
Douglas Gregorcde232f2009-01-29 01:05:33 +0000207/// @brief Semantic checking for initializer lists.
208///
209/// The InitListChecker class contains a set of routines that each
210/// handle the initialization of a certain kind of entity, e.g.,
211/// arrays, vectors, struct/union types, scalars, etc. The
212/// InitListChecker itself performs a recursive walk of the subobject
213/// structure of the type to be initialized, while stepping through
214/// the initializer list one element at a time. The IList and Index
215/// parameters to each of the Check* routines contain the active
216/// (syntactic) initializer list and the index into that initializer
217/// list that represents the current initializer. Each routine is
218/// responsible for moving that Index forward as it consumes elements.
219///
220/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000221/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000222/// initializer list and the index into that initializer list where we
223/// are copying initializers as we map them over to the semantic
224/// list. Once we have completed our recursive walk of the subobject
225/// structure, we will have constructed a full semantic initializer
226/// list.
227///
228/// C99 designators cause changes in the initializer list traversal,
229/// because they make the initialization "jump" into a specific
230/// subobject and then continue the initialization from that
231/// point. CheckDesignatedInitializer() recursively steps into the
232/// designated subobject and manages backing out the recursion to
233/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000234namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000235class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000236 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000237 bool hadError;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000238 bool VerifyOnly; // no diagnostics, no structure building
Benjamin Kramer6b441d62012-02-23 14:48:40 +0000239 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000240 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000241
Anders Carlsson6cabf312010-01-23 23:23:01 +0000242 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000243 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000244 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000245 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000246 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000247 InitListExpr *IList, QualType &T,
Richard Smith4e0d2e42013-09-20 20:10:22 +0000248 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000249 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000250 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000251 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000252 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000253 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000254 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000255 unsigned &StructuredIndex,
256 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000257 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000258 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000259 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000260 InitListExpr *StructuredList,
261 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000262 void CheckComplexType(const InitializedEntity &Entity,
263 InitListExpr *IList, QualType DeclType,
264 unsigned &Index,
265 InitListExpr *StructuredList,
266 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000267 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000268 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000269 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000270 InitListExpr *StructuredList,
271 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000272 void CheckReferenceType(const InitializedEntity &Entity,
273 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000274 unsigned &Index,
275 InitListExpr *StructuredList,
276 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000277 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000278 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000279 InitListExpr *StructuredList,
280 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000281 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000282 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000283 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000284 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000285 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000286 unsigned &StructuredIndex,
287 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000288 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000289 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000290 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000291 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000292 InitListExpr *StructuredList,
293 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000294 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000295 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000296 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000297 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000298 RecordDecl::field_iterator *NextField,
299 llvm::APSInt *NextElementIndex,
300 unsigned &Index,
301 InitListExpr *StructuredList,
302 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000303 bool FinishSubobjectInit,
304 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000305 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
306 QualType CurrentObjectType,
307 InitListExpr *StructuredList,
308 unsigned StructuredIndex,
309 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000310 void UpdateStructuredListElement(InitListExpr *StructuredList,
311 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000312 Expr *expr);
313 int numArrayElements(QualType DeclType);
314 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000315
Richard Smith454a7cd2014-06-03 08:26:00 +0000316 static ExprResult PerformEmptyInit(Sema &SemaRef,
317 SourceLocation Loc,
318 const InitializedEntity &Entity,
319 bool VerifyOnly);
320 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000321 const InitializedEntity &ParentEntity,
322 InitListExpr *ILE, bool &RequiresSecondPass);
Richard Smith454a7cd2014-06-03 08:26:00 +0000323 void FillInEmptyInitializations(const InitializedEntity &Entity,
Douglas Gregor723796a2009-12-16 06:35:08 +0000324 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000325 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
326 Expr *InitExpr, FieldDecl *Field,
327 bool TopLevelObject);
Richard Smith454a7cd2014-06-03 08:26:00 +0000328 void CheckEmptyInitializable(const InitializedEntity &Entity,
329 SourceLocation Loc);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000330
Douglas Gregor85df8d82009-01-29 00:45:39 +0000331public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000332 InitListChecker(Sema &S, const InitializedEntity &Entity,
Richard Smithde229232013-06-06 11:41:05 +0000333 InitListExpr *IL, QualType &T, bool VerifyOnly);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000334 bool HadError() { return hadError; }
335
336 // @brief Retrieves the fully-structured initializer list used for
337 // semantic analysis and code generation.
338 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
339};
Chris Lattner9ececce2009-02-24 22:48:58 +0000340} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000341
Richard Smith454a7cd2014-06-03 08:26:00 +0000342ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
343 SourceLocation Loc,
344 const InitializedEntity &Entity,
345 bool VerifyOnly) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000346 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
347 true);
Richard Smith454a7cd2014-06-03 08:26:00 +0000348 MultiExprArg SubInit;
349 Expr *InitExpr;
350 InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
351
352 // C++ [dcl.init.aggr]p7:
353 // If there are fewer initializer-clauses in the list than there are
354 // members in the aggregate, then each member not explicitly initialized
355 // ...
Nico Weberbcb70ee2014-07-02 23:51:09 +0000356 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
357 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
358 if (EmptyInitList) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000359 // C++1y / DR1070:
360 // shall be initialized [...] from an empty initializer list.
361 //
362 // We apply the resolution of this DR to C++11 but not C++98, since C++98
363 // does not have useful semantics for initialization from an init list.
364 // We treat this as copy-initialization, because aggregate initialization
365 // always performs copy-initialization on its elements.
366 //
367 // Only do this if we're initializing a class type, to avoid filling in
368 // the initializer list where possible.
369 InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
370 InitListExpr(SemaRef.Context, Loc, None, Loc);
371 InitExpr->setType(SemaRef.Context.VoidTy);
372 SubInit = InitExpr;
373 Kind = InitializationKind::CreateCopy(Loc, Loc);
374 } else {
375 // C++03:
376 // shall be value-initialized.
377 }
378
379 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000380 // libstdc++4.6 marks the vector default constructor as explicit in
381 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
382 // stlport does so too. Look for std::__debug for libstdc++, and for
383 // std:: for stlport. This is effectively a compiler-side implementation of
384 // LWG2193.
385 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
386 InitializationSequence::FK_ExplicitConstructor) {
387 OverloadCandidateSet::iterator Best;
388 OverloadingResult O =
389 InitSeq.getFailedCandidateSet()
390 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
391 (void)O;
392 assert(O == OR_Success && "Inconsistent overload resolution");
393 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
394 CXXRecordDecl *R = CtorDecl->getParent();
395
396 if (CtorDecl->getMinRequiredArguments() == 0 &&
397 CtorDecl->isExplicit() && R->getDeclName() &&
398 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
399
400
401 bool IsInStd = false;
402 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
403 ND && !IsInStd;
404 ND = dyn_cast<NamespaceDecl>(ND->getLexicalParent())) {
405 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
406 IsInStd = true;
407 }
408
409 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
410 .Cases("basic_string", "deque", "forward_list", true)
411 .Cases("list", "map", "multimap", "multiset", true)
412 .Cases("priority_queue", "queue", "set", "stack", true)
413 .Cases("unordered_map", "unordered_set", "vector", true)
414 .Default(false)) {
415 InitSeq.InitializeFrom(
416 SemaRef, Entity,
417 InitializationKind::CreateValue(Loc, Loc, Loc, true),
418 MultiExprArg(), /*TopLevelOfInitList=*/false);
419 // Emit a warning for this. System header warnings aren't shown
420 // by default, but people working on system headers should see it.
421 if (!VerifyOnly) {
422 SemaRef.Diag(CtorDecl->getLocation(),
423 diag::warn_invalid_initializer_from_system_header);
424 SemaRef.Diag(Entity.getDecl()->getLocation(),
425 diag::note_used_in_initialization_here);
426 }
427 }
428 }
429 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000430 if (!InitSeq) {
431 if (!VerifyOnly) {
432 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
433 if (Entity.getKind() == InitializedEntity::EK_Member)
434 SemaRef.Diag(Entity.getDecl()->getLocation(),
435 diag::note_in_omitted_aggregate_initializer)
436 << /*field*/1 << Entity.getDecl();
437 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
438 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
439 << /*array element*/0 << Entity.getElementIndex();
440 }
441 return ExprError();
442 }
443
444 return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
445 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
446}
447
448void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
449 SourceLocation Loc) {
450 assert(VerifyOnly &&
451 "CheckEmptyInitializable is only inteded for verification mode.");
452 if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true).isInvalid())
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000453 hadError = true;
454}
455
Richard Smith454a7cd2014-06-03 08:26:00 +0000456void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000457 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000458 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000459 bool &RequiresSecondPass) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000460 SourceLocation Loc = ILE->getLocEnd();
Douglas Gregor2bb07652009-12-22 00:05:34 +0000461 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000462 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000463 = InitializedEntity::InitializeMember(Field, &ParentEntity);
464 if (Init >= NumInits || !ILE->getInit(Init)) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000465 // C++1y [dcl.init.aggr]p7:
466 // If there are fewer initializer-clauses in the list than there are
467 // members in the aggregate, then each member not explicitly initialized
468 // shall be initialized from its brace-or-equal-initializer [...]
Richard Smith852c9db2013-04-20 22:23:05 +0000469 if (Field->hasInClassInitializer()) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000470 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context, Loc, Field);
Richard Smith852c9db2013-04-20 22:23:05 +0000471 if (Init < NumInits)
472 ILE->setInit(Init, DIE);
473 else {
474 ILE->updateInit(SemaRef.Context, Init, DIE);
475 RequiresSecondPass = true;
476 }
477 return;
478 }
479
Douglas Gregor2bb07652009-12-22 00:05:34 +0000480 if (Field->getType()->isReferenceType()) {
481 // C++ [dcl.init.aggr]p9:
482 // If an incomplete or empty initializer-list leaves a
483 // member of reference type uninitialized, the program is
484 // ill-formed.
485 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
486 << Field->getType()
487 << ILE->getSyntacticForm()->getSourceRange();
488 SemaRef.Diag(Field->getLocation(),
489 diag::note_uninit_reference_member);
490 hadError = true;
491 return;
492 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000493
Richard Smith454a7cd2014-06-03 08:26:00 +0000494 ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
495 /*VerifyOnly*/false);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000496 if (MemberInit.isInvalid()) {
497 hadError = true;
498 return;
499 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000500
Douglas Gregor2bb07652009-12-22 00:05:34 +0000501 if (hadError) {
502 // Do nothing
503 } else if (Init < NumInits) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000504 ILE->setInit(Init, MemberInit.getAs<Expr>());
Richard Smith454a7cd2014-06-03 08:26:00 +0000505 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
506 // Empty initialization requires a constructor call, so
Douglas Gregor2bb07652009-12-22 00:05:34 +0000507 // extend the initializer list to include the constructor
508 // call and make a note that we'll need to take another pass
509 // through the initializer list.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000510 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000511 RequiresSecondPass = true;
512 }
513 } else if (InitListExpr *InnerILE
514 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Richard Smith454a7cd2014-06-03 08:26:00 +0000515 FillInEmptyInitializations(MemberEntity, InnerILE,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000516 RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000517}
518
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000519/// Recursively replaces NULL values within the given initializer list
520/// with expressions that perform value-initialization of the
521/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000522void
Richard Smith454a7cd2014-06-03 08:26:00 +0000523InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
Douglas Gregor723796a2009-12-16 06:35:08 +0000524 InitListExpr *ILE,
525 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000526 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000527 "Should not have void type");
Mike Stump11289f42009-09-09 15:08:12 +0000528
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000529 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000530 const RecordDecl *RDecl = RType->getDecl();
531 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Richard Smith454a7cd2014-06-03 08:26:00 +0000532 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
Douglas Gregor2bb07652009-12-22 00:05:34 +0000533 Entity, ILE, RequiresSecondPass);
Richard Smith852c9db2013-04-20 22:23:05 +0000534 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
535 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000536 for (auto *Field : RDecl->fields()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000537 if (Field->hasInClassInitializer()) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000538 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass);
Richard Smith852c9db2013-04-20 22:23:05 +0000539 break;
540 }
541 }
542 } else {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000543 unsigned Init = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000544 for (auto *Field : RDecl->fields()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000545 if (Field->isUnnamedBitfield())
546 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000547
Douglas Gregor2bb07652009-12-22 00:05:34 +0000548 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000549 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000550
Richard Smith454a7cd2014-06-03 08:26:00 +0000551 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000552 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000553 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000554
Douglas Gregor2bb07652009-12-22 00:05:34 +0000555 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000556
Douglas Gregor2bb07652009-12-22 00:05:34 +0000557 // Only look at the first initialization of a union.
Richard Smith852c9db2013-04-20 22:23:05 +0000558 if (RDecl->isUnion())
Douglas Gregor2bb07652009-12-22 00:05:34 +0000559 break;
560 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000561 }
562
563 return;
Mike Stump11289f42009-09-09 15:08:12 +0000564 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000565
566 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000567
Douglas Gregor723796a2009-12-16 06:35:08 +0000568 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000569 unsigned NumInits = ILE->getNumInits();
570 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000571 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000572 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000573 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
574 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000575 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000576 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000577 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000578 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000579 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000580 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000581 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000582 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000583 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000584
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000585 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000586 if (hadError)
587 return;
588
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000589 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
590 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000591 ElementEntity.setElementIndex(Init);
592
Craig Topperc3ec1492014-05-26 06:22:03 +0000593 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000594 if (!InitExpr && !ILE->hasArrayFiller()) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000595 ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(),
596 ElementEntity,
597 /*VerifyOnly*/false);
Douglas Gregor723796a2009-12-16 06:35:08 +0000598 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000599 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000600 return;
601 }
602
603 if (hadError) {
604 // Do nothing
605 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000606 // For arrays, just set the expression used for value-initialization
607 // of the "holes" in the array.
608 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000609 ILE->setArrayFiller(ElementInit.getAs<Expr>());
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000610 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000611 ILE->setInit(Init, ElementInit.getAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000612 } else {
613 // For arrays, just set the expression used for value-initialization
614 // of the rest of elements and exit.
615 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000616 ILE->setArrayFiller(ElementInit.getAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000617 return;
618 }
619
Richard Smith454a7cd2014-06-03 08:26:00 +0000620 if (!isa<ImplicitValueInitExpr>(ElementInit.get())) {
621 // Empty initialization requires a constructor call, so
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000622 // extend the initializer list to include the constructor
623 // call and make a note that we'll need to take another pass
624 // through the initializer list.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000625 ILE->updateInit(SemaRef.Context, Init, ElementInit.getAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000626 RequiresSecondPass = true;
627 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000628 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000629 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000630 = dyn_cast_or_null<InitListExpr>(InitExpr))
Richard Smith454a7cd2014-06-03 08:26:00 +0000631 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000632 }
633}
634
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000635
Douglas Gregor723796a2009-12-16 06:35:08 +0000636InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000637 InitListExpr *IL, QualType &T,
Richard Smithde229232013-06-06 11:41:05 +0000638 bool VerifyOnly)
639 : SemaRef(S), VerifyOnly(VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000640 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000641
Richard Smith4e0d2e42013-09-20 20:10:22 +0000642 FullyStructuredList =
Craig Topperc3ec1492014-05-26 06:22:03 +0000643 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000644 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000645 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000646
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000647 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000648 bool RequiresSecondPass = false;
Richard Smith454a7cd2014-06-03 08:26:00 +0000649 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000650 if (RequiresSecondPass && !hadError)
Richard Smith454a7cd2014-06-03 08:26:00 +0000651 FillInEmptyInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000652 RequiresSecondPass);
653 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000654}
655
656int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000657 // FIXME: use a proper constant
658 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000659 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000660 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000661 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
662 }
663 return maxElements;
664}
665
666int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000667 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000668 int InitializableMembers = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000669 for (const auto *Field : structDecl->fields())
Douglas Gregor556e5862011-10-10 17:22:13 +0000670 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000671 ++InitializableMembers;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000672
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000673 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000674 return std::min(InitializableMembers, 1);
675 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000676}
677
Richard Smith4e0d2e42013-09-20 20:10:22 +0000678/// Check whether the range of the initializer \p ParentIList from element
679/// \p Index onwards can be used to initialize an object of type \p T. Update
680/// \p Index to indicate how many elements of the list were consumed.
681///
682/// This also fills in \p StructuredList, from element \p StructuredIndex
683/// onwards, with the fully-braced, desugared form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000684void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000685 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000686 QualType T, unsigned &Index,
687 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000688 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000689 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000690
Steve Narofff8ecff22008-05-01 22:18:59 +0000691 if (T->isArrayType())
692 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000693 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000694 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000695 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000696 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000697 else
David Blaikie83d382b2011-09-23 05:06:16 +0000698 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000699
Eli Friedmane0f832b2008-05-25 13:49:22 +0000700 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000701 if (!VerifyOnly)
702 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
703 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000704 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000705 hadError = true;
706 return;
707 }
708
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000709 // Build a structured initializer list corresponding to this subobject.
710 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000711 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
712 StructuredIndex,
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000713 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregor5741efb2009-03-01 17:12:46 +0000714 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000715 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000716
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000717 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000718 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000719 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000720 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000721 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000722 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000723
Richard Smithde229232013-06-06 11:41:05 +0000724 if (!VerifyOnly) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000725 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000726
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000727 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000728 // Update the structured sub-object initializer so that it's ending
729 // range corresponds with the end of the last initializer it used.
730 if (EndIndex < ParentIList->getNumInits()) {
731 SourceLocation EndLoc
732 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
733 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
734 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000735
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000736 // Complain about missing braces.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000737 if (T->isArrayType() || T->isRecordType()) {
738 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Richard Smithde229232013-06-06 11:41:05 +0000739 diag::warn_missing_braces)
Alp Tokerb6cc5922014-05-03 03:45:55 +0000740 << StructuredSubobjectInitList->getSourceRange()
741 << FixItHint::CreateInsertion(
742 StructuredSubobjectInitList->getLocStart(), "{")
743 << FixItHint::CreateInsertion(
744 SemaRef.getLocForEndOfToken(
745 StructuredSubobjectInitList->getLocEnd()),
746 "}");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000747 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000748 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000749}
750
Richard Smith4e0d2e42013-09-20 20:10:22 +0000751/// Check whether the initializer \p IList (that was written with explicit
752/// braces) can be used to initialize an object of type \p T.
753///
754/// This also fills in \p StructuredList with the fully-braced, desugared
755/// form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000756void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000757 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000758 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000759 bool TopLevelObject) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000760 if (!VerifyOnly) {
761 SyntacticToSemantic[IList] = StructuredList;
762 StructuredList->setSyntacticForm(IList);
763 }
Richard Smith4e0d2e42013-09-20 20:10:22 +0000764
765 unsigned Index = 0, StructuredIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000766 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000767 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000768 if (!VerifyOnly) {
Eli Friedman91f5ae52012-02-23 02:25:10 +0000769 QualType ExprTy = T;
770 if (!ExprTy->isArrayType())
771 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000772 IList->setType(ExprTy);
773 StructuredList->setType(ExprTy);
774 }
Eli Friedman85f54972008-05-25 13:22:35 +0000775 if (hadError)
776 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000777
Eli Friedman85f54972008-05-25 13:22:35 +0000778 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000779 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000780 if (VerifyOnly) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000781 if (SemaRef.getLangOpts().CPlusPlus ||
782 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000783 IList->getType()->isVectorType())) {
784 hadError = true;
785 }
786 return;
787 }
788
Eli Friedmanbd327452009-05-29 20:20:05 +0000789 if (StructuredIndex == 1 &&
Hans Wennborg950f3182013-05-16 09:22:40 +0000790 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
791 SIF_None) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000792 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000793 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000794 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000795 hadError = true;
796 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000797 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000798 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000799 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000800 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000801 // Don't complain for incomplete types, since we'll get an error
802 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000803 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000804 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000805 CurrentObjectType->isArrayType()? 0 :
806 CurrentObjectType->isVectorType()? 1 :
807 CurrentObjectType->isScalarType()? 2 :
808 CurrentObjectType->isUnionType()? 3 :
809 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000810
811 unsigned DK = diag::warn_excess_initializers;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000812 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanbd327452009-05-29 20:20:05 +0000813 DK = diag::err_excess_initializers;
814 hadError = true;
815 }
David Blaikiebbafb8a2012-03-11 07:00:24 +0000816 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman425038c2009-07-07 21:53:06 +0000817 DK = diag::err_excess_initializers;
818 hadError = true;
819 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000820
Chris Lattnerb0912a52009-02-24 22:50:46 +0000821 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000822 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000823 }
824 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000825
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000826 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
827 !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000828 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000829 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000830 << FixItHint::CreateRemoval(IList->getLocStart())
831 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000832}
833
Anders Carlsson6cabf312010-01-23 23:23:01 +0000834void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000835 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000836 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000837 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000838 unsigned &Index,
839 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000840 unsigned &StructuredIndex,
841 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000842 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
843 // Explicitly braced initializer for complex type can be real+imaginary
844 // parts.
845 CheckComplexType(Entity, IList, DeclType, Index,
846 StructuredList, StructuredIndex);
847 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000848 CheckScalarType(Entity, IList, DeclType, Index,
849 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000850 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000851 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000852 StructuredList, StructuredIndex);
Richard Smithe20c83d2012-07-07 08:35:56 +0000853 } else if (DeclType->isRecordType()) {
854 assert(DeclType->isAggregateType() &&
855 "non-aggregate records should be handed in CheckSubElementType");
856 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
857 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
858 SubobjectIsDesignatorContext, Index,
859 StructuredList, StructuredIndex,
860 TopLevelObject);
861 } else if (DeclType->isArrayType()) {
862 llvm::APSInt Zero(
863 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
864 false);
865 CheckArrayType(Entity, IList, DeclType, Zero,
866 SubobjectIsDesignatorContext, Index,
867 StructuredList, StructuredIndex);
Steve Naroffeaf58532008-08-10 16:05:48 +0000868 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
869 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000870 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000871 if (!VerifyOnly)
872 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
873 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000874 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000875 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000876 CheckReferenceType(Entity, IList, DeclType, Index,
877 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000878 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000879 if (!VerifyOnly)
880 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
881 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000882 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000883 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000884 if (!VerifyOnly)
885 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
886 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000887 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000888 }
889}
890
Anders Carlsson6cabf312010-01-23 23:23:01 +0000891void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000892 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000893 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000894 unsigned &Index,
895 InitListExpr *StructuredList,
896 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000897 Expr *expr = IList->getInit(Index);
Richard Smith72752e82013-05-31 02:56:17 +0000898
899 if (ElemType->isReferenceType())
900 return CheckReferenceType(Entity, IList, ElemType, Index,
901 StructuredList, StructuredIndex);
902
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000903 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Richard Smithe20c83d2012-07-07 08:35:56 +0000904 if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
Richard Smith4e0d2e42013-09-20 20:10:22 +0000905 InitListExpr *InnerStructuredList
Richard Smithe20c83d2012-07-07 08:35:56 +0000906 = getStructuredSubobjectInit(IList, Index, ElemType,
907 StructuredList, StructuredIndex,
908 SubInitList->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000909 CheckExplicitInitList(Entity, SubInitList, ElemType,
910 InnerStructuredList);
Richard Smithe20c83d2012-07-07 08:35:56 +0000911 ++StructuredIndex;
912 ++Index;
913 return;
914 }
915 assert(SemaRef.getLangOpts().CPlusPlus &&
916 "non-aggregate records are only possible in C++");
917 // C++ initialization is handled later.
918 }
919
Eli Friedman4628cf72013-08-19 22:12:56 +0000920 // FIXME: Need to handle atomic aggregate types with implicit init lists.
921 if (ElemType->isScalarType() || ElemType->isAtomicType())
John McCall5decec92011-02-21 07:57:55 +0000922 return CheckScalarType(Entity, IList, ElemType, Index,
923 StructuredList, StructuredIndex);
Anders Carlsson03068aa2009-08-27 17:18:13 +0000924
Eli Friedman4628cf72013-08-19 22:12:56 +0000925 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
926 ElemType->isArrayType()) && "Unexpected type");
927
John McCall5decec92011-02-21 07:57:55 +0000928 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
929 // arrayType can be incomplete if we're initializing a flexible
930 // array member. There's nothing we can do with the completed
931 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000932
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000933 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedmand8d7a372011-09-26 19:09:09 +0000934 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000935 CheckStringInit(expr, ElemType, arrayType, SemaRef);
936 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedmand8d7a372011-09-26 19:09:09 +0000937 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000938 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000939 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000940 }
John McCall5decec92011-02-21 07:57:55 +0000941
942 // Fall through for subaggregate initialization.
943
David Blaikiebbafb8a2012-03-11 07:00:24 +0000944 } else if (SemaRef.getLangOpts().CPlusPlus) {
John McCall5decec92011-02-21 07:57:55 +0000945 // C++ [dcl.init.aggr]p12:
946 // All implicit type conversions (clause 4) are considered when
Sebastian Redl26bcc942011-09-24 17:47:39 +0000947 // initializing the aggregate member with an initializer from
John McCall5decec92011-02-21 07:57:55 +0000948 // an initializer-list. If the initializer can initialize a
949 // member, the member is initialized. [...]
950
951 // FIXME: Better EqualLoc?
952 InitializationKind Kind =
953 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000954 InitializationSequence Seq(SemaRef, Entity, Kind, expr);
John McCall5decec92011-02-21 07:57:55 +0000955
956 if (Seq) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000957 if (!VerifyOnly) {
Richard Smith0f8ede12011-12-20 04:00:21 +0000958 ExprResult Result =
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000959 Seq.Perform(SemaRef, Entity, Kind, expr);
Richard Smith0f8ede12011-12-20 04:00:21 +0000960 if (Result.isInvalid())
961 hadError = true;
John McCall5decec92011-02-21 07:57:55 +0000962
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000963 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000964 Result.getAs<Expr>());
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000965 }
John McCall5decec92011-02-21 07:57:55 +0000966 ++Index;
967 return;
968 }
969
970 // Fall through for subaggregate initialization
971 } else {
972 // C99 6.7.8p13:
973 //
974 // The initializer for a structure or union object that has
975 // automatic storage duration shall be either an initializer
976 // list as described below, or a single expression that has
977 // compatible structure or union type. In the latter case, the
978 // initial value of the object, including unnamed members, is
979 // that of the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000980 ExprResult ExprRes = expr;
John McCall5decec92011-02-21 07:57:55 +0000981 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000982 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
983 !VerifyOnly)
Eli Friedmanb2a8d462013-09-17 04:07:04 +0000984 != Sema::Incompatible) {
John Wiegley01296292011-04-08 18:41:53 +0000985 if (ExprRes.isInvalid())
986 hadError = true;
987 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000988 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000989 if (ExprRes.isInvalid())
990 hadError = true;
John Wiegley01296292011-04-08 18:41:53 +0000991 }
992 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000993 ExprRes.getAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +0000994 ++Index;
995 return;
996 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000997 ExprRes.get();
John McCall5decec92011-02-21 07:57:55 +0000998 // Fall through for subaggregate initialization
999 }
1000
1001 // C++ [dcl.init.aggr]p12:
1002 //
1003 // [...] Otherwise, if the member is itself a non-empty
1004 // subaggregate, brace elision is assumed and the initializer is
1005 // considered for the initialization of the first member of
1006 // the subaggregate.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001007 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner83559382011-07-15 23:07:01 +00001008 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCall5decec92011-02-21 07:57:55 +00001009 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1010 StructuredIndex);
1011 ++StructuredIndex;
1012 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001013 if (!VerifyOnly) {
1014 // We cannot initialize this element, so let
1015 // PerformCopyInitialization produce the appropriate diagnostic.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001016 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001017 /*TopLevelOfInitList=*/true);
1018 }
John McCall5decec92011-02-21 07:57:55 +00001019 hadError = true;
1020 ++Index;
1021 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +00001022 }
Eli Friedman23a9e312008-05-19 19:16:24 +00001023}
1024
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001025void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1026 InitListExpr *IList, QualType DeclType,
1027 unsigned &Index,
1028 InitListExpr *StructuredList,
1029 unsigned &StructuredIndex) {
1030 assert(Index == 0 && "Index in explicit init list must be zero");
1031
1032 // As an extension, clang supports complex initializers, which initialize
1033 // a complex number component-wise. When an explicit initializer list for
1034 // a complex number contains two two initializers, this extension kicks in:
1035 // it exepcts the initializer list to contain two elements convertible to
1036 // the element type of the complex type. The first element initializes
1037 // the real part, and the second element intitializes the imaginary part.
1038
1039 if (IList->getNumInits() != 2)
1040 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1041 StructuredIndex);
1042
1043 // This is an extension in C. (The builtin _Complex type does not exist
1044 // in the C++ standard.)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001045 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001046 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
1047 << IList->getSourceRange();
1048
1049 // Initialize the complex number.
1050 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1051 InitializedEntity ElementEntity =
1052 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1053
1054 for (unsigned i = 0; i < 2; ++i) {
1055 ElementEntity.setElementIndex(Index);
1056 CheckSubElementType(ElementEntity, IList, elementType, Index,
1057 StructuredList, StructuredIndex);
1058 }
1059}
1060
1061
Anders Carlsson6cabf312010-01-23 23:23:01 +00001062void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001063 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +00001064 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001065 InitListExpr *StructuredList,
1066 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +00001067 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +00001068 if (!VerifyOnly)
1069 SemaRef.Diag(IList->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001070 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smithc8239732011-10-18 21:39:00 +00001071 diag::warn_cxx98_compat_empty_scalar_initializer :
1072 diag::err_empty_scalar_initializer)
1073 << IList->getSourceRange();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001074 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001075 ++Index;
1076 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001077 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001078 }
John McCall643169b2010-11-11 00:46:36 +00001079
1080 Expr *expr = IList->getInit(Index);
1081 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Richard Smithfe9d2c02013-11-19 03:41:32 +00001082 // FIXME: This is invalid, and accepting it causes overload resolution
1083 // to pick the wrong overload in some corner cases.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001084 if (!VerifyOnly)
1085 SemaRef.Diag(SubIList->getLocStart(),
Richard Smithfe9d2c02013-11-19 03:41:32 +00001086 diag::ext_many_braces_around_scalar_init)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001087 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001088
1089 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1090 StructuredIndex);
1091 return;
1092 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001093 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001094 SemaRef.Diag(expr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001095 diag::err_designator_for_scalar_init)
1096 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001097 hadError = true;
1098 ++Index;
1099 ++StructuredIndex;
1100 return;
1101 }
1102
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001103 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001104 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001105 hadError = true;
1106 ++Index;
1107 return;
1108 }
1109
John McCall643169b2010-11-11 00:46:36 +00001110 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001111 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001112 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +00001113
Craig Topperc3ec1492014-05-26 06:22:03 +00001114 Expr *ResultExpr = nullptr;
John McCall643169b2010-11-11 00:46:36 +00001115
1116 if (Result.isInvalid())
1117 hadError = true; // types weren't compatible.
1118 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001119 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001120
John McCall643169b2010-11-11 00:46:36 +00001121 if (ResultExpr != expr) {
1122 // The type was promoted, update initializer list.
1123 IList->setInit(Index, ResultExpr);
1124 }
1125 }
1126 if (hadError)
1127 ++StructuredIndex;
1128 else
1129 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1130 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001131}
1132
Anders Carlsson6cabf312010-01-23 23:23:01 +00001133void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1134 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +00001135 unsigned &Index,
1136 InitListExpr *StructuredList,
1137 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001138 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001139 // FIXME: It would be wonderful if we could point at the actual member. In
1140 // general, it would be useful to pass location information down the stack,
1141 // so that we know the location (or decl) of the "current object" being
1142 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001143 if (!VerifyOnly)
1144 SemaRef.Diag(IList->getLocStart(),
1145 diag::err_init_reference_member_uninitialized)
1146 << DeclType
1147 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +00001148 hadError = true;
1149 ++Index;
1150 ++StructuredIndex;
1151 return;
1152 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001153
1154 Expr *expr = IList->getInit(Index);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001155 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001156 if (!VerifyOnly)
1157 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1158 << DeclType << IList->getSourceRange();
1159 hadError = true;
1160 ++Index;
1161 ++StructuredIndex;
1162 return;
1163 }
1164
1165 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001166 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001167 hadError = true;
1168 ++Index;
1169 return;
1170 }
1171
1172 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001173 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1174 /*TopLevelOfInitList=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001175
1176 if (Result.isInvalid())
1177 hadError = true;
1178
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001179 expr = Result.getAs<Expr>();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001180 IList->setInit(Index, expr);
1181
1182 if (hadError)
1183 ++StructuredIndex;
1184 else
1185 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1186 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001187}
1188
Anders Carlsson6cabf312010-01-23 23:23:01 +00001189void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001190 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001191 unsigned &Index,
1192 InitListExpr *StructuredList,
1193 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001194 const VectorType *VT = DeclType->getAs<VectorType>();
1195 unsigned maxElements = VT->getNumElements();
1196 unsigned numEltsInit = 0;
1197 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001198
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001199 if (Index >= IList->getNumInits()) {
1200 // Make sure the element type can be value-initialized.
1201 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001202 CheckEmptyInitializable(
1203 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1204 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001205 return;
1206 }
1207
David Blaikiebbafb8a2012-03-11 07:00:24 +00001208 if (!SemaRef.getLangOpts().OpenCL) {
John McCall6a16b2f2010-10-30 00:11:39 +00001209 // If the initializing element is a vector, try to copy-initialize
1210 // instead of breaking it apart (which is doomed to failure anyway).
1211 Expr *Init = IList->getInit(Index);
1212 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001213 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001214 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001215 hadError = true;
1216 ++Index;
1217 return;
1218 }
1219
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001220 ExprResult Result =
1221 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
1222 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001223
Craig Topperc3ec1492014-05-26 06:22:03 +00001224 Expr *ResultExpr = nullptr;
John McCall6a16b2f2010-10-30 00:11:39 +00001225 if (Result.isInvalid())
1226 hadError = true; // types weren't compatible.
1227 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001228 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001229
John McCall6a16b2f2010-10-30 00:11:39 +00001230 if (ResultExpr != Init) {
1231 // The type was promoted, update initializer list.
1232 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001233 }
1234 }
John McCall6a16b2f2010-10-30 00:11:39 +00001235 if (hadError)
1236 ++StructuredIndex;
1237 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001238 UpdateStructuredListElement(StructuredList, StructuredIndex,
1239 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001240 ++Index;
1241 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001242 }
Mike Stump11289f42009-09-09 15:08:12 +00001243
John McCall6a16b2f2010-10-30 00:11:39 +00001244 InitializedEntity ElementEntity =
1245 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001246
John McCall6a16b2f2010-10-30 00:11:39 +00001247 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1248 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001249 if (Index >= IList->getNumInits()) {
1250 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001251 CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
John McCall6a16b2f2010-10-30 00:11:39 +00001252 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001253 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001254
John McCall6a16b2f2010-10-30 00:11:39 +00001255 ElementEntity.setElementIndex(Index);
1256 CheckSubElementType(ElementEntity, IList, elementType, Index,
1257 StructuredList, StructuredIndex);
1258 }
James Molloy9eef2652014-06-20 14:35:13 +00001259
1260 if (VerifyOnly)
1261 return;
1262
1263 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1264 const VectorType *T = Entity.getType()->getAs<VectorType>();
1265 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1266 T->getVectorKind() == VectorType::NeonPolyVector)) {
1267 // The ability to use vector initializer lists is a GNU vector extension
1268 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1269 // endian machines it works fine, however on big endian machines it
1270 // exhibits surprising behaviour:
1271 //
1272 // uint32x2_t x = {42, 64};
1273 // return vget_lane_u32(x, 0); // Will return 64.
1274 //
1275 // Because of this, explicitly call out that it is non-portable.
1276 //
1277 SemaRef.Diag(IList->getLocStart(),
1278 diag::warn_neon_vector_initializer_non_portable);
1279
1280 const char *typeCode;
1281 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1282
1283 if (elementType->isFloatingType())
1284 typeCode = "f";
1285 else if (elementType->isSignedIntegerType())
1286 typeCode = "s";
1287 else if (elementType->isUnsignedIntegerType())
1288 typeCode = "u";
1289 else
1290 llvm_unreachable("Invalid element type!");
1291
1292 SemaRef.Diag(IList->getLocStart(),
1293 SemaRef.Context.getTypeSize(VT) > 64 ?
1294 diag::note_neon_vector_initializer_non_portable_q :
1295 diag::note_neon_vector_initializer_non_portable)
1296 << typeCode << typeSize;
1297 }
1298
John McCall6a16b2f2010-10-30 00:11:39 +00001299 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001300 }
John McCall6a16b2f2010-10-30 00:11:39 +00001301
1302 InitializedEntity ElementEntity =
1303 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001304
John McCall6a16b2f2010-10-30 00:11:39 +00001305 // OpenCL initializers allows vectors to be constructed from vectors.
1306 for (unsigned i = 0; i < maxElements; ++i) {
1307 // Don't attempt to go past the end of the init list
1308 if (Index >= IList->getNumInits())
1309 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001310
John McCall6a16b2f2010-10-30 00:11:39 +00001311 ElementEntity.setElementIndex(Index);
1312
1313 QualType IType = IList->getInit(Index)->getType();
1314 if (!IType->isVectorType()) {
1315 CheckSubElementType(ElementEntity, IList, elementType, Index,
1316 StructuredList, StructuredIndex);
1317 ++numEltsInit;
1318 } else {
1319 QualType VecType;
1320 const VectorType *IVT = IType->getAs<VectorType>();
1321 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001322
John McCall6a16b2f2010-10-30 00:11:39 +00001323 if (IType->isExtVectorType())
1324 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1325 else
1326 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001327 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001328 CheckSubElementType(ElementEntity, IList, VecType, Index,
1329 StructuredList, StructuredIndex);
1330 numEltsInit += numIElts;
1331 }
1332 }
1333
1334 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001335 if (numEltsInit != maxElements) {
1336 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001337 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001338 diag::err_vector_incorrect_num_initializers)
1339 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1340 hadError = true;
1341 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001342}
1343
Anders Carlsson6cabf312010-01-23 23:23:01 +00001344void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001345 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001346 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001347 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001348 unsigned &Index,
1349 InitListExpr *StructuredList,
1350 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001351 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1352
Steve Narofff8ecff22008-05-01 22:18:59 +00001353 // Check for the special-case of initializing an array with a string.
1354 if (Index < IList->getNumInits()) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001355 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1356 SIF_None) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001357 // We place the string literal directly into the resulting
1358 // initializer list. This is the only place where the structure
1359 // of the structured initializer list doesn't match exactly,
1360 // because doing so would involve allocating one character
1361 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001362 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001363 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1364 UpdateStructuredListElement(StructuredList, StructuredIndex,
1365 IList->getInit(Index));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001366 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1367 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001368 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001369 return;
1370 }
1371 }
John McCall66884dd2011-02-21 07:22:22 +00001372 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001373 // Check for VLAs; in standard C it would be possible to check this
1374 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1375 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001376 if (!VerifyOnly)
1377 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1378 diag::err_variable_object_no_init)
1379 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001380 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001381 ++Index;
1382 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001383 return;
1384 }
1385
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001386 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001387 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1388 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001389 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001390 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001391 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001392 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001393 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001394 maxElementsKnown = true;
1395 }
1396
John McCall66884dd2011-02-21 07:22:22 +00001397 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001398 while (Index < IList->getNumInits()) {
1399 Expr *Init = IList->getInit(Index);
1400 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001401 // If we're not the subobject that matches up with the '{' for
1402 // the designator, we shouldn't be handling the
1403 // designator. Return immediately.
1404 if (!SubobjectIsDesignatorContext)
1405 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001406
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001407 // Handle this designated initializer. elementIndex will be
1408 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001409 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001410 DeclType, nullptr, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001411 StructuredList, StructuredIndex, true,
1412 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001413 hadError = true;
1414 continue;
1415 }
1416
Douglas Gregor033d1252009-01-23 16:54:12 +00001417 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001418 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001419 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001420 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001421 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001422
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001423 // If the array is of incomplete type, keep track of the number of
1424 // elements in the initializer.
1425 if (!maxElementsKnown && elementIndex > maxElements)
1426 maxElements = elementIndex;
1427
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001428 continue;
1429 }
1430
1431 // If we know the maximum number of elements, and we've already
1432 // hit it, stop consuming elements in the initializer list.
1433 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001434 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001435
Anders Carlsson6cabf312010-01-23 23:23:01 +00001436 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001437 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001438 Entity);
1439 // Check this element.
1440 CheckSubElementType(ElementEntity, IList, elementType, Index,
1441 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001442 ++elementIndex;
1443
1444 // If the array is of incomplete type, keep track of the number of
1445 // elements in the initializer.
1446 if (!maxElementsKnown && elementIndex > maxElements)
1447 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001448 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001449 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001450 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001451 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001452 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001453 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001454 // Sizing an array implicitly to zero is not allowed by ISO C,
1455 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001456 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001457 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001458 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001459
Mike Stump11289f42009-09-09 15:08:12 +00001460 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001461 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001462 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001463 if (!hadError && VerifyOnly) {
1464 // Check if there are any members of the array that get value-initialized.
1465 // If so, check if doing that is possible.
1466 // FIXME: This needs to detect holes left by designated initializers too.
1467 if (maxElementsKnown && elementIndex < maxElements)
Richard Smith454a7cd2014-06-03 08:26:00 +00001468 CheckEmptyInitializable(InitializedEntity::InitializeElement(
1469 SemaRef.Context, 0, Entity),
1470 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001471 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001472}
1473
Eli Friedman3fa64df2011-08-23 22:24:57 +00001474bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1475 Expr *InitExpr,
1476 FieldDecl *Field,
1477 bool TopLevelObject) {
1478 // Handle GNU flexible array initializers.
1479 unsigned FlexArrayDiag;
1480 if (isa<InitListExpr>(InitExpr) &&
1481 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1482 // Empty flexible array init always allowed as an extension
1483 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001484 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedman3fa64df2011-08-23 22:24:57 +00001485 // Disallow flexible array init in C++; it is not required for gcc
1486 // compatibility, and it needs work to IRGen correctly in general.
1487 FlexArrayDiag = diag::err_flexible_array_init;
1488 } else if (!TopLevelObject) {
1489 // Disallow flexible array init on non-top-level object
1490 FlexArrayDiag = diag::err_flexible_array_init;
1491 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1492 // Disallow flexible array init on anything which is not a variable.
1493 FlexArrayDiag = diag::err_flexible_array_init;
1494 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1495 // Disallow flexible array init on local variables.
1496 FlexArrayDiag = diag::err_flexible_array_init;
1497 } else {
1498 // Allow other cases.
1499 FlexArrayDiag = diag::ext_flexible_array_init;
1500 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001501
1502 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001503 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001504 FlexArrayDiag)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001505 << InitExpr->getLocStart();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001506 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1507 << Field;
1508 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001509
1510 return FlexArrayDiag != diag::ext_flexible_array_init;
1511}
1512
Anders Carlsson6cabf312010-01-23 23:23:01 +00001513void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001514 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001515 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001516 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001517 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001518 unsigned &Index,
1519 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001520 unsigned &StructuredIndex,
1521 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001522 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001523
Eli Friedman23a9e312008-05-19 19:16:24 +00001524 // If the record is invalid, some of it's members are invalid. To avoid
1525 // confusion, we forgo checking the intializer for the entire record.
1526 if (structDecl->isInvalidDecl()) {
Richard Smith845aa662012-09-28 21:23:50 +00001527 // Assume it was supposed to consume a single initializer.
1528 ++Index;
Eli Friedman23a9e312008-05-19 19:16:24 +00001529 hadError = true;
1530 return;
Mike Stump11289f42009-09-09 15:08:12 +00001531 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001532
1533 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001534 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith852c9db2013-04-20 22:23:05 +00001535
1536 // If there's a default initializer, use it.
1537 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1538 if (VerifyOnly)
1539 return;
1540 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1541 Field != FieldEnd; ++Field) {
1542 if (Field->hasInClassInitializer()) {
1543 StructuredList->setInitializedFieldInUnion(*Field);
1544 // FIXME: Actually build a CXXDefaultInitExpr?
1545 return;
1546 }
1547 }
1548 }
1549
1550 // Value-initialize the first named member of the union.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001551 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1552 Field != FieldEnd; ++Field) {
1553 if (Field->getDeclName()) {
1554 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001555 CheckEmptyInitializable(
1556 InitializedEntity::InitializeMember(*Field, &Entity),
1557 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001558 else
David Blaikie40ed2972012-06-06 20:45:41 +00001559 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001560 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001561 }
1562 }
1563 return;
1564 }
1565
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001566 // If structDecl is a forward declaration, this loop won't do
1567 // anything except look at designated initializers; That's okay,
1568 // because an error should get printed out elsewhere. It might be
1569 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001570 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001571 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001572 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001573 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001574 while (Index < IList->getNumInits()) {
1575 Expr *Init = IList->getInit(Index);
1576
1577 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001578 // If we're not the subobject that matches up with the '{' for
1579 // the designator, we shouldn't be handling the
1580 // designator. Return immediately.
1581 if (!SubobjectIsDesignatorContext)
1582 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001583
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001584 // Handle this designated initializer. Field will be updated to
1585 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001586 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001587 DeclType, &Field, nullptr, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001588 StructuredList, StructuredIndex,
1589 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001590 hadError = true;
1591
Douglas Gregora9add4e2009-02-12 19:00:39 +00001592 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001593
1594 // Disable check for missing fields when designators are used.
1595 // This matches gcc behaviour.
1596 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001597 continue;
1598 }
1599
1600 if (Field == FieldEnd) {
1601 // We've run out of fields. We're done.
1602 break;
1603 }
1604
Douglas Gregora9add4e2009-02-12 19:00:39 +00001605 // We've already initialized a member of a union. We're done.
1606 if (InitializedSomething && DeclType->isUnionType())
1607 break;
1608
Douglas Gregor91f84212008-12-11 16:49:14 +00001609 // If we've hit the flexible array member at the end, we're done.
1610 if (Field->getType()->isIncompleteArrayType())
1611 break;
1612
Douglas Gregor51695702009-01-29 16:53:55 +00001613 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001614 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001615 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001616 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001617 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001618
Douglas Gregora82064c2011-06-29 21:51:31 +00001619 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001620 bool InvalidUse;
1621 if (VerifyOnly)
David Blaikie40ed2972012-06-06 20:45:41 +00001622 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001623 else
David Blaikie40ed2972012-06-06 20:45:41 +00001624 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001625 IList->getInit(Index)->getLocStart());
1626 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001627 ++Index;
1628 ++Field;
1629 hadError = true;
1630 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001631 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001632
Anders Carlsson6cabf312010-01-23 23:23:01 +00001633 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001634 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001635 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1636 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001637 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001638
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001639 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001640 // Initialize the first field within the union.
David Blaikie40ed2972012-06-06 20:45:41 +00001641 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001642 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001643
1644 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001645 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001646
John McCalle40b58e2010-03-11 19:32:38 +00001647 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001648 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1649 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1650 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001651 // It is possible we have one or more unnamed bitfields remaining.
1652 // Find first (if any) named field and emit warning.
1653 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1654 it != end; ++it) {
Richard Smith852c9db2013-04-20 22:23:05 +00001655 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCalle40b58e2010-03-11 19:32:38 +00001656 SemaRef.Diag(IList->getSourceRange().getEnd(),
Aaron Ballmanb9bb2012014-01-03 14:54:10 +00001657 diag::warn_missing_field_initializers) << *it;
John McCalle40b58e2010-03-11 19:32:38 +00001658 break;
1659 }
1660 }
1661 }
1662
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001663 // Check that any remaining fields can be value-initialized.
1664 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1665 !Field->getType()->isIncompleteArrayType()) {
1666 // FIXME: Should check for holes left by designated initializers too.
1667 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smith852c9db2013-04-20 22:23:05 +00001668 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Richard Smith454a7cd2014-06-03 08:26:00 +00001669 CheckEmptyInitializable(
1670 InitializedEntity::InitializeMember(*Field, &Entity),
1671 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001672 }
1673 }
1674
Mike Stump11289f42009-09-09 15:08:12 +00001675 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001676 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001677 return;
1678
David Blaikie40ed2972012-06-06 20:45:41 +00001679 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00001680 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001681 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001682 ++Index;
1683 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001684 }
1685
Anders Carlsson6cabf312010-01-23 23:23:01 +00001686 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001687 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001688
Anders Carlsson6cabf312010-01-23 23:23:01 +00001689 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001690 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001691 StructuredList, StructuredIndex);
1692 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001693 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001694 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001695}
Steve Narofff8ecff22008-05-01 22:18:59 +00001696
Douglas Gregord5846a12009-04-15 06:41:24 +00001697/// \brief Expand a field designator that refers to a member of an
1698/// anonymous struct or union into a series of field designators that
1699/// refers to the field within the appropriate subobject.
1700///
Douglas Gregord5846a12009-04-15 06:41:24 +00001701static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001702 DesignatedInitExpr *DIE,
1703 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001704 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001705 typedef DesignatedInitExpr::Designator Designator;
1706
Douglas Gregord5846a12009-04-15 06:41:24 +00001707 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001708 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001709 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1710 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1711 if (PI + 1 == PE)
Craig Topperc3ec1492014-05-26 06:22:03 +00001712 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
Douglas Gregord5846a12009-04-15 06:41:24 +00001713 DIE->getDesignator(DesigIdx)->getDotLoc(),
1714 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1715 else
Craig Topperc3ec1492014-05-26 06:22:03 +00001716 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
1717 SourceLocation(), SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001718 assert(isa<FieldDecl>(*PI));
1719 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001720 }
1721
1722 // Expand the current designator into the set of replacement
1723 // designators, so we have a full subobject path down to where the
1724 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001725 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001726 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001727}
Mike Stump11289f42009-09-09 15:08:12 +00001728
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001729/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001730/// corresponds to FieldName.
1731static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1732 IdentifierInfo *FieldName) {
Argyrios Kyrtzidis54b10292012-09-10 22:04:26 +00001733 if (!FieldName)
Craig Topperc3ec1492014-05-26 06:22:03 +00001734 return nullptr;
Argyrios Kyrtzidis54b10292012-09-10 22:04:26 +00001735
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001736 assert(AnonField->isAnonymousStructOrUnion());
1737 Decl *NextDecl = AnonField->getNextDeclInContext();
Aaron Ballman6d1bebb2012-02-09 22:16:56 +00001738 while (IndirectFieldDecl *IF =
1739 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
Argyrios Kyrtzidis54b10292012-09-10 22:04:26 +00001740 if (FieldName == IF->getAnonField()->getIdentifier())
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001741 return IF;
1742 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001743 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001744 return nullptr;
Douglas Gregord5846a12009-04-15 06:41:24 +00001745}
1746
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001747static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1748 DesignatedInitExpr *DIE) {
1749 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1750 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1751 for (unsigned I = 0; I < NumIndexExprs; ++I)
1752 IndexExprs[I] = DIE->getSubExpr(I + 1);
1753 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001754 DIE->size(), IndexExprs,
1755 DIE->getEqualOrColonLoc(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001756 DIE->usesGNUSyntax(), DIE->getInit());
1757}
1758
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001759namespace {
1760
1761// Callback to only accept typo corrections that are for field members of
1762// the given struct or union.
1763class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1764 public:
1765 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1766 : Record(RD) {}
1767
Craig Toppere14c0f82014-03-12 04:55:44 +00001768 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001769 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1770 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1771 }
1772
1773 private:
1774 RecordDecl *Record;
1775};
1776
1777}
1778
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001779/// @brief Check the well-formedness of a C99 designated initializer.
1780///
1781/// Determines whether the designated initializer @p DIE, which
1782/// resides at the given @p Index within the initializer list @p
1783/// IList, is well-formed for a current object of type @p DeclType
1784/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001785/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001786/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001787///
1788/// @param IList The initializer list in which this designated
1789/// initializer occurs.
1790///
Douglas Gregora5324162009-04-15 04:56:10 +00001791/// @param DIE The designated initializer expression.
1792///
1793/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001794///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00001795/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001796/// into which the designation in @p DIE should refer.
1797///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001798/// @param NextField If non-NULL and the first designator in @p DIE is
1799/// a field, this will be set to the field declaration corresponding
1800/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001801///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001802/// @param NextElementIndex If non-NULL and the first designator in @p
1803/// DIE is an array designator or GNU array-range designator, this
1804/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001805///
1806/// @param Index Index into @p IList where the designated initializer
1807/// @p DIE occurs.
1808///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001809/// @param StructuredList The initializer list expression that
1810/// describes all of the subobject initializers in the order they'll
1811/// actually be initialized.
1812///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001813/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001814bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001815InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001816 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001817 DesignatedInitExpr *DIE,
1818 unsigned DesigIdx,
1819 QualType &CurrentObjectType,
1820 RecordDecl::field_iterator *NextField,
1821 llvm::APSInt *NextElementIndex,
1822 unsigned &Index,
1823 InitListExpr *StructuredList,
1824 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001825 bool FinishSubobjectInit,
1826 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001827 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001828 // Check the actual initialization for the designated object type.
1829 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001830
1831 // Temporarily remove the designator expression from the
1832 // initializer list that the child calls see, so that we don't try
1833 // to re-process the designator.
1834 unsigned OldIndex = Index;
1835 IList->setInit(OldIndex, DIE->getInit());
1836
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001837 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001838 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001839
1840 // Restore the designated initializer expression in the syntactic
1841 // form of the initializer list.
1842 if (IList->getInit(OldIndex) != DIE->getInit())
1843 DIE->setInit(IList->getInit(OldIndex));
1844 IList->setInit(OldIndex, DIE);
1845
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001846 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001847 }
1848
Douglas Gregora5324162009-04-15 04:56:10 +00001849 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001850 bool IsFirstDesignator = (DesigIdx == 0);
1851 if (!VerifyOnly) {
1852 assert((IsFirstDesignator || StructuredList) &&
1853 "Need a non-designated initializer list to start from");
1854
1855 // Determine the structural initializer list that corresponds to the
1856 // current subobject.
Benjamin Kramer6b441d62012-02-23 14:48:40 +00001857 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001858 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1859 StructuredList, StructuredIndex,
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001860 SourceRange(D->getLocStart(),
1861 DIE->getLocEnd()));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001862 assert(StructuredList && "Expected a structured initializer list");
1863 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001864
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001865 if (D->isFieldDesignator()) {
1866 // C99 6.7.8p7:
1867 //
1868 // If a designator has the form
1869 //
1870 // . identifier
1871 //
1872 // then the current object (defined below) shall have
1873 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001874 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001875 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001876 if (!RT) {
1877 SourceLocation Loc = D->getDotLoc();
1878 if (Loc.isInvalid())
1879 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001880 if (!VerifyOnly)
1881 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001882 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001883 ++Index;
1884 return true;
1885 }
1886
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001887 // Note: we perform a linear search of the fields here, despite
1888 // the fact that we have a faster lookup method, because we always
1889 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001890 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001891 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001892 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001893 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001894 Field = RT->getDecl()->field_begin(),
1895 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001896 for (; Field != FieldEnd; ++Field) {
1897 if (Field->isUnnamedBitfield())
1898 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001899
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001900 // If we find a field representing an anonymous field, look in the
1901 // IndirectFieldDecl that follow for the designated initializer.
1902 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1903 if (IndirectFieldDecl *IF =
David Blaikie40ed2972012-06-06 20:45:41 +00001904 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001905 // In verify mode, don't modify the original.
1906 if (VerifyOnly)
1907 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001908 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1909 D = DIE->getDesignator(DesigIdx);
1910 break;
1911 }
1912 }
David Blaikie40ed2972012-06-06 20:45:41 +00001913 if (KnownField && KnownField == *Field)
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001914 break;
1915 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001916 break;
1917
1918 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001919 }
1920
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001921 if (Field == FieldEnd) {
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001922 if (VerifyOnly) {
1923 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001924 return true; // No typo correction when just trying this out.
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001925 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001926
Douglas Gregord5846a12009-04-15 06:41:24 +00001927 // There was no normal field in the struct with the designated
1928 // name. Perform another lookup for this name, which may find
1929 // something that we can't designate (e.g., a member function),
1930 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001931 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001932 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Craig Topperc3ec1492014-05-26 06:22:03 +00001933 FieldDecl *ReplacementField = nullptr;
David Blaikieff7d47a2012-12-19 00:45:41 +00001934 if (Lookup.empty()) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001935 // Name lookup didn't find anything. Determine whether this
1936 // was a typo for another field name.
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001937 FieldInitializerValidatorCCC Validator(RT->getDecl());
Richard Smithf9b15102013-08-17 00:46:16 +00001938 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
1939 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Craig Topperc3ec1492014-05-26 06:22:03 +00001940 Sema::LookupMemberName, /*Scope=*/ nullptr, /*SS=*/ nullptr,
1941 Validator, Sema::CTK_ErrorRecovery, RT->getDecl())) {
Richard Smithf9b15102013-08-17 00:46:16 +00001942 SemaRef.diagnoseTypo(
1943 Corrected,
1944 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
1945 << FieldName << CurrentObjectType);
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001946 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001947 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001948 } else {
1949 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1950 << FieldName << CurrentObjectType;
1951 ++Index;
1952 return true;
1953 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001954 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001955
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001956 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001957 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001958 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001959 << FieldName;
David Blaikieff7d47a2012-12-19 00:45:41 +00001960 SemaRef.Diag(Lookup.front()->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001961 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001962 ++Index;
1963 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001964 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001965
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001966 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001967 // The replacement field comes from typo correction; find it
1968 // in the list of fields.
1969 FieldIndex = 0;
1970 Field = RT->getDecl()->field_begin();
1971 for (; Field != FieldEnd; ++Field) {
1972 if (Field->isUnnamedBitfield())
1973 continue;
1974
David Blaikie40ed2972012-06-06 20:45:41 +00001975 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001976 Field->getIdentifier() == ReplacementField->getIdentifier())
1977 break;
1978
1979 ++FieldIndex;
1980 }
1981 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001982 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001983
1984 // All of the fields of a union are located at the same place in
1985 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001986 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001987 FieldIndex = 0;
Matthew Curtis274a9cc2013-10-03 12:14:24 +00001988 if (!VerifyOnly) {
1989 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
1990 if (CurrentField && CurrentField != *Field) {
1991 assert(StructuredList->getNumInits() == 1
1992 && "A union should never have more than one initializer!");
1993
1994 // we're about to throw away an initializer, emit warning
1995 SemaRef.Diag(D->getFieldLoc(),
1996 diag::warn_initializer_overrides)
1997 << D->getSourceRange();
1998 Expr *ExistingInit = StructuredList->getInit(0);
1999 SemaRef.Diag(ExistingInit->getLocStart(),
2000 diag::note_previous_initializer)
2001 << /*FIXME:has side effects=*/0
2002 << ExistingInit->getSourceRange();
2003
2004 // remove existing initializer
2005 StructuredList->resizeInits(SemaRef.Context, 0);
Craig Topperc3ec1492014-05-26 06:22:03 +00002006 StructuredList->setInitializedFieldInUnion(nullptr);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002007 }
2008
David Blaikie40ed2972012-06-06 20:45:41 +00002009 StructuredList->setInitializedFieldInUnion(*Field);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002010 }
Douglas Gregor51695702009-01-29 16:53:55 +00002011 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002012
Douglas Gregora82064c2011-06-29 21:51:31 +00002013 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002014 bool InvalidUse;
2015 if (VerifyOnly)
David Blaikie40ed2972012-06-06 20:45:41 +00002016 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002017 else
David Blaikie40ed2972012-06-06 20:45:41 +00002018 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002019 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00002020 ++Index;
2021 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002022 }
Douglas Gregora82064c2011-06-29 21:51:31 +00002023
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002024 if (!VerifyOnly) {
2025 // Update the designator with the field declaration.
David Blaikie40ed2972012-06-06 20:45:41 +00002026 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00002027
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002028 // Make sure that our non-designated initializer list has space
2029 // for a subobject corresponding to this field.
2030 if (FieldIndex >= StructuredList->getNumInits())
2031 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2032 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002033
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002034 // This designator names a flexible array member.
2035 if (Field->getType()->isIncompleteArrayType()) {
2036 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00002037 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002038 // We can't designate an object within the flexible array
2039 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002040 if (!VerifyOnly) {
2041 DesignatedInitExpr::Designator *NextD
2042 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002043 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002044 diag::err_designator_into_flexible_array_member)
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002045 << SourceRange(NextD->getLocStart(),
2046 DIE->getLocEnd());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002047 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002048 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002049 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002050 Invalid = true;
2051 }
2052
Chris Lattner001b29c2010-10-10 17:49:49 +00002053 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2054 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002055 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002056 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002057 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002058 diag::err_flexible_array_init_needs_braces)
2059 << DIE->getInit()->getSourceRange();
2060 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002061 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002062 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002063 Invalid = true;
2064 }
2065
Eli Friedman3fa64df2011-08-23 22:24:57 +00002066 // Check GNU flexible array initializer.
David Blaikie40ed2972012-06-06 20:45:41 +00002067 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00002068 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002069 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002070
2071 if (Invalid) {
2072 ++Index;
2073 return true;
2074 }
2075
2076 // Initialize the array.
2077 bool prevHadError = hadError;
2078 unsigned newStructuredIndex = FieldIndex;
2079 unsigned OldIndex = Index;
2080 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00002081
2082 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002083 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002084 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002085 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002086
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002087 IList->setInit(OldIndex, DIE);
2088 if (hadError && !prevHadError) {
2089 ++Field;
2090 ++FieldIndex;
2091 if (NextField)
2092 *NextField = Field;
2093 StructuredIndex = FieldIndex;
2094 return true;
2095 }
2096 } else {
2097 // Recurse to check later designated subobjects.
David Blaikie2d7c57e2012-04-30 02:36:29 +00002098 QualType FieldType = Field->getType();
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002099 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002100
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002101 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002102 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002103 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002104 FieldType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002105 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002106 true, false))
2107 return true;
2108 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002109
2110 // Find the position of the next field to be initialized in this
2111 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002112 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002113 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002114
2115 // If this the first designator, our caller will continue checking
2116 // the rest of this struct/class/union subobject.
2117 if (IsFirstDesignator) {
2118 if (NextField)
2119 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002120 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002121 return false;
2122 }
2123
Douglas Gregor17bd0942009-01-28 23:36:17 +00002124 if (!FinishSubobjectInit)
2125 return false;
2126
Douglas Gregord5846a12009-04-15 06:41:24 +00002127 // We've already initialized something in the union; we're done.
2128 if (RT->getDecl()->isUnion())
2129 return hadError;
2130
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002131 // Check the remaining fields within this class/struct/union subobject.
2132 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002133
Anders Carlsson6cabf312010-01-23 23:23:01 +00002134 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002135 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002136 return hadError && !prevHadError;
2137 }
2138
2139 // C99 6.7.8p6:
2140 //
2141 // If a designator has the form
2142 //
2143 // [ constant-expression ]
2144 //
2145 // then the current object (defined below) shall have array
2146 // type and the expression shall be an integer constant
2147 // expression. If the array is of unknown size, any
2148 // nonnegative value is valid.
2149 //
2150 // Additionally, cope with the GNU extension that permits
2151 // designators of the form
2152 //
2153 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00002154 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002155 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002156 if (!VerifyOnly)
2157 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2158 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002159 ++Index;
2160 return true;
2161 }
2162
Craig Topperc3ec1492014-05-26 06:22:03 +00002163 Expr *IndexExpr = nullptr;
Douglas Gregor17bd0942009-01-28 23:36:17 +00002164 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2165 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002166 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00002167 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002168 DesignatedEndIndex = DesignatedStartIndex;
2169 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002170 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00002171
Mike Stump11289f42009-09-09 15:08:12 +00002172 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002173 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002174 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002175 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002176 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002177
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00002178 // Codegen can't handle evaluating array range designators that have side
2179 // effects, because we replicate the AST value for each initialized element.
2180 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2181 // elements with something that has a side effect, so codegen can emit an
2182 // "error unsupported" error instead of miscompiling the app.
2183 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002184 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00002185 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002186 }
2187
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002188 if (isa<ConstantArrayType>(AT)) {
2189 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002190 DesignatedStartIndex
2191 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002192 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00002193 DesignatedEndIndex
2194 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002195 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2196 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00002197 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002198 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002199 diag::err_array_designator_too_large)
2200 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2201 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002202 ++Index;
2203 return true;
2204 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00002205 } else {
2206 // Make sure the bit-widths and signedness match.
2207 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002208 DesignatedEndIndex
2209 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002210 else if (DesignatedStartIndex.getBitWidth() <
2211 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002212 DesignatedStartIndex
2213 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002214 DesignatedStartIndex.setIsUnsigned(true);
2215 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002216 }
Mike Stump11289f42009-09-09 15:08:12 +00002217
Eli Friedman1f16b742013-06-11 21:48:11 +00002218 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2219 // We're modifying a string literal init; we have to decompose the string
2220 // so we can modify the individual characters.
2221 ASTContext &Context = SemaRef.Context;
2222 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2223
2224 // Compute the character type
2225 QualType CharTy = AT->getElementType();
2226
2227 // Compute the type of the integer literals.
2228 QualType PromotedCharTy = CharTy;
2229 if (CharTy->isPromotableIntegerType())
2230 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2231 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2232
2233 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2234 // Get the length of the string.
2235 uint64_t StrLen = SL->getLength();
2236 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2237 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2238 StructuredList->resizeInits(Context, StrLen);
2239
2240 // Build a literal for each character in the string, and put them into
2241 // the init list.
2242 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2243 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2244 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002245 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002246 if (CharTy != PromotedCharTy)
2247 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002248 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002249 StructuredList->updateInit(Context, i, Init);
2250 }
2251 } else {
2252 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2253 std::string Str;
2254 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2255
2256 // Get the length of the string.
2257 uint64_t StrLen = Str.size();
2258 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2259 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2260 StructuredList->resizeInits(Context, StrLen);
2261
2262 // Build a literal for each character in the string, and put them into
2263 // the init list.
2264 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2265 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2266 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002267 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002268 if (CharTy != PromotedCharTy)
2269 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002270 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002271 StructuredList->updateInit(Context, i, Init);
2272 }
2273 }
2274 }
2275
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002276 // Make sure that our non-designated initializer list has space
2277 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002278 if (!VerifyOnly &&
2279 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00002280 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00002281 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002282
Douglas Gregor17bd0942009-01-28 23:36:17 +00002283 // Repeatedly perform subobject initializations in the range
2284 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002285
Douglas Gregor17bd0942009-01-28 23:36:17 +00002286 // Move to the next designator
2287 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2288 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002289
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002290 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00002291 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002292
Douglas Gregor17bd0942009-01-28 23:36:17 +00002293 while (DesignatedStartIndex <= DesignatedEndIndex) {
2294 // Recurse to check later designated subobjects.
2295 QualType ElementType = AT->getElementType();
2296 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002297
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002298 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002299 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002300 ElementType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002301 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002302 (DesignatedStartIndex == DesignatedEndIndex),
2303 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002304 return true;
2305
2306 // Move to the next index in the array that we'll be initializing.
2307 ++DesignatedStartIndex;
2308 ElementIndex = DesignatedStartIndex.getZExtValue();
2309 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002310
2311 // If this the first designator, our caller will continue checking
2312 // the rest of this array subobject.
2313 if (IsFirstDesignator) {
2314 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002315 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002316 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002317 return false;
2318 }
Mike Stump11289f42009-09-09 15:08:12 +00002319
Douglas Gregor17bd0942009-01-28 23:36:17 +00002320 if (!FinishSubobjectInit)
2321 return false;
2322
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002323 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002324 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002325 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002326 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002327 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002328 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002329}
2330
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002331// Get the structured initializer list for a subobject of type
2332// @p CurrentObjectType.
2333InitListExpr *
2334InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2335 QualType CurrentObjectType,
2336 InitListExpr *StructuredList,
2337 unsigned StructuredIndex,
2338 SourceRange InitRange) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002339 if (VerifyOnly)
Craig Topperc3ec1492014-05-26 06:22:03 +00002340 return nullptr; // No structured list in verification-only mode.
2341 Expr *ExistingInit = nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002342 if (!StructuredList)
Benjamin Kramer6b441d62012-02-23 14:48:40 +00002343 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002344 else if (StructuredIndex < StructuredList->getNumInits())
2345 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002346
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002347 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2348 return Result;
2349
2350 if (ExistingInit) {
2351 // We are creating an initializer list that initializes the
2352 // subobjects of the current object, but there was already an
2353 // initialization that completely initialized the current
2354 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002355 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002356 // struct X { int a, b; };
2357 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002358 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002359 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2360 // designated initializer re-initializes the whole
2361 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002362 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002363 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002364 << InitRange;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002365 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002366 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002367 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002368 << ExistingInit->getSourceRange();
2369 }
2370
Mike Stump11289f42009-09-09 15:08:12 +00002371 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002372 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko78852e92013-05-05 20:40:26 +00002373 InitRange.getBegin(), None,
Ted Kremenek013041e2010-02-19 01:50:18 +00002374 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002375
Eli Friedman91f5ae52012-02-23 02:25:10 +00002376 QualType ResultType = CurrentObjectType;
2377 if (!ResultType->isArrayType())
2378 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2379 Result->setType(ResultType);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002380
Douglas Gregor6d00c992009-03-20 23:58:33 +00002381 // Pre-allocate storage for the structured initializer list.
2382 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002383 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002384 bool GotNumInits = false;
2385 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002386 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002387 GotNumInits = true;
2388 } else if (Index < IList->getNumInits()) {
2389 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002390 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002391 GotNumInits = true;
2392 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002393 }
2394
Mike Stump11289f42009-09-09 15:08:12 +00002395 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002396 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2397 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2398 NumElements = CAType->getSize().getZExtValue();
2399 // Simple heuristic so that we don't allocate a very large
2400 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002401 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002402 NumElements = 0;
2403 }
John McCall9dd450b2009-09-21 23:43:11 +00002404 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002405 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002406 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002407 RecordDecl *RDecl = RType->getDecl();
2408 if (RDecl->isUnion())
2409 NumElements = 1;
2410 else
Aaron Ballman62e47c42014-03-10 13:43:55 +00002411 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002412 }
2413
Ted Kremenekac034612010-04-13 23:39:13 +00002414 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002415
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002416 // Link this new initializer list into the structured initializer
2417 // lists.
2418 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002419 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002420 else {
2421 Result->setSyntacticForm(IList);
2422 SyntacticToSemantic[IList] = Result;
2423 }
2424
2425 return Result;
2426}
2427
2428/// Update the initializer at index @p StructuredIndex within the
2429/// structured initializer list to the value @p expr.
2430void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2431 unsigned &StructuredIndex,
2432 Expr *expr) {
2433 // No structured initializer list to update
2434 if (!StructuredList)
2435 return;
2436
Ted Kremenekac034612010-04-13 23:39:13 +00002437 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2438 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002439 // This initializer overwrites a previous initializer. Warn.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002440 SemaRef.Diag(expr->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002441 diag::warn_initializer_overrides)
2442 << expr->getSourceRange();
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002443 SemaRef.Diag(PrevInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002444 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002445 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002446 << PrevInit->getSourceRange();
2447 }
Mike Stump11289f42009-09-09 15:08:12 +00002448
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002449 ++StructuredIndex;
2450}
2451
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002452/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002453/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002454/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002455/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002456/// failure. Returns the index expression, possibly with an implicit cast
2457/// added, on success. If everything went okay, Value will receive the
2458/// value of the constant expression.
2459static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002460CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002461 SourceLocation Loc = Index->getLocStart();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002462
2463 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002464 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2465 if (Result.isInvalid())
2466 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002467
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002468 if (Value.isSigned() && Value.isNegative())
2469 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002470 << Value.toString(10) << Index->getSourceRange();
2471
Douglas Gregor51650d32009-01-23 21:04:18 +00002472 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002473 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002474}
2475
John McCalldadc5752010-08-24 06:29:42 +00002476ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002477 SourceLocation Loc,
2478 bool GNUSyntax,
2479 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002480 typedef DesignatedInitExpr::Designator ASTDesignator;
2481
2482 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002483 SmallVector<ASTDesignator, 32> Designators;
2484 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002485
2486 // Build designators and check array designator expressions.
2487 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2488 const Designator &D = Desig.getDesignator(Idx);
2489 switch (D.getKind()) {
2490 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002491 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002492 D.getFieldLoc()));
2493 break;
2494
2495 case Designator::ArrayDesignator: {
2496 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2497 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00002498 if (!Index->isTypeDependent() && !Index->isValueDependent())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002499 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002500 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002501 Invalid = true;
2502 else {
2503 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002504 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002505 D.getRBracketLoc()));
2506 InitExpressions.push_back(Index);
2507 }
2508 break;
2509 }
2510
2511 case Designator::ArrayRangeDesignator: {
2512 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2513 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2514 llvm::APSInt StartValue;
2515 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002516 bool StartDependent = StartIndex->isTypeDependent() ||
2517 StartIndex->isValueDependent();
2518 bool EndDependent = EndIndex->isTypeDependent() ||
2519 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00002520 if (!StartDependent)
2521 StartIndex =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002522 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002523 if (!EndDependent)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002524 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002525
2526 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002527 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002528 else {
2529 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002530 if (StartDependent || EndDependent) {
2531 // Nothing to compute.
2532 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002533 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002534 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002535 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002536
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002537 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002538 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002539 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002540 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2541 Invalid = true;
2542 } else {
2543 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002544 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002545 D.getEllipsisLoc(),
2546 D.getRBracketLoc()));
2547 InitExpressions.push_back(StartIndex);
2548 InitExpressions.push_back(EndIndex);
2549 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002550 }
2551 break;
2552 }
2553 }
2554 }
2555
2556 if (Invalid || Init.isInvalid())
2557 return ExprError();
2558
2559 // Clear out the expressions within the designation.
2560 Desig.ClearExprs(*this);
2561
2562 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002563 = DesignatedInitExpr::Create(Context,
2564 Designators.data(), Designators.size(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00002565 InitExpressions, Loc, GNUSyntax,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002566 Init.getAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002567
David Blaikiebbafb8a2012-03-11 07:00:24 +00002568 if (!getLangOpts().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002569 Diag(DIE->getLocStart(), diag::ext_designated_init)
2570 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002571
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002572 return DIE;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002573}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002574
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002575//===----------------------------------------------------------------------===//
2576// Initialization entity
2577//===----------------------------------------------------------------------===//
2578
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002579InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002580 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002581 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002582{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002583 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2584 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002585 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002586 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002587 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002588 Type = VT->getElementType();
2589 } else {
2590 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2591 assert(CT && "Unexpected type");
2592 Kind = EK_ComplexElement;
2593 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002594 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002595}
2596
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002597InitializedEntity
2598InitializedEntity::InitializeBase(ASTContext &Context,
2599 const CXXBaseSpecifier *Base,
2600 bool IsInheritedVirtualBase) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002601 InitializedEntity Result;
2602 Result.Kind = EK_Base;
Craig Topperc3ec1492014-05-26 06:22:03 +00002603 Result.Parent = nullptr;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002604 Result.Base = reinterpret_cast<uintptr_t>(Base);
2605 if (IsInheritedVirtualBase)
2606 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002607
Douglas Gregor1b303932009-12-22 15:35:07 +00002608 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002609 return Result;
2610}
2611
Douglas Gregor85dabae2009-12-16 01:38:02 +00002612DeclarationName InitializedEntity::getName() const {
2613 switch (getKind()) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002614 case EK_Parameter:
2615 case EK_Parameter_CF_Audited: {
John McCall31168b02011-06-15 23:02:42 +00002616 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2617 return (D ? D->getDeclName() : DeclarationName());
2618 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002619
2620 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002621 case EK_Member:
2622 return VariableOrMember->getDeclName();
2623
Douglas Gregor19666fb2012-02-15 16:57:26 +00002624 case EK_LambdaCapture:
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00002625 return DeclarationName(Capture.VarID);
Douglas Gregor19666fb2012-02-15 16:57:26 +00002626
Douglas Gregor85dabae2009-12-16 01:38:02 +00002627 case EK_Result:
2628 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002629 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002630 case EK_Temporary:
2631 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002632 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002633 case EK_ArrayElement:
2634 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002635 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002636 case EK_BlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002637 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002638 case EK_RelatedResult:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002639 return DeclarationName();
2640 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002641
David Blaikie8a40f702012-01-17 06:56:22 +00002642 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00002643}
2644
Douglas Gregora4b592a2009-12-19 03:01:41 +00002645DeclaratorDecl *InitializedEntity::getDecl() const {
2646 switch (getKind()) {
2647 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002648 case EK_Member:
2649 return VariableOrMember;
2650
John McCall31168b02011-06-15 23:02:42 +00002651 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002652 case EK_Parameter_CF_Audited:
John McCall31168b02011-06-15 23:02:42 +00002653 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2654
Douglas Gregora4b592a2009-12-19 03:01:41 +00002655 case EK_Result:
2656 case EK_Exception:
2657 case EK_New:
2658 case EK_Temporary:
2659 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002660 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002661 case EK_ArrayElement:
2662 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002663 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002664 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002665 case EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002666 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002667 case EK_RelatedResult:
Craig Topperc3ec1492014-05-26 06:22:03 +00002668 return nullptr;
Douglas Gregora4b592a2009-12-19 03:01:41 +00002669 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002670
David Blaikie8a40f702012-01-17 06:56:22 +00002671 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00002672}
2673
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002674bool InitializedEntity::allowsNRVO() const {
2675 switch (getKind()) {
2676 case EK_Result:
2677 case EK_Exception:
2678 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002679
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002680 case EK_Variable:
2681 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002682 case EK_Parameter_CF_Audited:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002683 case EK_Member:
2684 case EK_New:
2685 case EK_Temporary:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002686 case EK_CompoundLiteralInit:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002687 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002688 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002689 case EK_ArrayElement:
2690 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002691 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002692 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002693 case EK_LambdaCapture:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002694 case EK_RelatedResult:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002695 break;
2696 }
2697
2698 return false;
2699}
2700
Richard Smithe6c01442013-06-05 00:46:14 +00002701unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
Richard Smithe3b28bc2013-06-12 21:51:50 +00002702 assert(getParent() != this);
Richard Smithe6c01442013-06-05 00:46:14 +00002703 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
2704 for (unsigned I = 0; I != Depth; ++I)
2705 OS << "`-";
2706
2707 switch (getKind()) {
2708 case EK_Variable: OS << "Variable"; break;
2709 case EK_Parameter: OS << "Parameter"; break;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002710 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
2711 break;
Richard Smithe6c01442013-06-05 00:46:14 +00002712 case EK_Result: OS << "Result"; break;
2713 case EK_Exception: OS << "Exception"; break;
2714 case EK_Member: OS << "Member"; break;
2715 case EK_New: OS << "New"; break;
2716 case EK_Temporary: OS << "Temporary"; break;
2717 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002718 case EK_RelatedResult: OS << "RelatedResult"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00002719 case EK_Base: OS << "Base"; break;
2720 case EK_Delegating: OS << "Delegating"; break;
2721 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
2722 case EK_VectorElement: OS << "VectorElement " << Index; break;
2723 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
2724 case EK_BlockElement: OS << "Block"; break;
2725 case EK_LambdaCapture:
2726 OS << "LambdaCapture ";
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00002727 OS << DeclarationName(Capture.VarID);
Richard Smithe6c01442013-06-05 00:46:14 +00002728 break;
2729 }
2730
2731 if (Decl *D = getDecl()) {
2732 OS << " ";
2733 cast<NamedDecl>(D)->printQualifiedName(OS);
2734 }
2735
2736 OS << " '" << getType().getAsString() << "'\n";
2737
2738 return Depth + 1;
2739}
2740
2741void InitializedEntity::dump() const {
2742 dumpImpl(llvm::errs());
2743}
2744
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002745//===----------------------------------------------------------------------===//
2746// Initialization sequence
2747//===----------------------------------------------------------------------===//
2748
2749void InitializationSequence::Step::Destroy() {
2750 switch (Kind) {
2751 case SK_ResolveAddressOfOverloadedFunction:
2752 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002753 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002754 case SK_CastDerivedToBaseLValue:
2755 case SK_BindReference:
2756 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002757 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002758 case SK_UserConversion:
2759 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002760 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002761 case SK_QualificationConversionLValue:
Jordan Roseb1312a52013-04-11 00:58:58 +00002762 case SK_LValueToRValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002763 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002764 case SK_ListConstructorCall:
Sebastian Redl29526f02011-11-27 16:50:07 +00002765 case SK_UnwrapInitList:
2766 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002767 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002768 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002769 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002770 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002771 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002772 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00002773 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002774 case SK_PassByIndirectCopyRestore:
2775 case SK_PassByIndirectRestore:
2776 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00002777 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00002778 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00002779 case SK_OCLZeroEvent:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002780 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002781
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002782 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00002783 case SK_ConversionSequenceNoNarrowing:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002784 delete ICS;
2785 }
2786}
2787
Douglas Gregor838fcc32010-03-26 20:14:36 +00002788bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002789 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002790}
2791
2792bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002793 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002794 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002795
Douglas Gregor838fcc32010-03-26 20:14:36 +00002796 switch (getFailureKind()) {
2797 case FK_TooManyInitsForReference:
2798 case FK_ArrayNeedsInitList:
2799 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00002800 case FK_ArrayNeedsInitListOrWideStringLiteral:
2801 case FK_NarrowStringIntoWideCharArray:
2802 case FK_WideStringIntoCharArray:
2803 case FK_IncompatWideStringIntoWideChar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002804 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2805 case FK_NonConstLValueReferenceBindingToTemporary:
2806 case FK_NonConstLValueReferenceBindingToUnrelated:
2807 case FK_RValueReferenceBindingToLValue:
2808 case FK_ReferenceInitDropsQualifiers:
2809 case FK_ReferenceInitFailed:
2810 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002811 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002812 case FK_TooManyInitsForScalar:
2813 case FK_ReferenceBindingToInitList:
2814 case FK_InitListBadDestinationType:
2815 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002816 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002817 case FK_ArrayTypeMismatch:
2818 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002819 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00002820 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00002821 case FK_PlaceholderType:
Sebastian Redl048a6d72012-04-01 19:54:59 +00002822 case FK_ExplicitConstructor:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002823 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002824
Douglas Gregor838fcc32010-03-26 20:14:36 +00002825 case FK_ReferenceInitOverloadFailed:
2826 case FK_UserConversionOverloadFailed:
2827 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002828 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002829 return FailedOverloadResult == OR_Ambiguous;
2830 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002831
David Blaikie8a40f702012-01-17 06:56:22 +00002832 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00002833}
2834
Douglas Gregorb33eed02010-04-16 22:09:46 +00002835bool InitializationSequence::isConstructorInitialization() const {
2836 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2837}
2838
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002839void
2840InitializationSequence
2841::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2842 DeclAccessPair Found,
2843 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002844 Step S;
2845 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2846 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002847 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002848 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002849 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002850 Steps.push_back(S);
2851}
2852
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002853void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002854 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002855 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002856 switch (VK) {
2857 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2858 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2859 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002860 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002861 S.Type = BaseType;
2862 Steps.push_back(S);
2863}
2864
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002865void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002866 bool BindingTemporary) {
2867 Step S;
2868 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2869 S.Type = T;
2870 Steps.push_back(S);
2871}
2872
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002873void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2874 Step S;
2875 S.Kind = SK_ExtraneousCopyToTemporary;
2876 S.Type = T;
2877 Steps.push_back(S);
2878}
2879
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002880void
2881InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2882 DeclAccessPair FoundDecl,
2883 QualType T,
2884 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002885 Step S;
2886 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002887 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002888 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002889 S.Function.Function = Function;
2890 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002891 Steps.push_back(S);
2892}
2893
2894void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002895 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002896 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002897 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002898 switch (VK) {
2899 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002900 S.Kind = SK_QualificationConversionRValue;
2901 break;
John McCall2536c6d2010-08-25 10:28:54 +00002902 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002903 S.Kind = SK_QualificationConversionXValue;
2904 break;
John McCall2536c6d2010-08-25 10:28:54 +00002905 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002906 S.Kind = SK_QualificationConversionLValue;
2907 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002908 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002909 S.Type = Ty;
2910 Steps.push_back(S);
2911}
2912
Jordan Roseb1312a52013-04-11 00:58:58 +00002913void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2914 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2915
2916 Step S;
2917 S.Kind = SK_LValueToRValue;
2918 S.Type = Ty;
2919 Steps.push_back(S);
2920}
2921
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002922void InitializationSequence::AddConversionSequenceStep(
Richard Smithaaa0ec42013-09-21 21:19:19 +00002923 const ImplicitConversionSequence &ICS, QualType T,
2924 bool TopLevelOfInitList) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002925 Step S;
Richard Smithaaa0ec42013-09-21 21:19:19 +00002926 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
2927 : SK_ConversionSequence;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002928 S.Type = T;
2929 S.ICS = new ImplicitConversionSequence(ICS);
2930 Steps.push_back(S);
2931}
2932
Douglas Gregor51e77d52009-12-10 17:56:55 +00002933void InitializationSequence::AddListInitializationStep(QualType T) {
2934 Step S;
2935 S.Kind = SK_ListInitialization;
2936 S.Type = T;
2937 Steps.push_back(S);
2938}
2939
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002940void
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002941InitializationSequence
2942::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2943 AccessSpecifier Access,
2944 QualType T,
Sebastian Redled2e5322011-12-22 14:44:04 +00002945 bool HadMultipleCandidates,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002946 bool FromInitList, bool AsInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002947 Step S;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002948 S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2949 : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002950 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002951 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002952 S.Function.Function = Constructor;
2953 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002954 Steps.push_back(S);
2955}
2956
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002957void InitializationSequence::AddZeroInitializationStep(QualType T) {
2958 Step S;
2959 S.Kind = SK_ZeroInitialization;
2960 S.Type = T;
2961 Steps.push_back(S);
2962}
2963
Douglas Gregore1314a62009-12-18 05:02:21 +00002964void InitializationSequence::AddCAssignmentStep(QualType T) {
2965 Step S;
2966 S.Kind = SK_CAssignment;
2967 S.Type = T;
2968 Steps.push_back(S);
2969}
2970
Eli Friedman78275202009-12-19 08:11:05 +00002971void InitializationSequence::AddStringInitStep(QualType T) {
2972 Step S;
2973 S.Kind = SK_StringInit;
2974 S.Type = T;
2975 Steps.push_back(S);
2976}
2977
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002978void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2979 Step S;
2980 S.Kind = SK_ObjCObjectConversion;
2981 S.Type = T;
2982 Steps.push_back(S);
2983}
2984
Douglas Gregore2f943b2011-02-22 18:29:51 +00002985void InitializationSequence::AddArrayInitStep(QualType T) {
2986 Step S;
2987 S.Kind = SK_ArrayInit;
2988 S.Type = T;
2989 Steps.push_back(S);
2990}
2991
Richard Smithebeed412012-02-15 22:38:09 +00002992void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2993 Step S;
2994 S.Kind = SK_ParenthesizedArrayInit;
2995 S.Type = T;
2996 Steps.push_back(S);
2997}
2998
John McCall31168b02011-06-15 23:02:42 +00002999void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3000 bool shouldCopy) {
3001 Step s;
3002 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3003 : SK_PassByIndirectRestore);
3004 s.Type = type;
3005 Steps.push_back(s);
3006}
3007
3008void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3009 Step S;
3010 S.Kind = SK_ProduceObjCObject;
3011 S.Type = T;
3012 Steps.push_back(S);
3013}
3014
Sebastian Redlc1839b12012-01-17 22:49:42 +00003015void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3016 Step S;
3017 S.Kind = SK_StdInitializerList;
3018 S.Type = T;
3019 Steps.push_back(S);
3020}
3021
Guy Benyei61054192013-02-07 10:55:47 +00003022void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3023 Step S;
3024 S.Kind = SK_OCLSamplerInit;
3025 S.Type = T;
3026 Steps.push_back(S);
3027}
3028
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003029void InitializationSequence::AddOCLZeroEventStep(QualType T) {
3030 Step S;
3031 S.Kind = SK_OCLZeroEvent;
3032 S.Type = T;
3033 Steps.push_back(S);
3034}
3035
Sebastian Redl29526f02011-11-27 16:50:07 +00003036void InitializationSequence::RewrapReferenceInitList(QualType T,
3037 InitListExpr *Syntactic) {
3038 assert(Syntactic->getNumInits() == 1 &&
3039 "Can only rewrap trivial init lists.");
3040 Step S;
3041 S.Kind = SK_UnwrapInitList;
3042 S.Type = Syntactic->getInit(0)->getType();
3043 Steps.insert(Steps.begin(), S);
3044
3045 S.Kind = SK_RewrapInitList;
3046 S.Type = T;
3047 S.WrappingSyntacticList = Syntactic;
3048 Steps.push_back(S);
3049}
3050
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003051void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003052 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00003053 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003054 this->Failure = Failure;
3055 this->FailedOverloadResult = Result;
3056}
3057
3058//===----------------------------------------------------------------------===//
3059// Attempt initialization
3060//===----------------------------------------------------------------------===//
3061
John McCall31168b02011-06-15 23:02:42 +00003062static void MaybeProduceObjCObject(Sema &S,
3063 InitializationSequence &Sequence,
3064 const InitializedEntity &Entity) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003065 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCall31168b02011-06-15 23:02:42 +00003066
3067 /// When initializing a parameter, produce the value if it's marked
3068 /// __attribute__((ns_consumed)).
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003069 if (Entity.isParameterKind()) {
John McCall31168b02011-06-15 23:02:42 +00003070 if (!Entity.isParameterConsumed())
3071 return;
3072
3073 assert(Entity.getType()->isObjCRetainableType() &&
3074 "consuming an object of unretainable type?");
3075 Sequence.AddProduceObjCObjectStep(Entity.getType());
3076
3077 /// When initializing a return value, if the return type is a
3078 /// retainable type, then returns need to immediately retain the
3079 /// object. If an autorelease is required, it will be done at the
3080 /// last instant.
3081 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
3082 if (!Entity.getType()->isObjCRetainableType())
3083 return;
3084
3085 Sequence.AddProduceObjCObjectStep(Entity.getType());
3086 }
3087}
3088
Richard Smithcc1b96d2013-06-12 22:31:48 +00003089static void TryListInitialization(Sema &S,
3090 const InitializedEntity &Entity,
3091 const InitializationKind &Kind,
3092 InitListExpr *InitList,
3093 InitializationSequence &Sequence);
3094
Richard Smithd86812d2012-07-05 08:39:21 +00003095/// \brief When initializing from init list via constructor, handle
3096/// initialization of an object of type std::initializer_list<T>.
Sebastian Redled2e5322011-12-22 14:44:04 +00003097///
Richard Smithd86812d2012-07-05 08:39:21 +00003098/// \return true if we have handled initialization of an object of type
3099/// std::initializer_list<T>, false otherwise.
3100static bool TryInitializerListConstruction(Sema &S,
3101 InitListExpr *List,
3102 QualType DestType,
3103 InitializationSequence &Sequence) {
3104 QualType E;
3105 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1bfe0682012-02-14 21:14:13 +00003106 return false;
3107
Richard Smithcc1b96d2013-06-12 22:31:48 +00003108 if (S.RequireCompleteType(List->getExprLoc(), E, 0)) {
3109 Sequence.setIncompleteTypeFailure(E);
3110 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003111 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00003112
3113 // Try initializing a temporary array from the init list.
3114 QualType ArrayType = S.Context.getConstantArrayType(
3115 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3116 List->getNumInits()),
3117 clang::ArrayType::Normal, 0);
3118 InitializedEntity HiddenArray =
3119 InitializedEntity::InitializeTemporary(ArrayType);
3120 InitializationKind Kind =
3121 InitializationKind::CreateDirectList(List->getExprLoc());
3122 TryListInitialization(S, HiddenArray, Kind, List, Sequence);
3123 if (Sequence)
3124 Sequence.AddStdInitializerListConstructionStep(DestType);
Richard Smithd86812d2012-07-05 08:39:21 +00003125 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003126}
3127
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003128static OverloadingResult
3129ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003130 MultiExprArg Args,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003131 OverloadCandidateSet &CandidateSet,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003132 ArrayRef<NamedDecl *> Ctors,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003133 OverloadCandidateSet::iterator &Best,
3134 bool CopyInitializing, bool AllowExplicit,
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003135 bool OnlyListConstructors, bool InitListSyntax) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003136 CandidateSet.clear();
3137
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003138 for (ArrayRef<NamedDecl *>::iterator
3139 Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003140 NamedDecl *D = *Con;
3141 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3142 bool SuppressUserConversions = false;
3143
3144 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003145 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003146 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3147 if (ConstructorTmpl)
3148 Constructor = cast<CXXConstructorDecl>(
3149 ConstructorTmpl->getTemplatedDecl());
3150 else {
3151 Constructor = cast<CXXConstructorDecl>(D);
3152
Richard Smith6c6ddab2013-09-21 21:23:47 +00003153 // C++11 [over.best.ics]p4:
3154 // However, when considering the argument of a constructor or
3155 // user-defined conversion function that is a candidate:
3156 // -- by 13.3.1.3 when invoked for the copying/moving of a temporary
3157 // in the second step of a class copy-initialization,
3158 // -- by 13.3.1.7 when passing the initializer list as a single
3159 // argument or when the initializer list has exactly one elementand
3160 // a conversion to some class X or reference to (possibly
3161 // cv-qualified) X is considered for the first parameter of a
3162 // constructor of X, or
3163 // -- by 13.3.1.4, 13.3.1.5, or 13.3.1.6 in all cases,
3164 // only standard conversion sequences and ellipsis conversion sequences
3165 // are considered.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003166 if ((CopyInitializing || (InitListSyntax && Args.size() == 1)) &&
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003167 Constructor->isCopyOrMoveConstructor())
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003168 SuppressUserConversions = true;
3169 }
3170
3171 if (!Constructor->isInvalidDecl() &&
3172 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003173 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003174 if (ConstructorTmpl)
3175 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003176 /*ExplicitArgs*/ nullptr, Args,
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003177 CandidateSet, SuppressUserConversions);
Douglas Gregor6073dca2012-02-24 23:56:31 +00003178 else {
3179 // C++ [over.match.copy]p1:
3180 // - When initializing a temporary to be bound to the first parameter
3181 // of a constructor that takes a reference to possibly cv-qualified
3182 // T as its first argument, called with a single argument in the
3183 // context of direct-initialization, explicit conversion functions
3184 // are also considered.
3185 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003186 Args.size() == 1 &&
Douglas Gregor6073dca2012-02-24 23:56:31 +00003187 Constructor->isCopyOrMoveConstructor();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003188 S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003189 SuppressUserConversions,
3190 /*PartialOverloading=*/false,
3191 /*AllowExplicit=*/AllowExplicitConv);
3192 }
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003193 }
3194 }
3195
3196 // Perform overload resolution and return the result.
3197 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3198}
3199
Sebastian Redled2e5322011-12-22 14:44:04 +00003200/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3201/// enumerates the constructors of the initialized entity and performs overload
3202/// resolution to select the best.
Sebastian Redl88e4d492012-02-04 21:27:33 +00003203/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redled2e5322011-12-22 14:44:04 +00003204/// class type.
3205static void TryConstructorInitialization(Sema &S,
3206 const InitializedEntity &Entity,
3207 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003208 MultiExprArg Args, QualType DestType,
Sebastian Redled2e5322011-12-22 14:44:04 +00003209 InitializationSequence &Sequence,
Sebastian Redl88e4d492012-02-04 21:27:33 +00003210 bool InitListSyntax = false) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003211 assert((!InitListSyntax || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
Sebastian Redl88e4d492012-02-04 21:27:33 +00003212 "InitListSyntax must come with a single initializer list argument.");
3213
Sebastian Redled2e5322011-12-22 14:44:04 +00003214 // The type we're constructing needs to be complete.
3215 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003216 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003217 return;
Sebastian Redled2e5322011-12-22 14:44:04 +00003218 }
3219
3220 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3221 assert(DestRecordType && "Constructor initialization requires record type");
3222 CXXRecordDecl *DestRecordDecl
3223 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3224
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003225 // Build the candidate set directly in the initialization sequence
3226 // structure, so that it will persist if we fail.
3227 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3228
3229 // Determine whether we are allowed to call explicit constructors or
3230 // explicit conversion operators.
Sebastian Redl048a6d72012-04-01 19:54:59 +00003231 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003232 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003233
Sebastian Redled2e5322011-12-22 14:44:04 +00003234 // - Otherwise, if T is a class type, constructors are considered. The
3235 // applicable constructors are enumerated, and the best one is chosen
3236 // through overload resolution.
David Blaikieff7d47a2012-12-19 00:45:41 +00003237 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003238 // The container holding the constructors can under certain conditions
3239 // be changed while iterating (e.g. because of deserialization).
3240 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00003241 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Sebastian Redled2e5322011-12-22 14:44:04 +00003242
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003243 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redled2e5322011-12-22 14:44:04 +00003244 OverloadCandidateSet::iterator Best;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003245 bool AsInitializerList = false;
3246
3247 // C++11 [over.match.list]p1:
3248 // When objects of non-aggregate type T are list-initialized, overload
3249 // resolution selects the constructor in two phases:
3250 // - Initially, the candidate functions are the initializer-list
3251 // constructors of the class T and the argument list consists of the
3252 // initializer list as a single argument.
3253 if (InitListSyntax) {
Richard Smithd86812d2012-07-05 08:39:21 +00003254 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003255 AsInitializerList = true;
Richard Smithd86812d2012-07-05 08:39:21 +00003256
3257 // If the initializer list has no elements and T has a default constructor,
3258 // the first phase is omitted.
Richard Smith2be35f52012-12-01 02:35:44 +00003259 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003260 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003261 CandidateSet, Ctors, Best,
Richard Smithd86812d2012-07-05 08:39:21 +00003262 CopyInitialization, AllowExplicit,
3263 /*OnlyListConstructor=*/true,
3264 InitListSyntax);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003265
3266 // Time to unwrap the init list.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003267 Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003268 }
3269
3270 // C++11 [over.match.list]p1:
3271 // - If no viable initializer-list constructor is found, overload resolution
3272 // is performed again, where the candidate functions are all the
Richard Smithd86812d2012-07-05 08:39:21 +00003273 // constructors of the class T and the argument list consists of the
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003274 // elements of the initializer list.
3275 if (Result == OR_No_Viable_Function) {
3276 AsInitializerList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003277 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003278 CandidateSet, Ctors, Best,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003279 CopyInitialization, AllowExplicit,
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003280 /*OnlyListConstructors=*/false,
3281 InitListSyntax);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003282 }
3283 if (Result) {
Sebastian Redl88e4d492012-02-04 21:27:33 +00003284 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003285 InitializationSequence::FK_ListConstructorOverloadFailed :
3286 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00003287 Result);
3288 return;
3289 }
3290
Richard Smithd86812d2012-07-05 08:39:21 +00003291 // C++11 [dcl.init]p6:
Sebastian Redled2e5322011-12-22 14:44:04 +00003292 // If a program calls for the default initialization of an object
3293 // of a const-qualified type T, T shall be a class type with a
3294 // user-provided default constructor.
3295 if (Kind.getKind() == InitializationKind::IK_Default &&
3296 Entity.getType().isConstQualified() &&
Aaron Ballman899b9c62012-07-31 22:40:31 +00003297 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
Sebastian Redled2e5322011-12-22 14:44:04 +00003298 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3299 return;
3300 }
3301
Sebastian Redl048a6d72012-04-01 19:54:59 +00003302 // C++11 [over.match.list]p1:
3303 // In copy-list-initialization, if an explicit constructor is chosen, the
3304 // initializer is ill-formed.
3305 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3306 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3307 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3308 return;
3309 }
3310
Sebastian Redled2e5322011-12-22 14:44:04 +00003311 // Add the constructor initialization step. Any cv-qualification conversion is
3312 // subsumed by the initialization.
3313 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Sebastian Redled2e5322011-12-22 14:44:04 +00003314 Sequence.AddConstructorInitializationStep(CtorDecl,
3315 Best->FoundDecl.getAccess(),
3316 DestType, HadMultipleCandidates,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003317 InitListSyntax, AsInitializerList);
Sebastian Redled2e5322011-12-22 14:44:04 +00003318}
3319
Sebastian Redl29526f02011-11-27 16:50:07 +00003320static bool
3321ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3322 Expr *Initializer,
3323 QualType &SourceType,
3324 QualType &UnqualifiedSourceType,
3325 QualType UnqualifiedTargetType,
3326 InitializationSequence &Sequence) {
3327 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3328 S.Context.OverloadTy) {
3329 DeclAccessPair Found;
3330 bool HadMultipleCandidates = false;
3331 if (FunctionDecl *Fn
3332 = S.ResolveAddressOfOverloadedFunction(Initializer,
3333 UnqualifiedTargetType,
3334 false, Found,
3335 &HadMultipleCandidates)) {
3336 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3337 HadMultipleCandidates);
3338 SourceType = Fn->getType();
3339 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3340 } else if (!UnqualifiedTargetType->isRecordType()) {
3341 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3342 return true;
3343 }
3344 }
3345 return false;
3346}
3347
3348static void TryReferenceInitializationCore(Sema &S,
3349 const InitializedEntity &Entity,
3350 const InitializationKind &Kind,
3351 Expr *Initializer,
3352 QualType cv1T1, QualType T1,
3353 Qualifiers T1Quals,
3354 QualType cv2T2, QualType T2,
3355 Qualifiers T2Quals,
3356 InitializationSequence &Sequence);
3357
Richard Smithd86812d2012-07-05 08:39:21 +00003358static void TryValueInitialization(Sema &S,
3359 const InitializedEntity &Entity,
3360 const InitializationKind &Kind,
3361 InitializationSequence &Sequence,
Craig Topperc3ec1492014-05-26 06:22:03 +00003362 InitListExpr *InitList = nullptr);
Richard Smithd86812d2012-07-05 08:39:21 +00003363
Sebastian Redl29526f02011-11-27 16:50:07 +00003364/// \brief Attempt list initialization of a reference.
3365static void TryReferenceListInitialization(Sema &S,
3366 const InitializedEntity &Entity,
3367 const InitializationKind &Kind,
3368 InitListExpr *InitList,
Richard Smithfaadef72013-06-08 00:02:08 +00003369 InitializationSequence &Sequence) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003370 // First, catch C++03 where this isn't possible.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003371 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003372 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3373 return;
3374 }
3375
3376 QualType DestType = Entity.getType();
3377 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3378 Qualifiers T1Quals;
3379 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3380
3381 // Reference initialization via an initializer list works thus:
3382 // If the initializer list consists of a single element that is
3383 // reference-related to the referenced type, bind directly to that element
3384 // (possibly creating temporaries).
3385 // Otherwise, initialize a temporary with the initializer list and
3386 // bind to that.
3387 if (InitList->getNumInits() == 1) {
3388 Expr *Initializer = InitList->getInit(0);
3389 QualType cv2T2 = Initializer->getType();
3390 Qualifiers T2Quals;
3391 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3392
3393 // If this fails, creating a temporary wouldn't work either.
3394 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3395 T1, Sequence))
3396 return;
3397
3398 SourceLocation DeclLoc = Initializer->getLocStart();
3399 bool dummy1, dummy2, dummy3;
3400 Sema::ReferenceCompareResult RefRelationship
3401 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3402 dummy2, dummy3);
3403 if (RefRelationship >= Sema::Ref_Related) {
3404 // Try to bind the reference here.
3405 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3406 T1Quals, cv2T2, T2, T2Quals, Sequence);
3407 if (Sequence)
3408 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3409 return;
3410 }
Richard Smith03d93932013-01-15 07:58:29 +00003411
3412 // Update the initializer if we've resolved an overloaded function.
3413 if (Sequence.step_begin() != Sequence.step_end())
3414 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl29526f02011-11-27 16:50:07 +00003415 }
3416
3417 // Not reference-related. Create a temporary and bind to that.
3418 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3419
3420 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3421 if (Sequence) {
3422 if (DestType->isRValueReferenceType() ||
3423 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3424 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3425 else
3426 Sequence.SetFailed(
3427 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3428 }
3429}
3430
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003431/// \brief Attempt list initialization (C++0x [dcl.init.list])
3432static void TryListInitialization(Sema &S,
3433 const InitializedEntity &Entity,
3434 const InitializationKind &Kind,
3435 InitListExpr *InitList,
3436 InitializationSequence &Sequence) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003437 QualType DestType = Entity.getType();
3438
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003439 // C++ doesn't allow scalar initialization with more than one argument.
3440 // But C99 complex numbers are scalars and it makes sense there.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003441 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003442 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3443 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3444 return;
3445 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003446 if (DestType->isReferenceType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003447 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003448 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003449 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00003450 if (DestType->isRecordType()) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003451 if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003452 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redl4f28b582012-02-19 12:27:43 +00003453 return;
3454 }
3455
Richard Smithd86812d2012-07-05 08:39:21 +00003456 // C++11 [dcl.init.list]p3:
3457 // - If T is an aggregate, aggregate initialization is performed.
Sebastian Redl4f28b582012-02-19 12:27:43 +00003458 if (!DestType->isAggregateType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003459 if (S.getLangOpts().CPlusPlus11) {
Richard Smithd86812d2012-07-05 08:39:21 +00003460 // - Otherwise, if the initializer list has no elements and T is a
3461 // class type with a default constructor, the object is
3462 // value-initialized.
3463 if (InitList->getNumInits() == 0) {
3464 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
Richard Smith2be35f52012-12-01 02:35:44 +00003465 if (RD->hasDefaultConstructor()) {
Richard Smithd86812d2012-07-05 08:39:21 +00003466 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3467 return;
3468 }
3469 }
3470
3471 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3472 // an initializer_list object constructed [...]
3473 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3474 return;
3475
3476 // - Otherwise, if T is a class type, constructors are considered.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003477 Expr *InitListAsExpr = InitList;
3478 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smithd86812d2012-07-05 08:39:21 +00003479 Sequence, /*InitListSyntax*/true);
Sebastian Redl4f28b582012-02-19 12:27:43 +00003480 } else
3481 Sequence.SetFailed(
3482 InitializationSequence::FK_InitListBadDestinationType);
3483 return;
3484 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003485 }
Richard Smith089c3162013-09-21 21:55:46 +00003486 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
3487 InitList->getNumInits() == 1 &&
3488 InitList->getInit(0)->getType()->isRecordType()) {
3489 // - Otherwise, if the initializer list has a single element of type E
3490 // [...references are handled above...], the object or reference is
3491 // initialized from that element; if a narrowing conversion is required
3492 // to convert the element to T, the program is ill-formed.
3493 //
3494 // Per core-24034, this is direct-initialization if we were performing
3495 // direct-list-initialization and copy-initialization otherwise.
3496 // We can't use InitListChecker for this, because it always performs
3497 // copy-initialization. This only matters if we might use an 'explicit'
3498 // conversion operator, so we only need to handle the cases where the source
3499 // is of record type.
3500 InitializationKind SubKind =
3501 Kind.getKind() == InitializationKind::IK_DirectList
3502 ? InitializationKind::CreateDirect(Kind.getLocation(),
3503 InitList->getLBraceLoc(),
3504 InitList->getRBraceLoc())
3505 : Kind;
3506 Expr *SubInit[1] = { InitList->getInit(0) };
3507 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
3508 /*TopLevelOfInitList*/true);
3509 if (Sequence)
3510 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3511 return;
3512 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003513
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003514 InitListChecker CheckInitList(S, Entity, InitList,
Richard Smithde229232013-06-06 11:41:05 +00003515 DestType, /*VerifyOnly=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003516 if (CheckInitList.HadError()) {
3517 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3518 return;
3519 }
3520
3521 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003522 Sequence.AddListInitializationStep(DestType);
3523}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003524
3525/// \brief Try a reference initialization that involves calling a conversion
3526/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003527static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3528 const InitializedEntity &Entity,
3529 const InitializationKind &Kind,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003530 Expr *Initializer,
3531 bool AllowRValues,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003532 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003533 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003534 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3535 QualType T1 = cv1T1.getUnqualifiedType();
3536 QualType cv2T2 = Initializer->getType();
3537 QualType T2 = cv2T2.getUnqualifiedType();
3538
3539 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003540 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003541 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003542 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003543 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003544 ObjCConversion,
3545 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003546 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00003547 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003548 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003549 (void)ObjCLifetimeConversion;
3550
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003551 // Build the candidate set directly in the initialization sequence
3552 // structure, so that it will persist if we fail.
3553 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3554 CandidateSet.clear();
3555
3556 // Determine whether we are allowed to call explicit constructors or
3557 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00003558 bool AllowExplicit = Kind.AllowExplicit();
Richard Smith6c6ddab2013-09-21 21:23:47 +00003559 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
3560
Craig Topperc3ec1492014-05-26 06:22:03 +00003561 const RecordType *T1RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003562 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3563 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003564 // The type we're converting to is a class type. Enumerate its constructors
3565 // to see if there is a suitable conversion.
3566 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00003567
David Blaikieff7d47a2012-12-19 00:45:41 +00003568 DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003569 // The container holding the constructors can under certain conditions
3570 // be changed while iterating (e.g. because of deserialization).
3571 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00003572 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00003573 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003574 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3575 NamedDecl *D = *CI;
John McCalla0296f72010-03-19 07:35:19 +00003576 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3577
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003578 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003579 CXXConstructorDecl *Constructor = nullptr;
John McCalla0296f72010-03-19 07:35:19 +00003580 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003581 if (ConstructorTmpl)
3582 Constructor = cast<CXXConstructorDecl>(
3583 ConstructorTmpl->getTemplatedDecl());
3584 else
John McCalla0296f72010-03-19 07:35:19 +00003585 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003586
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003587 if (!Constructor->isInvalidDecl() &&
3588 Constructor->isConvertingConstructor(AllowExplicit)) {
3589 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003590 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003591 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003592 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003593 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003594 else
John McCalla0296f72010-03-19 07:35:19 +00003595 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003596 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003597 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003598 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003599 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003600 }
John McCall3696dcb2010-08-17 07:23:57 +00003601 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3602 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003603
Craig Topperc3ec1492014-05-26 06:22:03 +00003604 const RecordType *T2RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003605 if ((T2RecordType = T2->getAs<RecordType>()) &&
3606 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003607 // The type we're converting from is a class type, enumerate its conversion
3608 // functions.
3609 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3610
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00003611 std::pair<CXXRecordDecl::conversion_iterator,
3612 CXXRecordDecl::conversion_iterator>
3613 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3614 for (CXXRecordDecl::conversion_iterator
3615 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003616 NamedDecl *D = *I;
3617 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3618 if (isa<UsingShadowDecl>(D))
3619 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003620
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003621 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3622 CXXConversionDecl *Conv;
3623 if (ConvTemplate)
3624 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3625 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003626 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003627
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003628 // If the conversion function doesn't return a reference type,
3629 // it can't be considered for this conversion unless we're allowed to
3630 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003631 // FIXME: Do we need to make sure that we only consider conversion
3632 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003633 // break recursion.
Douglas Gregor6073dca2012-02-24 23:56:31 +00003634 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003635 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3636 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003637 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003638 ActingDC, Initializer,
Douglas Gregor68782142013-12-18 21:46:16 +00003639 DestType, CandidateSet,
3640 /*AllowObjCConversionOnExplicit=*/
3641 false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003642 else
John McCalla0296f72010-03-19 07:35:19 +00003643 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00003644 Initializer, DestType, CandidateSet,
3645 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003646 }
3647 }
3648 }
John McCall3696dcb2010-08-17 07:23:57 +00003649 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3650 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003651
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003652 SourceLocation DeclLoc = Initializer->getLocStart();
3653
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003654 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003655 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003656 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003657 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003658 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003659
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003660 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00003661 // This is the overload that will be used for this initialization step if we
3662 // use this initialization. Mark it as referenced.
3663 Function->setReferenced();
Chandler Carruth30141632011-02-25 19:41:05 +00003664
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003665 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003666 if (isa<CXXConversionDecl>(Function))
Alp Toker314cc812014-01-25 16:55:45 +00003667 T2 = Function->getReturnType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003668 else
3669 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003670
3671 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003672 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCalla0296f72010-03-19 07:35:19 +00003673 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003674 T2.getNonLValueExprType(S.Context),
3675 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003676
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003677 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003678 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00003679 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003680 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00003681 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003682 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00003683 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003684
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003685 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003686 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003687 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003688 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003689 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003690 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00003691 NewDerivedToBase, NewObjCConversion,
3692 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00003693 if (NewRefRelationship == Sema::Ref_Incompatible) {
3694 // If the type we've converted to is not reference-related to the
3695 // type we're looking for, then there is another conversion step
3696 // we need to perform to produce a temporary of the right type
3697 // that we'll be binding to.
3698 ImplicitConversionSequence ICS;
3699 ICS.setStandard();
3700 ICS.Standard = Best->FinalConversion;
3701 T2 = ICS.Standard.getToType(2);
3702 Sequence.AddConversionSequenceStep(ICS, T2);
3703 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003704 Sequence.AddDerivedToBaseCastStep(
3705 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003706 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00003707 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003708 else if (NewObjCConversion)
3709 Sequence.AddObjCObjectConversionStep(
3710 S.Context.getQualifiedType(T1,
3711 T2.getNonReferenceType().getQualifiers()));
3712
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003713 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00003714 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003715
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003716 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3717 return OR_Success;
3718}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003719
Richard Smithc620f552011-10-19 16:55:56 +00003720static void CheckCXX98CompatAccessibleCopy(Sema &S,
3721 const InitializedEntity &Entity,
3722 Expr *CurInitExpr);
3723
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003724/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3725static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003726 const InitializedEntity &Entity,
3727 const InitializationKind &Kind,
3728 Expr *Initializer,
3729 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003730 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003731 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003732 Qualifiers T1Quals;
3733 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003734 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003735 Qualifiers T2Quals;
3736 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00003737
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003738 // If the initializer is the address of an overloaded function, try
3739 // to resolve the overloaded function. If all goes well, T2 is the
3740 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00003741 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3742 T1, Sequence))
3743 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00003744
Sebastian Redl29526f02011-11-27 16:50:07 +00003745 // Delegate everything else to a subfunction.
3746 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3747 T1Quals, cv2T2, T2, T2Quals, Sequence);
3748}
3749
Jordan Roseb1312a52013-04-11 00:58:58 +00003750/// Converts the target of reference initialization so that it has the
3751/// appropriate qualifiers and value kind.
3752///
3753/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3754/// \code
3755/// int x;
3756/// const int &r = x;
3757/// \endcode
3758///
3759/// In this case the reference is binding to a bitfield lvalue, which isn't
3760/// valid. Perform a load to create a lifetime-extended temporary instead.
3761/// \code
3762/// const int &r = someStruct.bitfield;
3763/// \endcode
3764static ExprValueKind
3765convertQualifiersAndValueKindIfNecessary(Sema &S,
3766 InitializationSequence &Sequence,
3767 Expr *Initializer,
3768 QualType cv1T1,
3769 Qualifiers T1Quals,
3770 Qualifiers T2Quals,
3771 bool IsLValueRef) {
John McCalld25db7e2013-05-06 21:39:12 +00003772 bool IsNonAddressableType = Initializer->refersToBitField() ||
Jordan Roseb1312a52013-04-11 00:58:58 +00003773 Initializer->refersToVectorElement();
3774
3775 if (IsNonAddressableType) {
3776 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3777 // lvalue reference to a non-volatile const type, or the reference shall be
3778 // an rvalue reference.
3779 //
3780 // If not, we can't make a temporary and bind to that. Give up and allow the
3781 // error to be diagnosed later.
3782 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3783 assert(Initializer->isGLValue());
3784 return Initializer->getValueKind();
3785 }
3786
3787 // Force a load so we can materialize a temporary.
3788 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3789 return VK_RValue;
3790 }
3791
3792 if (T1Quals != T2Quals) {
3793 Sequence.AddQualificationConversionStep(cv1T1,
3794 Initializer->getValueKind());
3795 }
3796
3797 return Initializer->getValueKind();
3798}
3799
3800
Sebastian Redl29526f02011-11-27 16:50:07 +00003801/// \brief Reference initialization without resolving overloaded functions.
3802static void TryReferenceInitializationCore(Sema &S,
3803 const InitializedEntity &Entity,
3804 const InitializationKind &Kind,
3805 Expr *Initializer,
3806 QualType cv1T1, QualType T1,
3807 Qualifiers T1Quals,
3808 QualType cv2T2, QualType T2,
3809 Qualifiers T2Quals,
3810 InitializationSequence &Sequence) {
3811 QualType DestType = Entity.getType();
3812 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003813 // Compute some basic properties of the types and the initializer.
3814 bool isLValueRef = DestType->isLValueReferenceType();
3815 bool isRValueRef = !isLValueRef;
3816 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003817 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003818 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003819 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003820 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003821 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003822 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00003823
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003824 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003825 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003826 // "cv2 T2" as follows:
3827 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003828 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003829 // expression
Richard Smith6c6ddab2013-09-21 21:23:47 +00003830 // Note the analogous bullet points for rvalue refs to functions. Because
Sebastian Redld92badf2010-06-30 18:13:39 +00003831 // there are no function rvalues in C++, rvalue refs to functions are treated
3832 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003833 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00003834 bool T1Function = T1->isFunctionType();
3835 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003836 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003837 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003838 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003839 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003840 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003841 // reference-compatible with "cv2 T2," or
3842 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003843 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003844 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003845 // can occur. However, we do pay attention to whether it is a bit-field
3846 // to decide whether we're actually binding to a temporary created from
3847 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003848 if (DerivedToBase)
3849 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003850 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00003851 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003852 else if (ObjCConversion)
3853 Sequence.AddObjCObjectConversionStep(
3854 S.Context.getQualifiedType(T1, T2Quals));
3855
Jordan Roseb1312a52013-04-11 00:58:58 +00003856 ExprValueKind ValueKind =
3857 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3858 cv1T1, T1Quals, T2Quals,
3859 isLValueRef);
3860 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003861 return;
3862 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003863
3864 // - has a class type (i.e., T2 is a class type), where T1 is not
3865 // reference-related to T2, and can be implicitly converted to an
3866 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3867 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003868 // applicable conversion functions (13.3.1.6) and choosing the best
3869 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00003870 // If we have an rvalue ref to function type here, the rhs must be
Richard Smith6c6ddab2013-09-21 21:23:47 +00003871 // an rvalue. DR1287 removed the "implicitly" here.
Sebastian Redld92badf2010-06-30 18:13:39 +00003872 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3873 (isLValueRef || InitCategory.isRValue())) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00003874 ConvOvlResult = TryRefInitWithConversionFunction(
3875 S, Entity, Kind, Initializer, /*AllowRValues*/isRValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003876 if (ConvOvlResult == OR_Success)
3877 return;
Richard Smith6c6ddab2013-09-21 21:23:47 +00003878 if (ConvOvlResult != OR_No_Viable_Function)
John McCall0d1da222010-01-12 00:44:57 +00003879 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00003880 InitializationSequence::FK_ReferenceInitOverloadFailed,
3881 ConvOvlResult);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003882 }
3883 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003884
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003885 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003886 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00003887 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003888 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00003889 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3890 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3891 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003892 Sequence.SetOverloadFailure(
3893 InitializationSequence::FK_ReferenceInitOverloadFailed,
3894 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003895 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003896 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003897 ? (RefRelationship == Sema::Ref_Related
3898 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3899 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3900 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00003901
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003902 return;
3903 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003904
Douglas Gregor92e460e2011-01-20 16:44:54 +00003905 // - If the initializer expression
3906 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3907 // "cv1 T1" is reference-compatible with "cv2 T2"
3908 // Note: functions are handled below.
3909 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00003910 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003911 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003912 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00003913 (InitCategory.isXValue() ||
3914 (InitCategory.isPRValue() && T2->isRecordType()) ||
3915 (InitCategory.isPRValue() && T2->isArrayType()))) {
3916 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3917 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003918 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3919 // compiler the freedom to perform a copy here or bind to the
3920 // object, while C++0x requires that we bind directly to the
3921 // object. Hence, we always bind to the object without making an
3922 // extra copy. However, in C++03 requires that we check for the
3923 // presence of a suitable copy constructor:
3924 //
3925 // The constructor that would be used to make the copy shall
3926 // be callable whether or not the copy is actually done.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003927 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003928 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003929 else if (S.getLangOpts().CPlusPlus11)
Richard Smithc620f552011-10-19 16:55:56 +00003930 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003931 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003932
Douglas Gregor92e460e2011-01-20 16:44:54 +00003933 if (DerivedToBase)
3934 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3935 ValueKind);
3936 else if (ObjCConversion)
3937 Sequence.AddObjCObjectConversionStep(
3938 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003939
Jordan Roseb1312a52013-04-11 00:58:58 +00003940 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3941 Initializer, cv1T1,
3942 T1Quals, T2Quals,
3943 isLValueRef);
3944
3945 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003946 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00003947 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003948
3949 // - has a class type (i.e., T2 is a class type), where T1 is not
3950 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00003951 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3952 // where "cv1 T1" is reference-compatible with "cv3 T3",
Richard Smith6c6ddab2013-09-21 21:23:47 +00003953 //
3954 // DR1287 removes the "implicitly" here.
Douglas Gregor92e460e2011-01-20 16:44:54 +00003955 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003956 if (RefRelationship == Sema::Ref_Incompatible) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00003957 ConvOvlResult = TryRefInitWithConversionFunction(
3958 S, Entity, Kind, Initializer, /*AllowRValues*/true, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003959 if (ConvOvlResult)
3960 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00003961 InitializationSequence::FK_ReferenceInitOverloadFailed,
3962 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003963
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003964 return;
3965 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003966
Douglas Gregor6fa6ab02013-03-26 23:59:23 +00003967 if ((RefRelationship == Sema::Ref_Compatible ||
3968 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3969 isRValueRef && InitCategory.isLValue()) {
3970 Sequence.SetFailed(
3971 InitializationSequence::FK_RValueReferenceBindingToLValue);
3972 return;
3973 }
3974
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003975 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3976 return;
3977 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003978
3979 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003980 // from the initializer expression using the rules for a non-reference
Richard Smith2eabf782013-06-13 00:57:57 +00003981 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003982 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00003983
John McCallec6f4e92010-06-04 02:29:22 +00003984 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3985
Richard Smith2eabf782013-06-13 00:57:57 +00003986 // FIXME: Why do we use an implicit conversion here rather than trying
3987 // copy-initialization?
John McCall31168b02011-06-15 23:02:42 +00003988 ImplicitConversionSequence ICS
3989 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith2eabf782013-06-13 00:57:57 +00003990 /*SuppressUserConversions=*/false,
3991 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003992 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003993 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3994 /*AllowObjCWritebackConversion=*/false);
3995
3996 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003997 // FIXME: Use the conversion function set stored in ICS to turn
3998 // this into an overloading ambiguity diagnostic. However, we need
3999 // to keep that set as an OverloadCandidateSet rather than as some
4000 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00004001 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4002 Sequence.SetOverloadFailure(
4003 InitializationSequence::FK_ReferenceInitOverloadFailed,
4004 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00004005 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4006 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00004007 else
4008 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004009 return;
John McCall31168b02011-06-15 23:02:42 +00004010 } else {
4011 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004012 }
4013
4014 // [...] If T1 is reference-related to T2, cv1 must be the
4015 // same cv-qualification as, or greater cv-qualification
4016 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00004017 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4018 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004019 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00004020 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004021 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4022 return;
4023 }
4024
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004025 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004026 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004027 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004028 InitCategory.isLValue()) {
4029 Sequence.SetFailed(
4030 InitializationSequence::FK_RValueReferenceBindingToLValue);
4031 return;
4032 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004033
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004034 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
4035 return;
4036}
4037
4038/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004039/// (C++ [dcl.init.string], C99 6.7.8).
4040static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004041 const InitializedEntity &Entity,
4042 const InitializationKind &Kind,
4043 Expr *Initializer,
4044 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004045 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004046}
4047
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004048/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004049static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004050 const InitializedEntity &Entity,
4051 const InitializationKind &Kind,
Richard Smithd86812d2012-07-05 08:39:21 +00004052 InitializationSequence &Sequence,
4053 InitListExpr *InitList) {
4054 assert((!InitList || InitList->getNumInits() == 0) &&
4055 "Shouldn't use value-init for non-empty init lists");
4056
Richard Smith1bfe0682012-02-14 21:14:13 +00004057 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004058 //
4059 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00004060 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004061
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004062 // -- if T is an array type, then each element is value-initialized;
Richard Smith1bfe0682012-02-14 21:14:13 +00004063 T = S.Context.getBaseElementType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004064
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004065 if (const RecordType *RT = T->getAs<RecordType>()) {
4066 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithd86812d2012-07-05 08:39:21 +00004067 bool NeedZeroInitialization = true;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004068 if (!S.getLangOpts().CPlusPlus11) {
Richard Smithd86812d2012-07-05 08:39:21 +00004069 // C++98:
4070 // -- if T is a class type (clause 9) with a user-declared constructor
4071 // (12.1), then the default constructor for T is called (and the
4072 // initialization is ill-formed if T has no accessible default
4073 // constructor);
Richard Smith1bfe0682012-02-14 21:14:13 +00004074 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithd86812d2012-07-05 08:39:21 +00004075 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00004076 } else {
4077 // C++11:
4078 // -- if T is a class type (clause 9) with either no default constructor
4079 // (12.1 [class.ctor]) or a default constructor that is user-provided
4080 // or deleted, then the object is default-initialized;
4081 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4082 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithd86812d2012-07-05 08:39:21 +00004083 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00004084 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004085
Richard Smith1bfe0682012-02-14 21:14:13 +00004086 // -- if T is a (possibly cv-qualified) non-union class type without a
4087 // user-provided or deleted default constructor, then the object is
4088 // zero-initialized and, if T has a non-trivial default constructor,
4089 // default-initialized;
Richard Smithfb266522012-10-18 00:44:17 +00004090 // The 'non-union' here was removed by DR1502. The 'non-trivial default
4091 // constructor' part was removed by DR1507.
Richard Smithd86812d2012-07-05 08:39:21 +00004092 if (NeedZeroInitialization)
4093 Sequence.AddZeroInitializationStep(Entity.getType());
4094
Richard Smith593f9932012-12-08 02:01:17 +00004095 // C++03:
4096 // -- if T is a non-union class type without a user-declared constructor,
4097 // then every non-static data member and base class component of T is
4098 // value-initialized;
4099 // [...] A program that calls for [...] value-initialization of an
4100 // entity of reference type is ill-formed.
4101 //
4102 // C++11 doesn't need this handling, because value-initialization does not
4103 // occur recursively there, and the implicit default constructor is
4104 // defined as deleted in the problematic cases.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004105 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smith593f9932012-12-08 02:01:17 +00004106 ClassDecl->hasUninitializedReferenceMember()) {
4107 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4108 return;
4109 }
4110
Richard Smithd86812d2012-07-05 08:39:21 +00004111 // If this is list-value-initialization, pass the empty init list on when
4112 // building the constructor call. This affects the semantics of a few
4113 // things (such as whether an explicit default constructor can be called).
4114 Expr *InitListAsExpr = InitList;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004115 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithd86812d2012-07-05 08:39:21 +00004116 bool InitListSyntax = InitList;
4117
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004118 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
4119 InitListSyntax);
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004120 }
4121 }
4122
Douglas Gregor1b303932009-12-22 15:35:07 +00004123 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004124}
4125
Douglas Gregor85dabae2009-12-16 01:38:02 +00004126/// \brief Attempt default initialization (C++ [dcl.init]p6).
4127static void TryDefaultInitialization(Sema &S,
4128 const InitializedEntity &Entity,
4129 const InitializationKind &Kind,
4130 InitializationSequence &Sequence) {
4131 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004132
Douglas Gregor85dabae2009-12-16 01:38:02 +00004133 // C++ [dcl.init]p6:
4134 // To default-initialize an object of type T means:
4135 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00004136 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4137
Douglas Gregor85dabae2009-12-16 01:38:02 +00004138 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4139 // constructor for T is called (and the initialization is ill-formed if
4140 // T has no accessible default constructor);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004141 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004142 TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
Chandler Carruthc9262402010-08-23 07:55:51 +00004143 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004144 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004145
Douglas Gregor85dabae2009-12-16 01:38:02 +00004146 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004147
Douglas Gregor85dabae2009-12-16 01:38:02 +00004148 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004149 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00004150 // default constructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004151 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004152 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00004153 return;
4154 }
4155
4156 // If the destination type has a lifetime property, zero-initialize it.
4157 if (DestType.getQualifiers().hasObjCLifetime()) {
4158 Sequence.AddZeroInitializationStep(Entity.getType());
4159 return;
4160 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004161}
4162
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004163/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4164/// which enumerates all conversion functions and performs overload resolution
4165/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004166static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004167 const InitializedEntity &Entity,
4168 const InitializationKind &Kind,
4169 Expr *Initializer,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004170 InitializationSequence &Sequence,
4171 bool TopLevelOfInitList) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004172 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00004173 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4174 QualType SourceType = Initializer->getType();
4175 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4176 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004177
Douglas Gregor540c3b02009-12-14 17:27:33 +00004178 // Build the candidate set directly in the initialization sequence
4179 // structure, so that it will persist if we fail.
4180 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4181 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004182
Douglas Gregor540c3b02009-12-14 17:27:33 +00004183 // Determine whether we are allowed to call explicit constructors or
4184 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00004185 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004186
Douglas Gregor540c3b02009-12-14 17:27:33 +00004187 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4188 // The type we're converting to is a class type. Enumerate its constructors
4189 // to see if there is a suitable conversion.
4190 CXXRecordDecl *DestRecordDecl
4191 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004192
Douglas Gregord9848152010-04-26 14:36:57 +00004193 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004194 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
David Blaikieff7d47a2012-12-19 00:45:41 +00004195 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
David Blaikie12be6392012-10-18 16:57:32 +00004196 // The container holding the constructors can under certain conditions
4197 // be changed while iterating. To be safe we copy the lookup results
4198 // to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00004199 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00004200 for (SmallVectorImpl<NamedDecl *>::iterator
David Blaikie12be6392012-10-18 16:57:32 +00004201 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Douglas Gregord9848152010-04-26 14:36:57 +00004202 Con != ConEnd; ++Con) {
4203 NamedDecl *D = *Con;
4204 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004205
Douglas Gregord9848152010-04-26 14:36:57 +00004206 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00004207 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregord9848152010-04-26 14:36:57 +00004208 FunctionTemplateDecl *ConstructorTmpl
4209 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004210 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00004211 Constructor = cast<CXXConstructorDecl>(
4212 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00004213 else
Douglas Gregord9848152010-04-26 14:36:57 +00004214 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004215
Douglas Gregord9848152010-04-26 14:36:57 +00004216 if (!Constructor->isInvalidDecl() &&
4217 Constructor->isConvertingConstructor(AllowExplicit)) {
4218 if (ConstructorTmpl)
4219 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004220 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004221 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004222 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004223 else
4224 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004225 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004226 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004227 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004228 }
Douglas Gregord9848152010-04-26 14:36:57 +00004229 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004230 }
Eli Friedman78275202009-12-19 08:11:05 +00004231
4232 SourceLocation DeclLoc = Initializer->getLocStart();
4233
Douglas Gregor540c3b02009-12-14 17:27:33 +00004234 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4235 // The type we're converting from is a class type, enumerate its conversion
4236 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00004237
Eli Friedman4afe9a32009-12-20 22:12:03 +00004238 // We can only enumerate the conversion functions for a complete type; if
4239 // the type isn't complete, simply skip this step.
4240 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
4241 CXXRecordDecl *SourceRecordDecl
4242 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004243
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00004244 std::pair<CXXRecordDecl::conversion_iterator,
4245 CXXRecordDecl::conversion_iterator>
4246 Conversions = SourceRecordDecl->getVisibleConversionFunctions();
4247 for (CXXRecordDecl::conversion_iterator
4248 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004249 NamedDecl *D = *I;
4250 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4251 if (isa<UsingShadowDecl>(D))
4252 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004253
Eli Friedman4afe9a32009-12-20 22:12:03 +00004254 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4255 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00004256 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00004257 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00004258 else
John McCallda4458e2010-03-31 01:36:47 +00004259 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004260
Eli Friedman4afe9a32009-12-20 22:12:03 +00004261 if (AllowExplicit || !Conv->isExplicit()) {
4262 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004263 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004264 ActingDC, Initializer, DestType,
Douglas Gregor68782142013-12-18 21:46:16 +00004265 CandidateSet, AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004266 else
John McCalla0296f72010-03-19 07:35:19 +00004267 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004268 Initializer, DestType, CandidateSet,
4269 AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004270 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004271 }
4272 }
4273 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004274
4275 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004276 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00004277 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00004278 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004279 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004280 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00004281 Result);
4282 return;
4283 }
John McCall0d1da222010-01-12 00:44:57 +00004284
Douglas Gregor540c3b02009-12-14 17:27:33 +00004285 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004286 Function->setReferenced();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004287 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004288
Douglas Gregor540c3b02009-12-14 17:27:33 +00004289 if (isa<CXXConstructorDecl>(Function)) {
4290 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithb24f0672012-02-11 19:22:50 +00004291 // subsumed by the initialization. Per DR5, the created temporary is of the
4292 // cv-unqualified type of the destination.
4293 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4294 DestType.getUnqualifiedType(),
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004295 HadMultipleCandidates);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004296 return;
4297 }
4298
4299 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004300 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004301 if (ConvType->getAs<RecordType>()) {
Richard Smithb24f0672012-02-11 19:22:50 +00004302 // If we're converting to a class type, there may be an copy of
Douglas Gregor5ab11652010-04-17 22:01:05 +00004303 // the resulting temporary object (possible to create an object of
4304 // a base class type). That copy is not a separate conversion, so
4305 // we just make a note of the actual destination type (possibly a
4306 // base class of the type returned by the conversion function) and
4307 // let the user-defined conversion step handle the conversion.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004308 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4309 HadMultipleCandidates);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004310 return;
4311 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004312
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004313 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4314 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004315
Douglas Gregor5ab11652010-04-17 22:01:05 +00004316 // If the conversion following the call to the conversion function
4317 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004318 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4319 Best->FinalConversion.Third) {
4320 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00004321 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00004322 ICS.Standard = Best->FinalConversion;
Richard Smithaaa0ec42013-09-21 21:19:19 +00004323 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004324 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004325}
4326
Richard Smithf032001b2013-06-20 02:18:31 +00004327/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4328/// a function with a pointer return type contains a 'return false;' statement.
4329/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4330/// code using that header.
4331///
4332/// Work around this by treating 'return false;' as zero-initializing the result
4333/// if it's used in a pointer-returning function in a system header.
4334static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4335 const InitializedEntity &Entity,
4336 const Expr *Init) {
4337 return S.getLangOpts().CPlusPlus11 &&
4338 Entity.getKind() == InitializedEntity::EK_Result &&
4339 Entity.getType()->isPointerType() &&
4340 isa<CXXBoolLiteralExpr>(Init) &&
4341 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4342 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4343}
4344
John McCall31168b02011-06-15 23:02:42 +00004345/// The non-zero enum values here are indexes into diagnostic alternatives.
4346enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4347
4348/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00004349static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004350 bool isAddressOf, bool &isWeakAccess) {
John McCall31168b02011-06-15 23:02:42 +00004351 // Skip parens.
4352 e = e->IgnoreParens();
4353
4354 // Skip address-of nodes.
4355 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4356 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004357 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4358 isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004359
4360 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00004361 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4362 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00004363 case CK_Dependent:
4364 case CK_BitCast:
4365 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00004366 case CK_NoOp:
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004367 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004368
4369 case CK_ArrayToPointerDecay:
4370 return IIK_nonscalar;
4371
4372 case CK_NullToPointer:
4373 return IIK_okay;
4374
4375 default:
4376 break;
4377 }
4378
4379 // If we have a declaration reference, it had better be a local variable.
John McCall113bee02012-03-10 09:33:50 +00004380 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004381 // set isWeakAccess to true, to mean that there will be an implicit
4382 // load which requires a cleanup.
4383 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4384 isWeakAccess = true;
4385
John McCall63f84442011-06-27 23:59:58 +00004386 if (!isAddressOf) return IIK_nonlocal;
4387
John McCall113bee02012-03-10 09:33:50 +00004388 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4389 if (!var) return IIK_nonlocal;
John McCall63f84442011-06-27 23:59:58 +00004390
4391 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00004392
4393 // If we have a conditional operator, check both sides.
4394 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004395 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4396 isWeakAccess))
John McCall31168b02011-06-15 23:02:42 +00004397 return iik;
4398
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004399 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004400
4401 // These are never scalar.
4402 } else if (isa<ArraySubscriptExpr>(e)) {
4403 return IIK_nonscalar;
4404
4405 // Otherwise, it needs to be a null pointer constant.
4406 } else {
4407 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4408 ? IIK_okay : IIK_nonlocal);
4409 }
4410
4411 return IIK_nonlocal;
4412}
4413
4414/// Check whether the given expression is a valid operand for an
4415/// indirect copy/restore.
4416static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4417 assert(src->isRValue());
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004418 bool isWeakAccess = false;
4419 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4420 // If isWeakAccess to true, there will be an implicit
4421 // load which requires a cleanup.
4422 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4423 S.ExprNeedsCleanups = true;
4424
John McCall31168b02011-06-15 23:02:42 +00004425 if (iik == IIK_okay) return;
4426
4427 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4428 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4429 << src->getSourceRange();
4430}
4431
Douglas Gregore2f943b2011-02-22 18:29:51 +00004432/// \brief Determine whether we have compatible array types for the
4433/// purposes of GNU by-copy array initialization.
4434static bool hasCompatibleArrayTypes(ASTContext &Context,
4435 const ArrayType *Dest,
4436 const ArrayType *Source) {
4437 // If the source and destination array types are equivalent, we're
4438 // done.
4439 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4440 return true;
4441
4442 // Make sure that the element types are the same.
4443 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4444 return false;
4445
4446 // The only mismatch we allow is when the destination is an
4447 // incomplete array type and the source is a constant array type.
4448 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4449}
4450
John McCall31168b02011-06-15 23:02:42 +00004451static bool tryObjCWritebackConversion(Sema &S,
4452 InitializationSequence &Sequence,
4453 const InitializedEntity &Entity,
4454 Expr *Initializer) {
4455 bool ArrayDecay = false;
4456 QualType ArgType = Initializer->getType();
4457 QualType ArgPointee;
4458 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4459 ArrayDecay = true;
4460 ArgPointee = ArgArrayType->getElementType();
4461 ArgType = S.Context.getPointerType(ArgPointee);
4462 }
4463
4464 // Handle write-back conversion.
4465 QualType ConvertedArgType;
4466 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4467 ConvertedArgType))
4468 return false;
4469
4470 // We should copy unless we're passing to an argument explicitly
4471 // marked 'out'.
4472 bool ShouldCopy = true;
4473 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4474 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4475
4476 // Do we need an lvalue conversion?
4477 if (ArrayDecay || Initializer->isGLValue()) {
4478 ImplicitConversionSequence ICS;
4479 ICS.setStandard();
4480 ICS.Standard.setAsIdentityConversion();
4481
4482 QualType ResultType;
4483 if (ArrayDecay) {
4484 ICS.Standard.First = ICK_Array_To_Pointer;
4485 ResultType = S.Context.getPointerType(ArgPointee);
4486 } else {
4487 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4488 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4489 }
4490
4491 Sequence.AddConversionSequenceStep(ICS, ResultType);
4492 }
4493
4494 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4495 return true;
4496}
4497
Guy Benyei61054192013-02-07 10:55:47 +00004498static bool TryOCLSamplerInitialization(Sema &S,
4499 InitializationSequence &Sequence,
4500 QualType DestType,
4501 Expr *Initializer) {
4502 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4503 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4504 return false;
4505
4506 Sequence.AddOCLSamplerInitStep(DestType);
4507 return true;
4508}
4509
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004510//
4511// OpenCL 1.2 spec, s6.12.10
4512//
4513// The event argument can also be used to associate the
4514// async_work_group_copy with a previous async copy allowing
4515// an event to be shared by multiple async copies; otherwise
4516// event should be zero.
4517//
4518static bool TryOCLZeroEventInitialization(Sema &S,
4519 InitializationSequence &Sequence,
4520 QualType DestType,
4521 Expr *Initializer) {
4522 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4523 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4524 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4525 return false;
4526
4527 Sequence.AddOCLZeroEventStep(DestType);
4528 return true;
4529}
4530
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004531InitializationSequence::InitializationSequence(Sema &S,
4532 const InitializedEntity &Entity,
4533 const InitializationKind &Kind,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004534 MultiExprArg Args,
4535 bool TopLevelOfInitList)
Richard Smith100b24a2014-04-17 01:52:14 +00004536 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
Richard Smith089c3162013-09-21 21:55:46 +00004537 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList);
4538}
4539
4540void InitializationSequence::InitializeFrom(Sema &S,
4541 const InitializedEntity &Entity,
4542 const InitializationKind &Kind,
4543 MultiExprArg Args,
4544 bool TopLevelOfInitList) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004545 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004546
John McCall5e77d762013-04-16 07:28:30 +00004547 // Eliminate non-overload placeholder types in the arguments. We
4548 // need to do this before checking whether types are dependent
4549 // because lowering a pseudo-object expression might well give us
4550 // something of dependent type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004551 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall5e77d762013-04-16 07:28:30 +00004552 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4553 // FIXME: should we be doing this here?
4554 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4555 if (result.isInvalid()) {
4556 SetFailed(FK_PlaceholderType);
4557 return;
4558 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004559 Args[I] = result.get();
John McCall5e77d762013-04-16 07:28:30 +00004560 }
4561
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004562 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004563 // The semantics of initializers are as follows. The destination type is
4564 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004565 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004566 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004567 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004568 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004569
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004570 if (DestType->isDependentType() ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004571 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004572 SequenceKind = DependentSequence;
4573 return;
4574 }
4575
Sebastian Redld201edf2011-06-05 13:59:11 +00004576 // Almost everything is a normal sequence.
4577 setSequenceKind(NormalSequence);
4578
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004579 QualType SourceType;
Craig Topperc3ec1492014-05-26 06:22:03 +00004580 Expr *Initializer = nullptr;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004581 if (Args.size() == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004582 Initializer = Args[0];
Fariborz Jahanian283bf892013-12-18 21:04:43 +00004583 if (S.getLangOpts().ObjC1) {
4584 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
4585 DestType, Initializer->getType(),
4586 Initializer) ||
4587 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
4588 Args[0] = Initializer;
4589
4590 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004591 if (!isa<InitListExpr>(Initializer))
4592 SourceType = Initializer->getType();
4593 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004594
Sebastian Redl0501c632012-02-12 16:37:36 +00004595 // - If the initializer is a (non-parenthesized) braced-init-list, the
4596 // object is list-initialized (8.5.4).
4597 if (Kind.getKind() != InitializationKind::IK_Direct) {
4598 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4599 TryListInitialization(S, Entity, Kind, InitList, *this);
4600 return;
4601 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004602 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004603
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004604 // - If the destination type is a reference type, see 8.5.3.
4605 if (DestType->isReferenceType()) {
4606 // C++0x [dcl.init.ref]p1:
4607 // A variable declared to be a T& or T&&, that is, "reference to type T"
4608 // (8.3.2), shall be initialized by an object, or function, of type T or
4609 // by an object that can be converted into a T.
4610 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004611 if (Args.size() != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004612 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004613 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004614 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004615 return;
4616 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004617
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004618 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004619 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004620 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004621 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004622 return;
4623 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004624
Douglas Gregor85dabae2009-12-16 01:38:02 +00004625 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00004626 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004627 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004628 return;
4629 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004630
John McCall66884dd2011-02-21 07:22:22 +00004631 // - If the destination type is an array of characters, an array of
4632 // char16_t, an array of char32_t, or an array of wchar_t, and the
4633 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004634 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004635 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00004636 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00004637 if (Initializer && isa<VariableArrayType>(DestAT)) {
4638 SetFailed(FK_VariableLengthArrayHasInitializer);
4639 return;
4640 }
4641
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004642 if (Initializer) {
4643 switch (IsStringInit(Initializer, DestAT, Context)) {
4644 case SIF_None:
4645 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4646 return;
4647 case SIF_NarrowStringIntoWideChar:
4648 SetFailed(FK_NarrowStringIntoWideCharArray);
4649 return;
4650 case SIF_WideStringIntoChar:
4651 SetFailed(FK_WideStringIntoCharArray);
4652 return;
4653 case SIF_IncompatWideStringIntoWideChar:
4654 SetFailed(FK_IncompatWideStringIntoWideChar);
4655 return;
4656 case SIF_Other:
4657 break;
4658 }
John McCall66884dd2011-02-21 07:22:22 +00004659 }
4660
Douglas Gregore2f943b2011-02-22 18:29:51 +00004661 // Note: as an GNU C extension, we allow initialization of an
4662 // array from a compound literal that creates an array of the same
4663 // type, so long as the initializer has no side effects.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004664 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregore2f943b2011-02-22 18:29:51 +00004665 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4666 Initializer->getType()->isArrayType()) {
4667 const ArrayType *SourceAT
4668 = Context.getAsArrayType(Initializer->getType());
4669 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004670 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004671 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004672 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004673 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004674 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004675 }
Richard Smithebeed412012-02-15 22:38:09 +00004676 }
Richard Smithd86812d2012-07-05 08:39:21 +00004677 // Note: as a GNU C++ extension, we allow list-initialization of a
4678 // class member of array type from a parenthesized initializer list.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004679 else if (S.getLangOpts().CPlusPlus &&
Richard Smithebeed412012-02-15 22:38:09 +00004680 Entity.getKind() == InitializedEntity::EK_Member &&
4681 Initializer && isa<InitListExpr>(Initializer)) {
4682 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4683 *this);
4684 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004685 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004686 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004687 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
4688 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004689 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004690 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004691
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004692 return;
4693 }
Eli Friedman78275202009-12-19 08:11:05 +00004694
John McCall31168b02011-06-15 23:02:42 +00004695 // Determine whether we should consider writeback conversions for
4696 // Objective-C ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004697 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004698 Entity.isParameterKind();
John McCall31168b02011-06-15 23:02:42 +00004699
4700 // We're at the end of the line for C: it's either a write-back conversion
4701 // or it's a C assignment. There's no need to check anything else.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004702 if (!S.getLangOpts().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00004703 // If allowed, check whether this is an Objective-C writeback conversion.
4704 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004705 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00004706 return;
4707 }
Guy Benyei61054192013-02-07 10:55:47 +00004708
4709 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4710 return;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004711
4712 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4713 return;
4714
John McCall31168b02011-06-15 23:02:42 +00004715 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004716 AddCAssignmentStep(DestType);
4717 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00004718 return;
4719 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004720
David Blaikiebbafb8a2012-03-11 07:00:24 +00004721 assert(S.getLangOpts().CPlusPlus);
John McCall31168b02011-06-15 23:02:42 +00004722
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004723 // - If the destination type is a (possibly cv-qualified) class type:
4724 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004725 // - If the initialization is direct-initialization, or if it is
4726 // copy-initialization where the cv-unqualified version of the
4727 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004728 // class of the destination, constructors are considered. [...]
4729 if (Kind.getKind() == InitializationKind::IK_Direct ||
4730 (Kind.getKind() == InitializationKind::IK_Copy &&
4731 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4732 S.IsDerivedFrom(SourceType, DestType))))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004733 TryConstructorInitialization(S, Entity, Kind, Args,
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004734 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004735 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004736 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004737 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004738 // used) to a derived class thereof are enumerated as described in
4739 // 13.3.1.4, and the best one is chosen through overload resolution
4740 // (13.3).
4741 else
Richard Smithaaa0ec42013-09-21 21:19:19 +00004742 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this,
4743 TopLevelOfInitList);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004744 return;
4745 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004746
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004747 if (Args.size() > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004748 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004749 return;
4750 }
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004751 assert(Args.size() == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004752
4753 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004754 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004755 if (!SourceType.isNull() && SourceType->isRecordType()) {
Richard Smithaaa0ec42013-09-21 21:19:19 +00004756 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this,
4757 TopLevelOfInitList);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004758 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004759 return;
4760 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004761
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004762 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00004763 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004764 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004765 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004766 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00004767
4768 ImplicitConversionSequence ICS
4769 = S.TryImplicitConversion(Initializer, Entity.getType(),
4770 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00004771 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00004772 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00004773 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4774 allowObjCWritebackConversion);
4775
4776 if (ICS.isStandard() &&
4777 ICS.Standard.Second == ICK_Writeback_Conversion) {
4778 // Objective-C ARC writeback conversion.
4779
4780 // We should copy unless we're passing to an argument explicitly
4781 // marked 'out'.
4782 bool ShouldCopy = true;
4783 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4784 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4785
4786 // If there was an lvalue adjustment, add it as a separate conversion.
4787 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4788 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4789 ImplicitConversionSequence LvalueICS;
4790 LvalueICS.setStandard();
4791 LvalueICS.Standard.setAsIdentityConversion();
4792 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4793 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004794 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00004795 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004796
4797 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00004798 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004799 DeclAccessPair dap;
Richard Smithf032001b2013-06-20 02:18:31 +00004800 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
4801 AddZeroInitializationStep(Entity.getType());
4802 } else if (Initializer->getType() == Context.OverloadTy &&
4803 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
4804 false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004805 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004806 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004807 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00004808 } else {
Richard Smithaaa0ec42013-09-21 21:19:19 +00004809 AddConversionSequenceStep(ICS, Entity.getType(), TopLevelOfInitList);
John McCallfa272342011-06-16 23:24:51 +00004810
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004811 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004812 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004813}
4814
4815InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004816 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004817 StepEnd = Steps.end();
4818 Step != StepEnd; ++Step)
4819 Step->Destroy();
4820}
4821
4822//===----------------------------------------------------------------------===//
4823// Perform initialization
4824//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004825static Sema::AssignmentAction
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00004826getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004827 switch(Entity.getKind()) {
4828 case InitializedEntity::EK_Variable:
4829 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004830 case InitializedEntity::EK_Exception:
4831 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004832 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00004833 return Sema::AA_Initializing;
4834
4835 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004836 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00004837 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4838 return Sema::AA_Sending;
4839
Douglas Gregore1314a62009-12-18 05:02:21 +00004840 return Sema::AA_Passing;
4841
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00004842 case InitializedEntity::EK_Parameter_CF_Audited:
4843 if (Entity.getDecl() &&
4844 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4845 return Sema::AA_Sending;
4846
4847 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
4848
Douglas Gregore1314a62009-12-18 05:02:21 +00004849 case InitializedEntity::EK_Result:
4850 return Sema::AA_Returning;
4851
Douglas Gregore1314a62009-12-18 05:02:21 +00004852 case InitializedEntity::EK_Temporary:
Fariborz Jahanian14e95412013-07-11 19:13:34 +00004853 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00004854 // FIXME: Can we tell apart casting vs. converting?
4855 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004856
Douglas Gregore1314a62009-12-18 05:02:21 +00004857 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004858 case InitializedEntity::EK_ArrayElement:
4859 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004860 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004861 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004862 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004863 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00004864 return Sema::AA_Initializing;
4865 }
4866
David Blaikie8a40f702012-01-17 06:56:22 +00004867 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00004868}
4869
Richard Smith27874d62013-01-08 00:08:23 +00004870/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor95562572010-04-24 23:45:46 +00004871/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004872static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004873 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00004874 case InitializedEntity::EK_ArrayElement:
4875 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004876 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004877 case InitializedEntity::EK_New:
4878 case InitializedEntity::EK_Variable:
4879 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004880 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004881 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004882 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00004883 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004884 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004885 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004886 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00004887 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004888
Douglas Gregore1314a62009-12-18 05:02:21 +00004889 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004890 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregore1314a62009-12-18 05:02:21 +00004891 case InitializedEntity::EK_Temporary:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00004892 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00004893 return true;
4894 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004895
Douglas Gregore1314a62009-12-18 05:02:21 +00004896 llvm_unreachable("missed an InitializedEntity kind?");
4897}
4898
Douglas Gregor95562572010-04-24 23:45:46 +00004899/// \brief Whether the given entity, when initialized with an object
4900/// created for that initialization, requires destruction.
4901static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4902 switch (Entity.getKind()) {
Douglas Gregor95562572010-04-24 23:45:46 +00004903 case InitializedEntity::EK_Result:
4904 case InitializedEntity::EK_New:
4905 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004906 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00004907 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004908 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004909 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004910 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor95562572010-04-24 23:45:46 +00004911 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004912
Richard Smith27874d62013-01-08 00:08:23 +00004913 case InitializedEntity::EK_Member:
Douglas Gregor95562572010-04-24 23:45:46 +00004914 case InitializedEntity::EK_Variable:
4915 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004916 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor95562572010-04-24 23:45:46 +00004917 case InitializedEntity::EK_Temporary:
4918 case InitializedEntity::EK_ArrayElement:
4919 case InitializedEntity::EK_Exception:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004920 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00004921 case InitializedEntity::EK_RelatedResult:
Douglas Gregor95562572010-04-24 23:45:46 +00004922 return true;
4923 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004924
4925 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00004926}
4927
Richard Smithc620f552011-10-19 16:55:56 +00004928/// \brief Look for copy and move constructors and constructor templates, for
4929/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4930static void LookupCopyAndMoveConstructors(Sema &S,
4931 OverloadCandidateSet &CandidateSet,
4932 CXXRecordDecl *Class,
4933 Expr *CurInitExpr) {
David Blaikieff7d47a2012-12-19 00:45:41 +00004934 DeclContext::lookup_result R = S.LookupConstructors(Class);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004935 // The container holding the constructors can under certain conditions
4936 // be changed while iterating (e.g. because of deserialization).
4937 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00004938 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00004939 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004940 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4941 NamedDecl *D = *CI;
Craig Topperc3ec1492014-05-26 06:22:03 +00004942 CXXConstructorDecl *Constructor = nullptr;
Richard Smithc620f552011-10-19 16:55:56 +00004943
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004944 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smithc620f552011-10-19 16:55:56 +00004945 // Handle copy/moveconstructors, only.
4946 if (!Constructor || Constructor->isInvalidDecl() ||
4947 !Constructor->isCopyOrMoveConstructor() ||
4948 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4949 continue;
4950
4951 DeclAccessPair FoundDecl
4952 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4953 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004954 CurInitExpr, CandidateSet);
Richard Smithc620f552011-10-19 16:55:56 +00004955 continue;
4956 }
4957
4958 // Handle constructor templates.
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004959 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smithc620f552011-10-19 16:55:56 +00004960 if (ConstructorTmpl->isInvalidDecl())
4961 continue;
4962
4963 Constructor = cast<CXXConstructorDecl>(
4964 ConstructorTmpl->getTemplatedDecl());
4965 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4966 continue;
4967
4968 // FIXME: Do we need to limit this to copy-constructor-like
4969 // candidates?
4970 DeclAccessPair FoundDecl
4971 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
Craig Topperc3ec1492014-05-26 06:22:03 +00004972 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004973 CurInitExpr, CandidateSet, true);
Richard Smithc620f552011-10-19 16:55:56 +00004974 }
4975}
4976
4977/// \brief Get the location at which initialization diagnostics should appear.
4978static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4979 Expr *Initializer) {
4980 switch (Entity.getKind()) {
4981 case InitializedEntity::EK_Result:
4982 return Entity.getReturnLoc();
4983
4984 case InitializedEntity::EK_Exception:
4985 return Entity.getThrowLoc();
4986
4987 case InitializedEntity::EK_Variable:
4988 return Entity.getDecl()->getLocation();
4989
Douglas Gregor19666fb2012-02-15 16:57:26 +00004990 case InitializedEntity::EK_LambdaCapture:
4991 return Entity.getCaptureLoc();
4992
Richard Smithc620f552011-10-19 16:55:56 +00004993 case InitializedEntity::EK_ArrayElement:
4994 case InitializedEntity::EK_Member:
4995 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004996 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithc620f552011-10-19 16:55:56 +00004997 case InitializedEntity::EK_Temporary:
4998 case InitializedEntity::EK_New:
4999 case InitializedEntity::EK_Base:
5000 case InitializedEntity::EK_Delegating:
5001 case InitializedEntity::EK_VectorElement:
5002 case InitializedEntity::EK_ComplexElement:
5003 case InitializedEntity::EK_BlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005004 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005005 case InitializedEntity::EK_RelatedResult:
Richard Smithc620f552011-10-19 16:55:56 +00005006 return Initializer->getLocStart();
5007 }
5008 llvm_unreachable("missed an InitializedEntity kind?");
5009}
5010
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005011/// \brief Make a (potentially elidable) temporary copy of the object
5012/// provided by the given initializer by calling the appropriate copy
5013/// constructor.
5014///
5015/// \param S The Sema object used for type-checking.
5016///
Abramo Bagnara92141d22011-01-27 19:55:10 +00005017/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005018/// the type of the initializer expression or a superclass thereof.
5019///
James Dennett634962f2012-06-14 21:40:34 +00005020/// \param Entity The entity being initialized.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005021///
5022/// \param CurInit The initializer expression.
5023///
5024/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5025/// is permitted in C++03 (but not C++0x) when binding a reference to
5026/// an rvalue.
5027///
5028/// \returns An expression that copies the initializer expression into
5029/// a temporary object, or an error expression if a copy could not be
5030/// created.
John McCalldadc5752010-08-24 06:29:42 +00005031static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005032 QualType T,
5033 const InitializedEntity &Entity,
5034 ExprResult CurInit,
5035 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00005036 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00005037 Expr *CurInitExpr = (Expr *)CurInit.get();
Craig Topperc3ec1492014-05-26 06:22:03 +00005038 CXXRecordDecl *Class = nullptr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005039 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005040 Class = cast<CXXRecordDecl>(Record->getDecl());
5041 if (!Class)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005042 return CurInit;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005043
Douglas Gregor5d369002011-01-21 18:05:27 +00005044 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005045 // When certain criteria are met, an implementation is allowed to
5046 // omit the copy/move construction of a class object, even if the
5047 // copy/move constructor and/or destructor for the object have
5048 // side effects. [...]
5049 // - when a temporary class object that has not been bound to a
5050 // reference (12.2) would be copied/moved to a class object
5051 // with the same cv-unqualified type, the copy/move operation
5052 // can be omitted by constructing the temporary object
5053 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005054 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005055 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00005056 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005057 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00005058 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00005059 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smithc620f552011-10-19 16:55:56 +00005060 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00005061
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005062 // Make sure that the type we are copying is complete.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005063 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005064 return CurInit;
Douglas Gregord5c231e2010-04-24 21:09:25 +00005065
Douglas Gregorf282a762011-01-21 19:38:21 +00005066 // Perform overload resolution using the class's copy/move constructors.
Richard Smithc620f552011-10-19 16:55:56 +00005067 // Only consider constructors and constructor templates. Per
5068 // C++0x [dcl.init]p16, second bullet to class types, this initialization
5069 // is direct-initialization.
Richard Smith100b24a2014-04-17 01:52:14 +00005070 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smithc620f552011-10-19 16:55:56 +00005071 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005072
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005073 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5074
Douglas Gregore1314a62009-12-18 05:02:21 +00005075 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00005076 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005077 case OR_Success:
5078 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005079
Douglas Gregore1314a62009-12-18 05:02:21 +00005080 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005081 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
5082 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
5083 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005084 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005085 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005086 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005087 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00005088 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005089 return CurInit;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005090
Douglas Gregore1314a62009-12-18 05:02:21 +00005091 case OR_Ambiguous:
5092 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005093 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005094 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005095 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallfaf5fb42010-08-26 23:41:50 +00005096 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005097
Douglas Gregore1314a62009-12-18 05:02:21 +00005098 case OR_Deleted:
5099 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005100 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005101 << CurInitExpr->getSourceRange();
Richard Smith852265f2012-03-30 20:53:28 +00005102 S.NoteDeletedFunction(Best->Function);
John McCallfaf5fb42010-08-26 23:41:50 +00005103 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005104 }
5105
Douglas Gregor5ab11652010-04-17 22:01:05 +00005106 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramerf0623432012-08-23 22:51:59 +00005107 SmallVector<Expr*, 8> ConstructorArgs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005108 CurInit.get(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005109
Anders Carlssona01874b2010-04-21 18:47:17 +00005110 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005111 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005112
5113 if (IsExtraneousCopy) {
5114 // If this is a totally extraneous copy for C++03 reference
5115 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00005116 // expression. We don't generate an (elided) copy operation here
5117 // because doing so would require us to pass down a flag to avoid
5118 // infinite recursion, where each step adds another extraneous,
5119 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005120
Douglas Gregor30b52772010-04-18 07:57:34 +00005121 // Instantiate the default arguments of any extra parameters in
5122 // the selected copy constructor, as if we were going to create a
5123 // proper call to the copy constructor.
5124 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5125 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5126 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005127 diag::err_call_incomplete_argument))
Douglas Gregor30b52772010-04-18 07:57:34 +00005128 break;
5129
5130 // Build the default argument expression; we don't actually care
5131 // if this succeeds or not, because this routine will complain
5132 // if there was a problem.
5133 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5134 }
5135
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005136 return CurInitExpr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005137 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005138
Douglas Gregor5ab11652010-04-17 22:01:05 +00005139 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005140 // constructor call (we might have derived-to-base conversions, or
5141 // the copy constructor may have default arguments).
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005142 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005143 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005144
Douglas Gregord0ace022010-04-25 00:55:24 +00005145 // Actually perform the constructor call.
5146 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005147 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005148 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005149 /*ListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005150 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005151 CXXConstructExpr::CK_Complete,
5152 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005153
Douglas Gregord0ace022010-04-25 00:55:24 +00005154 // If we're supposed to bind temporaries, do so.
5155 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005156 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005157 return CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00005158}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005159
Richard Smithc620f552011-10-19 16:55:56 +00005160/// \brief Check whether elidable copy construction for binding a reference to
5161/// a temporary would have succeeded if we were building in C++98 mode, for
5162/// -Wc++98-compat.
5163static void CheckCXX98CompatAccessibleCopy(Sema &S,
5164 const InitializedEntity &Entity,
5165 Expr *CurInitExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005166 assert(S.getLangOpts().CPlusPlus11);
Richard Smithc620f552011-10-19 16:55:56 +00005167
5168 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5169 if (!Record)
5170 return;
5171
5172 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005173 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
Richard Smithc620f552011-10-19 16:55:56 +00005174 return;
5175
5176 // Find constructors which would have been considered.
Richard Smith100b24a2014-04-17 01:52:14 +00005177 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smithc620f552011-10-19 16:55:56 +00005178 LookupCopyAndMoveConstructors(
5179 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
5180
5181 // Perform overload resolution.
5182 OverloadCandidateSet::iterator Best;
5183 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
5184
5185 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5186 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5187 << CurInitExpr->getSourceRange();
5188
5189 switch (OR) {
5190 case OR_Success:
5191 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCall5dadb652012-04-07 03:04:20 +00005192 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smithc620f552011-10-19 16:55:56 +00005193 // FIXME: Check default arguments as far as that's possible.
5194 break;
5195
5196 case OR_No_Viable_Function:
5197 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005198 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005199 break;
5200
5201 case OR_Ambiguous:
5202 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005203 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005204 break;
5205
5206 case OR_Deleted:
5207 S.Diag(Loc, Diag);
Richard Smith852265f2012-03-30 20:53:28 +00005208 S.NoteDeletedFunction(Best->Function);
Richard Smithc620f552011-10-19 16:55:56 +00005209 break;
5210 }
5211}
5212
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005213void InitializationSequence::PrintInitLocationNote(Sema &S,
5214 const InitializedEntity &Entity) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005215 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005216 if (Entity.getDecl()->getLocation().isInvalid())
5217 return;
5218
5219 if (Entity.getDecl()->getDeclName())
5220 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5221 << Entity.getDecl()->getDeclName();
5222 else
5223 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5224 }
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005225 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5226 Entity.getMethodDecl())
5227 S.Diag(Entity.getMethodDecl()->getLocation(),
5228 diag::note_method_return_type_change)
5229 << Entity.getMethodDecl()->getDeclName();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005230}
5231
Sebastian Redl112aa822011-07-14 19:07:55 +00005232static bool isReferenceBinding(const InitializationSequence::Step &s) {
5233 return s.Kind == InitializationSequence::SK_BindReference ||
5234 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
5235}
5236
Jordan Rose6c0505e2013-05-06 16:48:12 +00005237/// Returns true if the parameters describe a constructor initialization of
5238/// an explicit temporary object, e.g. "Point(x, y)".
5239static bool isExplicitTemporary(const InitializedEntity &Entity,
5240 const InitializationKind &Kind,
5241 unsigned NumArgs) {
5242 switch (Entity.getKind()) {
5243 case InitializedEntity::EK_Temporary:
5244 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005245 case InitializedEntity::EK_RelatedResult:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005246 break;
5247 default:
5248 return false;
5249 }
5250
5251 switch (Kind.getKind()) {
5252 case InitializationKind::IK_DirectList:
5253 return true;
5254 // FIXME: Hack to work around cast weirdness.
5255 case InitializationKind::IK_Direct:
5256 case InitializationKind::IK_Value:
5257 return NumArgs != 1;
5258 default:
5259 return false;
5260 }
5261}
5262
Sebastian Redled2e5322011-12-22 14:44:04 +00005263static ExprResult
5264PerformConstructorInitialization(Sema &S,
5265 const InitializedEntity &Entity,
5266 const InitializationKind &Kind,
5267 MultiExprArg Args,
5268 const InitializationSequence::Step& Step,
Richard Smithd59b8322012-12-19 01:39:02 +00005269 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005270 bool IsListInitialization,
5271 SourceLocation LBraceLoc,
5272 SourceLocation RBraceLoc) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005273 unsigned NumArgs = Args.size();
5274 CXXConstructorDecl *Constructor
5275 = cast<CXXConstructorDecl>(Step.Function.Function);
5276 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5277
5278 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00005279 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redled2e5322011-12-22 14:44:04 +00005280 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5281 ? Kind.getEqualLoc()
5282 : Kind.getLocation();
5283
5284 if (Kind.getKind() == InitializationKind::IK_Default) {
5285 // Force even a trivial, implicit default constructor to be
5286 // semantically checked. We do this explicitly because we don't build
5287 // the definition for completely trivial constructors.
Matt Beaumont-Gay47ff1222012-02-24 08:37:56 +00005288 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redled2e5322011-12-22 14:44:04 +00005289 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregorf704ade2012-02-24 07:48:37 +00005290 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redled2e5322011-12-22 14:44:04 +00005291 S.DefineImplicitDefaultConstructor(Loc, Constructor);
5292 }
5293
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005294 ExprResult CurInit((Expr *)nullptr);
Sebastian Redled2e5322011-12-22 14:44:04 +00005295
Douglas Gregor6073dca2012-02-24 23:56:31 +00005296 // C++ [over.match.copy]p1:
5297 // - When initializing a temporary to be bound to the first parameter
5298 // of a constructor that takes a reference to possibly cv-qualified
5299 // T as its first argument, called with a single argument in the
5300 // context of direct-initialization, explicit conversion functions
5301 // are also considered.
5302 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
5303 Args.size() == 1 &&
5304 Constructor->isCopyOrMoveConstructor();
5305
Sebastian Redled2e5322011-12-22 14:44:04 +00005306 // Determine the arguments required to actually perform the constructor
5307 // call.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005308 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005309 Loc, ConstructorArgs,
Richard Smith6b216962013-02-05 05:52:24 +00005310 AllowExplicitConv,
5311 IsListInitialization))
Sebastian Redled2e5322011-12-22 14:44:04 +00005312 return ExprError();
5313
5314
Jordan Rose6c0505e2013-05-06 16:48:12 +00005315 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005316 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedmanfa0df832012-02-02 03:46:19 +00005317 S.MarkFunctionReferenced(Loc, Constructor);
Richard Smith22262ab2013-05-04 06:44:46 +00005318 if (S.DiagnoseUseOfDecl(Constructor, Loc))
5319 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005320
5321 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5322 if (!TSInfo)
5323 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005324 SourceRange ParenOrBraceRange =
5325 (Kind.getKind() == InitializationKind::IK_DirectList)
5326 ? SourceRange(LBraceLoc, RBraceLoc)
5327 : Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005328
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005329 CurInit = new (S.Context) CXXTemporaryObjectExpr(
5330 S.Context, Constructor, TSInfo, ConstructorArgs, ParenOrBraceRange,
5331 HadMultipleCandidates, IsListInitialization,
5332 ConstructorInitRequiresZeroInit);
Sebastian Redled2e5322011-12-22 14:44:04 +00005333 } else {
5334 CXXConstructExpr::ConstructionKind ConstructKind =
5335 CXXConstructExpr::CK_Complete;
5336
5337 if (Entity.getKind() == InitializedEntity::EK_Base) {
5338 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5339 CXXConstructExpr::CK_VirtualBase :
5340 CXXConstructExpr::CK_NonVirtualBase;
5341 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5342 ConstructKind = CXXConstructExpr::CK_Delegating;
5343 }
5344
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005345 // Only get the parenthesis or brace range if it is a list initialization or
5346 // direct construction.
5347 SourceRange ParenOrBraceRange;
5348 if (IsListInitialization)
5349 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
5350 else if (Kind.getKind() == InitializationKind::IK_Direct)
5351 ParenOrBraceRange = Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005352
5353 // If the entity allows NRVO, mark the construction as elidable
5354 // unconditionally.
5355 if (Entity.allowsNRVO())
5356 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5357 Constructor, /*Elidable=*/true,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005358 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005359 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005360 IsListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005361 ConstructorInitRequiresZeroInit,
5362 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005363 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00005364 else
5365 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5366 Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005367 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005368 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005369 IsListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005370 ConstructorInitRequiresZeroInit,
5371 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005372 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00005373 }
5374 if (CurInit.isInvalid())
5375 return ExprError();
5376
5377 // Only check access if all of that succeeded.
5378 S.CheckConstructorAccess(Loc, Constructor, Entity,
5379 Step.Function.FoundDecl.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00005380 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5381 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005382
5383 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005384 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redled2e5322011-12-22 14:44:04 +00005385
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005386 return CurInit;
Sebastian Redled2e5322011-12-22 14:44:04 +00005387}
5388
Richard Smitheb3cad52012-06-04 22:27:30 +00005389/// Determine whether the specified InitializedEntity definitely has a lifetime
5390/// longer than the current full-expression. Conservatively returns false if
5391/// it's unclear.
5392static bool
5393InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5394 const InitializedEntity *Top = &Entity;
5395 while (Top->getParent())
5396 Top = Top->getParent();
5397
5398 switch (Top->getKind()) {
5399 case InitializedEntity::EK_Variable:
5400 case InitializedEntity::EK_Result:
5401 case InitializedEntity::EK_Exception:
5402 case InitializedEntity::EK_Member:
5403 case InitializedEntity::EK_New:
5404 case InitializedEntity::EK_Base:
5405 case InitializedEntity::EK_Delegating:
5406 return true;
5407
5408 case InitializedEntity::EK_ArrayElement:
5409 case InitializedEntity::EK_VectorElement:
5410 case InitializedEntity::EK_BlockElement:
5411 case InitializedEntity::EK_ComplexElement:
5412 // Could not determine what the full initialization is. Assume it might not
5413 // outlive the full-expression.
5414 return false;
5415
5416 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005417 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smitheb3cad52012-06-04 22:27:30 +00005418 case InitializedEntity::EK_Temporary:
5419 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005420 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005421 case InitializedEntity::EK_RelatedResult:
Richard Smitheb3cad52012-06-04 22:27:30 +00005422 // The entity being initialized might not outlive the full-expression.
5423 return false;
5424 }
5425
5426 llvm_unreachable("unknown entity kind");
5427}
5428
Richard Smithe6c01442013-06-05 00:46:14 +00005429/// Determine the declaration which an initialized entity ultimately refers to,
5430/// for the purpose of lifetime-extending a temporary bound to a reference in
5431/// the initialization of \p Entity.
David Majnemerdaff3702014-05-01 17:50:17 +00005432static const InitializedEntity *getEntityForTemporaryLifetimeExtension(
5433 const InitializedEntity *Entity,
Craig Topperc3ec1492014-05-26 06:22:03 +00005434 const InitializedEntity *FallbackDecl = nullptr) {
Richard Smithe6c01442013-06-05 00:46:14 +00005435 // C++11 [class.temporary]p5:
David Majnemerdaff3702014-05-01 17:50:17 +00005436 switch (Entity->getKind()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005437 case InitializedEntity::EK_Variable:
5438 // The temporary [...] persists for the lifetime of the reference
David Majnemerdaff3702014-05-01 17:50:17 +00005439 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00005440
5441 case InitializedEntity::EK_Member:
5442 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00005443 if (Entity->getParent())
5444 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5445 Entity);
Richard Smithe6c01442013-06-05 00:46:14 +00005446
5447 // except:
5448 // -- A temporary bound to a reference member in a constructor's
5449 // ctor-initializer persists until the constructor exits.
David Majnemerdaff3702014-05-01 17:50:17 +00005450 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00005451
5452 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005453 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithe6c01442013-06-05 00:46:14 +00005454 // -- A temporary bound to a reference parameter in a function call
5455 // persists until the completion of the full-expression containing
5456 // the call.
5457 case InitializedEntity::EK_Result:
5458 // -- The lifetime of a temporary bound to the returned value in a
5459 // function return statement is not extended; the temporary is
5460 // destroyed at the end of the full-expression in the return statement.
5461 case InitializedEntity::EK_New:
5462 // -- A temporary bound to a reference in a new-initializer persists
5463 // until the completion of the full-expression containing the
5464 // new-initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00005465 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005466
5467 case InitializedEntity::EK_Temporary:
5468 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005469 case InitializedEntity::EK_RelatedResult:
Richard Smithe6c01442013-06-05 00:46:14 +00005470 // We don't yet know the storage duration of the surrounding temporary.
5471 // Assume it's got full-expression duration for now, it will patch up our
5472 // storage duration if that's not correct.
David Majnemerdaff3702014-05-01 17:50:17 +00005473 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005474
5475 case InitializedEntity::EK_ArrayElement:
5476 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00005477 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5478 FallbackDecl);
Richard Smithe6c01442013-06-05 00:46:14 +00005479
5480 case InitializedEntity::EK_Base:
5481 case InitializedEntity::EK_Delegating:
5482 // We can reach this case for aggregate initialization in a constructor:
5483 // struct A { int &&r; };
5484 // struct B : A { B() : A{0} {} };
5485 // In this case, use the innermost field decl as the context.
5486 return FallbackDecl;
5487
5488 case InitializedEntity::EK_BlockElement:
5489 case InitializedEntity::EK_LambdaCapture:
5490 case InitializedEntity::EK_Exception:
5491 case InitializedEntity::EK_VectorElement:
5492 case InitializedEntity::EK_ComplexElement:
David Majnemerdaff3702014-05-01 17:50:17 +00005493 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005494 }
Benjamin Kramercabc8822013-06-05 15:37:50 +00005495 llvm_unreachable("unknown entity kind");
Richard Smithe6c01442013-06-05 00:46:14 +00005496}
5497
David Majnemerdaff3702014-05-01 17:50:17 +00005498static void performLifetimeExtension(Expr *Init,
5499 const InitializedEntity *ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005500
5501/// Update a glvalue expression that is used as the initializer of a reference
5502/// to note that its lifetime is extended.
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005503/// \return \c true if any temporary had its lifetime extended.
David Majnemerdaff3702014-05-01 17:50:17 +00005504static bool
5505performReferenceExtension(Expr *Init,
5506 const InitializedEntity *ExtendingEntity) {
Richard Smithe6c01442013-06-05 00:46:14 +00005507 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5508 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
5509 // This is just redundant braces around an initializer. Step over it.
5510 Init = ILE->getInit(0);
5511 }
5512 }
5513
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005514 // Walk past any constructs which we can lifetime-extend across.
5515 Expr *Old;
5516 do {
5517 Old = Init;
5518
5519 // Step over any subobject adjustments; we may have a materialized
5520 // temporary inside them.
5521 SmallVector<const Expr *, 2> CommaLHSs;
5522 SmallVector<SubobjectAdjustment, 2> Adjustments;
5523 Init = const_cast<Expr *>(
5524 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5525
5526 // Per current approach for DR1376, look through casts to reference type
5527 // when performing lifetime extension.
5528 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
5529 if (CE->getSubExpr()->isGLValue())
5530 Init = CE->getSubExpr();
5531
5532 // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
5533 // It's unclear if binding a reference to that xvalue extends the array
5534 // temporary.
5535 } while (Init != Old);
5536
Richard Smithe6c01442013-06-05 00:46:14 +00005537 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
5538 // Update the storage duration of the materialized temporary.
5539 // FIXME: Rebuild the expression instead of mutating it.
David Majnemerdaff3702014-05-01 17:50:17 +00005540 ME->setExtendingDecl(ExtendingEntity->getDecl(),
5541 ExtendingEntity->allocateManglingNumber());
5542 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005543 return true;
Richard Smithe6c01442013-06-05 00:46:14 +00005544 }
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005545
5546 return false;
Richard Smithe6c01442013-06-05 00:46:14 +00005547}
5548
5549/// Update a prvalue expression that is going to be materialized as a
5550/// lifetime-extended temporary.
David Majnemerdaff3702014-05-01 17:50:17 +00005551static void performLifetimeExtension(Expr *Init,
5552 const InitializedEntity *ExtendingEntity) {
Richard Smithe6c01442013-06-05 00:46:14 +00005553 // Dig out the expression which constructs the extended temporary.
5554 SmallVector<const Expr *, 2> CommaLHSs;
5555 SmallVector<SubobjectAdjustment, 2> Adjustments;
5556 Init = const_cast<Expr *>(
5557 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5558
Richard Smith736a9472013-06-12 20:42:33 +00005559 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
5560 Init = BTE->getSubExpr();
5561
Richard Smithcc1b96d2013-06-12 22:31:48 +00005562 if (CXXStdInitializerListExpr *ILE =
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005563 dyn_cast<CXXStdInitializerListExpr>(Init)) {
David Majnemerdaff3702014-05-01 17:50:17 +00005564 performReferenceExtension(ILE->getSubExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005565 return;
5566 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00005567
Richard Smithe6c01442013-06-05 00:46:14 +00005568 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00005569 if (ILE->getType()->isArrayType()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005570 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
David Majnemerdaff3702014-05-01 17:50:17 +00005571 performLifetimeExtension(ILE->getInit(I), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005572 return;
5573 }
5574
Richard Smithcc1b96d2013-06-12 22:31:48 +00005575 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005576 assert(RD->isAggregate() && "aggregate init on non-aggregate");
5577
5578 // If we lifetime-extend a braced initializer which is initializing an
5579 // aggregate, and that aggregate contains reference members which are
5580 // bound to temporaries, those temporaries are also lifetime-extended.
5581 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
5582 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00005583 performReferenceExtension(ILE->getInit(0), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005584 else {
5585 unsigned Index = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005586 for (const auto *I : RD->fields()) {
Richard Smith0bca59d2013-07-01 06:08:20 +00005587 if (Index >= ILE->getNumInits())
5588 break;
Richard Smithe6c01442013-06-05 00:46:14 +00005589 if (I->isUnnamedBitfield())
5590 continue;
Richard Smith8d7f11d2013-06-27 22:54:33 +00005591 Expr *SubInit = ILE->getInit(Index);
Richard Smithe6c01442013-06-05 00:46:14 +00005592 if (I->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00005593 performReferenceExtension(SubInit, ExtendingEntity);
Richard Smith8d7f11d2013-06-27 22:54:33 +00005594 else if (isa<InitListExpr>(SubInit) ||
5595 isa<CXXStdInitializerListExpr>(SubInit))
Richard Smithe6c01442013-06-05 00:46:14 +00005596 // This may be either aggregate-initialization of a member or
5597 // initialization of a std::initializer_list object. Either way,
5598 // we should recursively lifetime-extend that initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00005599 performLifetimeExtension(SubInit, ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005600 ++Index;
5601 }
5602 }
5603 }
5604 }
5605}
5606
Richard Smithcc1b96d2013-06-12 22:31:48 +00005607static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
5608 const Expr *Init, bool IsInitializerList,
5609 const ValueDecl *ExtendingDecl) {
5610 // Warn if a field lifetime-extends a temporary.
5611 if (isa<FieldDecl>(ExtendingDecl)) {
5612 if (IsInitializerList) {
5613 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
5614 << /*at end of constructor*/true;
5615 return;
5616 }
5617
5618 bool IsSubobjectMember = false;
5619 for (const InitializedEntity *Ent = Entity.getParent(); Ent;
5620 Ent = Ent->getParent()) {
5621 if (Ent->getKind() != InitializedEntity::EK_Base) {
5622 IsSubobjectMember = true;
5623 break;
5624 }
5625 }
5626 S.Diag(Init->getExprLoc(),
5627 diag::warn_bind_ref_member_to_temporary)
5628 << ExtendingDecl << Init->getSourceRange()
5629 << IsSubobjectMember << IsInitializerList;
5630 if (IsSubobjectMember)
5631 S.Diag(ExtendingDecl->getLocation(),
5632 diag::note_ref_subobject_of_member_declared_here);
5633 else
5634 S.Diag(ExtendingDecl->getLocation(),
5635 diag::note_ref_or_ptr_member_declared_here)
5636 << /*is pointer*/false;
5637 }
5638}
5639
Richard Smithaaa0ec42013-09-21 21:19:19 +00005640static void DiagnoseNarrowingInInitList(Sema &S,
5641 const ImplicitConversionSequence &ICS,
5642 QualType PreNarrowingType,
5643 QualType EntityType,
5644 const Expr *PostInit);
5645
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005646ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005647InitializationSequence::Perform(Sema &S,
5648 const InitializedEntity &Entity,
5649 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00005650 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00005651 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00005652 if (Failed()) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005653 Diagnose(S, Entity, Kind, Args);
John McCallfaf5fb42010-08-26 23:41:50 +00005654 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005655 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005656
Sebastian Redld201edf2011-06-05 13:59:11 +00005657 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00005658 // If the declaration is a non-dependent, incomplete array type
5659 // that has an initializer, then its type will be completed once
5660 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00005661 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00005662 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00005663 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005664 if (const IncompleteArrayType *ArrayT
5665 = S.Context.getAsIncompleteArrayType(DeclType)) {
5666 // FIXME: We don't currently have the ability to accurately
5667 // compute the length of an initializer list without
5668 // performing full type-checking of the initializer list
5669 // (since we have to determine where braces are implicitly
5670 // introduced and such). So, we fall back to making the array
5671 // type a dependently-sized array type with no specified
5672 // bound.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005673 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00005674 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00005675
Douglas Gregor51e77d52009-12-10 17:56:55 +00005676 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00005677 if (DeclaratorDecl *DD = Entity.getDecl()) {
5678 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5679 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00005680 if (IncompleteArrayTypeLoc ArrayLoc =
5681 TL.getAs<IncompleteArrayTypeLoc>())
5682 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregor1b303932009-12-22 15:35:07 +00005683 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00005684 }
5685
5686 *ResultType
5687 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005688 /*NumElts=*/nullptr,
Douglas Gregor51e77d52009-12-10 17:56:55 +00005689 ArrayT->getSizeModifier(),
5690 ArrayT->getIndexTypeCVRQualifiers(),
5691 Brackets);
5692 }
5693
5694 }
5695 }
Sebastian Redla9351792012-02-11 23:51:47 +00005696 if (Kind.getKind() == InitializationKind::IK_Direct &&
5697 !Kind.isExplicitCast()) {
5698 // Rebuild the ParenListExpr.
5699 SourceRange ParenRange = Kind.getParenRange();
5700 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005701 Args);
Sebastian Redla9351792012-02-11 23:51:47 +00005702 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00005703 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregorbf138952012-04-04 04:06:51 +00005704 Kind.isExplicitCast() ||
5705 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005706 return ExprResult(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005707 }
5708
Sebastian Redld201edf2011-06-05 13:59:11 +00005709 // No steps means no initialization.
5710 if (Steps.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005711 return ExprResult((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005712
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005713 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005714 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005715 !Entity.isParameterKind()) {
Richard Smith2b349ae2012-04-19 06:58:00 +00005716 // Produce a C++98 compatibility warning if we are initializing a reference
5717 // from an initializer list. For parameters, we produce a better warning
5718 // elsewhere.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005719 Expr *Init = Args[0];
Richard Smith2b349ae2012-04-19 06:58:00 +00005720 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5721 << Init->getSourceRange();
5722 }
5723
Richard Smitheb3cad52012-06-04 22:27:30 +00005724 // Diagnose cases where we initialize a pointer to an array temporary, and the
5725 // pointer obviously outlives the temporary.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005726 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smitheb3cad52012-06-04 22:27:30 +00005727 Entity.getType()->isPointerType() &&
5728 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005729 Expr *Init = Args[0];
Richard Smitheb3cad52012-06-04 22:27:30 +00005730 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5731 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5732 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5733 << Init->getSourceRange();
5734 }
5735
Douglas Gregor1b303932009-12-22 15:35:07 +00005736 QualType DestType = Entity.getType().getNonReferenceType();
5737 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00005738 // the same as Entity.getDecl()->getType() in cases involving type merging,
5739 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00005740 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00005741 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00005742 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005743
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005744 ExprResult CurInit((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005745
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005746 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00005747 // grab the only argument out the Args and place it into the "current"
5748 // initializer.
5749 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005750 case SK_ResolveAddressOfOverloadedFunction:
5751 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005752 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005753 case SK_CastDerivedToBaseLValue:
5754 case SK_BindReference:
5755 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005756 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00005757 case SK_UserConversion:
5758 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005759 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005760 case SK_QualificationConversionRValue:
Jordan Roseb1312a52013-04-11 00:58:58 +00005761 case SK_LValueToRValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005762 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00005763 case SK_ConversionSequenceNoNarrowing:
Douglas Gregore1314a62009-12-18 05:02:21 +00005764 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00005765 case SK_UnwrapInitList:
5766 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00005767 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00005768 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00005769 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00005770 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00005771 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00005772 case SK_PassByIndirectCopyRestore:
5773 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00005774 case SK_ProduceObjCObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005775 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00005776 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005777 case SK_OCLZeroEvent: {
Douglas Gregore1314a62009-12-18 05:02:21 +00005778 assert(Args.size() == 1);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005779 CurInit = Args[0];
John Wiegley01296292011-04-08 18:41:53 +00005780 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005781 break;
John McCall34376a62010-12-04 03:47:34 +00005782 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005783
Douglas Gregore1314a62009-12-18 05:02:21 +00005784 case SK_ConstructorInitialization:
Richard Smithd86812d2012-07-05 08:39:21 +00005785 case SK_ListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00005786 case SK_ZeroInitialization:
5787 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005788 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005789
5790 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005791 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005792 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005793 for (step_iterator Step = step_begin(), StepEnd = step_end();
5794 Step != StepEnd; ++Step) {
5795 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005796 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005797
John Wiegley01296292011-04-08 18:41:53 +00005798 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005799
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005800 switch (Step->Kind) {
5801 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005802 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005803 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00005804 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +00005805 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5806 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005807 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall16df1e52010-03-30 21:47:33 +00005808 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00005809 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005810 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005811
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005812 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005813 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005814 case SK_CastDerivedToBaseLValue: {
5815 // We have a derived-to-base cast that produces either an rvalue or an
5816 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005817
John McCallcf142162010-08-07 06:22:56 +00005818 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00005819
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005820 // Casts to inaccessible base classes are allowed with C-style casts.
5821 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5822 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00005823 CurInit.get()->getLocStart(),
5824 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00005825 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00005826 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005827
Douglas Gregor88d292c2010-05-13 16:44:06 +00005828 if (S.BasePathInvolvesVirtualBase(BasePath)) {
5829 QualType T = SourceType;
5830 if (const PointerType *Pointer = T->getAs<PointerType>())
5831 T = Pointer->getPointeeType();
5832 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00005833 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00005834 cast<CXXRecordDecl>(RecordTy->getDecl()));
5835 }
5836
John McCall2536c6d2010-08-25 10:28:54 +00005837 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005838 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005839 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005840 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005841 VK_XValue :
5842 VK_RValue);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005843 CurInit =
5844 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
5845 CurInit.get(), &BasePath, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005846 break;
5847 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005848
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005849 case SK_BindReference:
John McCalld25db7e2013-05-06 21:39:12 +00005850 // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
5851 if (CurInit.get()->refersToBitField()) {
5852 // We don't necessarily have an unambiguous source bit-field.
5853 FieldDecl *BitField = CurInit.get()->getSourceBitField();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005854 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00005855 << Entity.getType().isVolatileQualified()
John McCalld25db7e2013-05-06 21:39:12 +00005856 << (BitField ? BitField->getDeclName() : DeclarationName())
Craig Topperc3ec1492014-05-26 06:22:03 +00005857 << (BitField != nullptr)
John Wiegley01296292011-04-08 18:41:53 +00005858 << CurInit.get()->getSourceRange();
John McCalld25db7e2013-05-06 21:39:12 +00005859 if (BitField)
5860 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5861
John McCallfaf5fb42010-08-26 23:41:50 +00005862 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005863 }
Anders Carlssona91be642010-01-29 02:47:33 +00005864
John Wiegley01296292011-04-08 18:41:53 +00005865 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00005866 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00005867 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5868 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00005869 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005870 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00005871 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00005872 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005873
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005874 // Reference binding does not have any corresponding ASTs.
5875
5876 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00005877 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00005878 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00005879
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005880 // Even though we didn't materialize a temporary, the binding may still
5881 // extend the lifetime of a temporary. This happens if we bind a reference
5882 // to the result of a cast to reference type.
David Majnemerdaff3702014-05-01 17:50:17 +00005883 if (const InitializedEntity *ExtendingEntity =
5884 getEntityForTemporaryLifetimeExtension(&Entity))
5885 if (performReferenceExtension(CurInit.get(), ExtendingEntity))
5886 warnOnLifetimeExtension(S, Entity, CurInit.get(),
5887 /*IsInitializerList=*/false,
5888 ExtendingEntity->getDecl());
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005889
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005890 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00005891
Richard Smithe6c01442013-06-05 00:46:14 +00005892 case SK_BindReferenceToTemporary: {
Jordan Roseb1312a52013-04-11 00:58:58 +00005893 // Make sure the "temporary" is actually an rvalue.
5894 assert(CurInit.get()->isRValue() && "not a temporary");
5895
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005896 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00005897 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00005898 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005899
Douglas Gregorfe314812011-06-21 17:03:29 +00005900 // Materialize the temporary into memory.
Richard Smith736a9472013-06-12 20:42:33 +00005901 MaterializeTemporaryExpr *MTE = new (S.Context) MaterializeTemporaryExpr(
Richard Smithe6c01442013-06-05 00:46:14 +00005902 Entity.getType().getNonReferenceType(), CurInit.get(),
David Majnemerdaff3702014-05-01 17:50:17 +00005903 Entity.getType()->isLValueReferenceType());
5904
5905 // Maybe lifetime-extend the temporary's subobjects to match the
5906 // entity's lifetime.
5907 if (const InitializedEntity *ExtendingEntity =
5908 getEntityForTemporaryLifetimeExtension(&Entity))
5909 if (performReferenceExtension(MTE, ExtendingEntity))
5910 warnOnLifetimeExtension(S, Entity, CurInit.get(), /*IsInitializerList=*/false,
5911 ExtendingEntity->getDecl());
Douglas Gregor58df5092011-06-22 16:12:01 +00005912
5913 // If we're binding to an Objective-C object that has lifetime, we
Richard Smith736a9472013-06-12 20:42:33 +00005914 // need cleanups. Likewise if we're extending this temporary to automatic
5915 // storage duration -- we need to register its cleanup during the
5916 // full-expression's cleanups.
5917 if ((S.getLangOpts().ObjCAutoRefCount &&
5918 MTE->getType()->isObjCLifetimeType()) ||
5919 (MTE->getStorageDuration() == SD_Automatic &&
5920 MTE->getType().isDestructedType()))
Douglas Gregor58df5092011-06-22 16:12:01 +00005921 S.ExprNeedsCleanups = true;
Richard Smith736a9472013-06-12 20:42:33 +00005922
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005923 CurInit = MTE;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005924 break;
Richard Smithe6c01442013-06-05 00:46:14 +00005925 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005926
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005927 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005928 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005929 /*IsExtraneousCopy=*/true);
5930 break;
5931
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005932 case SK_UserConversion: {
5933 // We have a user-defined conversion that invokes either a constructor
5934 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00005935 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00005936 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00005937 FunctionDecl *Fn = Step->Function.Function;
5938 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005939 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00005940 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00005941 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005942 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00005943 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley01296292011-04-08 18:41:53 +00005944 SourceLocation Loc = CurInit.get()->getLocStart();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005945 CurInit.get(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00005946
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005947 // Determine the arguments required to actually perform the constructor
5948 // call.
John Wiegley01296292011-04-08 18:41:53 +00005949 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005950 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00005951 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005952 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005953 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005954
Richard Smithb24f0672012-02-11 19:22:50 +00005955 // Build an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005956 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005957 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005958 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005959 /*ListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005960 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005961 CXXConstructExpr::CK_Complete,
5962 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005963 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005964 return ExprError();
John McCall760af172010-02-01 03:16:54 +00005965
Anders Carlssona01874b2010-04-21 18:47:17 +00005966 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00005967 FoundFn.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00005968 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5969 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005970
John McCalle3027922010-08-25 11:45:40 +00005971 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00005972 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5973 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5974 S.IsDerivedFrom(SourceType, Class))
5975 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005976
Douglas Gregor95562572010-04-24 23:45:46 +00005977 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005978 } else {
5979 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00005980 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Craig Topperc3ec1492014-05-26 06:22:03 +00005981 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
John McCalla0296f72010-03-19 07:35:19 +00005982 FoundFn);
Richard Smith22262ab2013-05-04 06:44:46 +00005983 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5984 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005985
5986 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005987 // derived-to-base conversion? I believe the answer is "no", because
5988 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00005989 ExprResult CurInitExprRes =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005990 S.PerformObjectArgumentInitialization(CurInit.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005991 /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00005992 FoundFn, Conversion);
5993 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005994 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005995 CurInit = CurInitExprRes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005996
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005997 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005998 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5999 HadMultipleCandidates);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006000 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00006001 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006002
John McCalle3027922010-08-25 11:45:40 +00006003 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006004
Alp Toker314cc812014-01-25 16:55:45 +00006005 CreatedObject = Conversion->getReturnType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006006 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006007
Sebastian Redl112aa822011-07-14 19:07:55 +00006008 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00006009 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
6010
6011 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00006012 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00006013 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006014 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00006015 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00006016 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00006017 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00006018 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith22262ab2013-05-04 06:44:46 +00006019 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
6020 return ExprError();
Douglas Gregor95562572010-04-24 23:45:46 +00006021 }
6022 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006023
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006024 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
6025 CastKind, CurInit.get(), nullptr,
6026 CurInit.get()->getValueKind());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00006027 if (MaybeBindToTemp)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006028 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00006029 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006030 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006031 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006032 break;
6033 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006034
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006035 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006036 case SK_QualificationConversionXValue:
6037 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006038 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00006039 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006040 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006041 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006042 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006043 VK_XValue :
6044 VK_RValue);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006045 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006046 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006047 }
6048
Jordan Roseb1312a52013-04-11 00:58:58 +00006049 case SK_LValueToRValue: {
6050 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006051 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
6052 CK_LValueToRValue, CurInit.get(),
6053 /*BasePath=*/nullptr, VK_RValue);
Jordan Roseb1312a52013-04-11 00:58:58 +00006054 break;
6055 }
6056
Richard Smithaaa0ec42013-09-21 21:19:19 +00006057 case SK_ConversionSequence:
6058 case SK_ConversionSequenceNoNarrowing: {
6059 Sema::CheckedConversionKind CCK
John McCall31168b02011-06-15 23:02:42 +00006060 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
6061 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00006062 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00006063 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00006064 ExprResult CurInitExprRes =
6065 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00006066 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00006067 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006068 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006069 CurInit = CurInitExprRes;
Richard Smithaaa0ec42013-09-21 21:19:19 +00006070
6071 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
6072 S.getLangOpts().CPlusPlus && !CurInit.get()->isValueDependent())
6073 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
6074 CurInit.get());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006075 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00006076 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006077
Douglas Gregor51e77d52009-12-10 17:56:55 +00006078 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00006079 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smithcc1b96d2013-06-12 22:31:48 +00006080 // If we're not initializing the top-level entity, we need to create an
6081 // InitializeTemporary entity for our target type.
6082 QualType Ty = Step->Type;
6083 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl29526f02011-11-27 16:50:07 +00006084 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smithd712d0d2013-02-02 01:13:06 +00006085 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
6086 InitListChecker PerformInitList(S, InitEntity,
Richard Smithde229232013-06-06 11:41:05 +00006087 InitList, Ty, /*VerifyOnly=*/false);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006088 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00006089 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00006090
Richard Smithcc1b96d2013-06-12 22:31:48 +00006091 // Hack: We must update *ResultType if available in order to set the
6092 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
6093 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
6094 if (ResultType &&
6095 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00006096 if ((*ResultType)->isRValueReferenceType())
6097 Ty = S.Context.getRValueReferenceType(Ty);
6098 else if ((*ResultType)->isLValueReferenceType())
6099 Ty = S.Context.getLValueReferenceType(Ty,
6100 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
6101 *ResultType = Ty;
6102 }
6103
6104 InitListExpr *StructuredInitList =
6105 PerformInitList.getFullyStructuredList();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006106 CurInit.get();
Richard Smithd712d0d2013-02-02 01:13:06 +00006107 CurInit = shouldBindAsTemporary(InitEntity)
6108 ? S.MaybeBindToTemporary(StructuredInitList)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006109 : StructuredInitList;
Douglas Gregor51e77d52009-12-10 17:56:55 +00006110 break;
6111 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006112
Sebastian Redled2e5322011-12-22 14:44:04 +00006113 case SK_ListConstructorCall: {
Sebastian Redl5a41f682012-02-12 16:37:24 +00006114 // When an initializer list is passed for a parameter of type "reference
6115 // to object", we don't get an EK_Temporary entity, but instead an
6116 // EK_Parameter entity with reference type.
Sebastian Redl99f66162012-02-19 12:27:56 +00006117 // FIXME: This is a hack. What we really should do is create a user
6118 // conversion step for this case, but this makes it considerably more
6119 // complicated. For now, this will do.
Sebastian Redl5a41f682012-02-12 16:37:24 +00006120 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6121 Entity.getType().getNonReferenceType());
6122 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithd86812d2012-07-05 08:39:21 +00006123 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006124 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith2b349ae2012-04-19 06:58:00 +00006125 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
6126 << InitList->getSourceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006127 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl5a41f682012-02-12 16:37:24 +00006128 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
6129 Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006130 Kind, Arg, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006131 ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006132 /*IsListInitialization*/ true,
6133 InitList->getLBraceLoc(),
6134 InitList->getRBraceLoc());
Sebastian Redled2e5322011-12-22 14:44:04 +00006135 break;
6136 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006137
Sebastian Redl29526f02011-11-27 16:50:07 +00006138 case SK_UnwrapInitList:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006139 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
Sebastian Redl29526f02011-11-27 16:50:07 +00006140 break;
6141
6142 case SK_RewrapInitList: {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006143 Expr *E = CurInit.get();
Sebastian Redl29526f02011-11-27 16:50:07 +00006144 InitListExpr *Syntactic = Step->WrappingSyntacticList;
6145 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramerc215e762012-08-24 11:54:20 +00006146 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl29526f02011-11-27 16:50:07 +00006147 ILE->setSyntacticForm(Syntactic);
6148 ILE->setType(E->getType());
6149 ILE->setValueKind(E->getValueKind());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006150 CurInit = ILE;
Sebastian Redl29526f02011-11-27 16:50:07 +00006151 break;
6152 }
6153
Sebastian Redl99f66162012-02-19 12:27:56 +00006154 case SK_ConstructorInitialization: {
6155 // When an initializer list is passed for a parameter of type "reference
6156 // to object", we don't get an EK_Temporary entity, but instead an
6157 // EK_Parameter entity with reference type.
6158 // FIXME: This is a hack. What we really should do is create a user
6159 // conversion step for this case, but this makes it considerably more
6160 // complicated. For now, this will do.
6161 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6162 Entity.getType().getNonReferenceType());
6163 bool UseTemporary = Entity.getType()->isReferenceType();
6164 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
6165 : Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006166 Kind, Args, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006167 ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006168 /*IsListInitialization*/ false,
6169 /*LBraceLoc*/ SourceLocation(),
6170 /*RBraceLoc*/ SourceLocation());
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006171 break;
Sebastian Redl99f66162012-02-19 12:27:56 +00006172 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006173
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006174 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006175 step_iterator NextStep = Step;
6176 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006177 if (NextStep != StepEnd &&
Richard Smithd86812d2012-07-05 08:39:21 +00006178 (NextStep->Kind == SK_ConstructorInitialization ||
6179 NextStep->Kind == SK_ListConstructorCall)) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006180 // The need for zero-initialization is recorded directly into
6181 // the call to the object's constructor within the next step.
6182 ConstructorInitRequiresZeroInit = true;
6183 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006184 S.getLangOpts().CPlusPlus &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006185 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00006186 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6187 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006188 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00006189 Kind.getRange().getBegin());
6190
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006191 CurInit = new (S.Context) CXXScalarValueInitExpr(
6192 TSInfo->getType().getNonLValueExprType(S.Context), TSInfo,
6193 Kind.getRange().getEnd());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006194 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006195 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006196 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006197 break;
6198 }
Douglas Gregore1314a62009-12-18 05:02:21 +00006199
6200 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00006201 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006202 ExprResult Result = CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00006203 Sema::AssignConvertType ConvTy =
Fariborz Jahanian25eef192013-07-31 21:40:51 +00006204 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
6205 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley01296292011-04-08 18:41:53 +00006206 if (Result.isInvalid())
6207 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006208 CurInit = Result;
Douglas Gregor96596c92009-12-22 07:24:36 +00006209
6210 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006211 ExprResult CurInitExprRes = CurInit;
Douglas Gregor96596c92009-12-22 07:24:36 +00006212 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006213 Entity.isParameterKind() &&
John Wiegley01296292011-04-08 18:41:53 +00006214 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00006215 == Sema::Compatible)
6216 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00006217 if (CurInitExprRes.isInvalid())
6218 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006219 CurInit = CurInitExprRes;
Douglas Gregor96596c92009-12-22 07:24:36 +00006220
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006221 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00006222 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
6223 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00006224 CurInit.get(),
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00006225 getAssignmentAction(Entity, true),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006226 &Complained)) {
6227 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00006228 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006229 } else if (Complained)
6230 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00006231 break;
6232 }
Eli Friedman78275202009-12-19 08:11:05 +00006233
6234 case SK_StringInit: {
6235 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00006236 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00006237 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00006238 break;
6239 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006240
6241 case SK_ObjCObjectConversion:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006242 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00006243 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00006244 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006245 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006246
6247 case SK_ArrayInit:
6248 // Okay: we checked everything before creating this step. Note that
6249 // this is a GNU extension.
6250 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00006251 << Step->Type << CurInit.get()->getType()
6252 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00006253
6254 // If the destination type is an incomplete array type, update the
6255 // type accordingly.
6256 if (ResultType) {
6257 if (const IncompleteArrayType *IncompleteDest
6258 = S.Context.getAsIncompleteArrayType(Step->Type)) {
6259 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00006260 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00006261 *ResultType = S.Context.getConstantArrayType(
6262 IncompleteDest->getElementType(),
6263 ConstantSource->getSize(),
6264 ArrayType::Normal, 0);
6265 }
6266 }
6267 }
John McCall31168b02011-06-15 23:02:42 +00006268 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006269
Richard Smithebeed412012-02-15 22:38:09 +00006270 case SK_ParenthesizedArrayInit:
6271 // Okay: we checked everything before creating this step. Note that
6272 // this is a GNU extension.
6273 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
6274 << CurInit.get()->getSourceRange();
6275 break;
6276
John McCall31168b02011-06-15 23:02:42 +00006277 case SK_PassByIndirectCopyRestore:
6278 case SK_PassByIndirectRestore:
6279 checkIndirectCopyRestoreSource(S, CurInit.get());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006280 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
6281 CurInit.get(), Step->Type,
6282 Step->Kind == SK_PassByIndirectCopyRestore);
John McCall31168b02011-06-15 23:02:42 +00006283 break;
6284
6285 case SK_ProduceObjCObject:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006286 CurInit =
6287 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
6288 CurInit.get(), nullptr, VK_RValue);
Douglas Gregore2f943b2011-02-22 18:29:51 +00006289 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00006290
6291 case SK_StdInitializerList: {
Richard Smithcc1b96d2013-06-12 22:31:48 +00006292 S.Diag(CurInit.get()->getExprLoc(),
6293 diag::warn_cxx98_compat_initializer_list_init)
6294 << CurInit.get()->getSourceRange();
Sebastian Redl249dee52012-03-05 19:35:43 +00006295
Richard Smithcc1b96d2013-06-12 22:31:48 +00006296 // Materialize the temporary into memory.
6297 MaterializeTemporaryExpr *MTE = new (S.Context)
6298 MaterializeTemporaryExpr(CurInit.get()->getType(), CurInit.get(),
David Majnemerdaff3702014-05-01 17:50:17 +00006299 /*BoundToLvalueReference=*/false);
6300
6301 // Maybe lifetime-extend the array temporary's subobjects to match the
6302 // entity's lifetime.
6303 if (const InitializedEntity *ExtendingEntity =
6304 getEntityForTemporaryLifetimeExtension(&Entity))
6305 if (performReferenceExtension(MTE, ExtendingEntity))
6306 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6307 /*IsInitializerList=*/true,
6308 ExtendingEntity->getDecl());
Richard Smithcc1b96d2013-06-12 22:31:48 +00006309
6310 // Wrap it in a construction of a std::initializer_list<T>.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006311 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006312
6313 // Bind the result, in case the library has given initializer_list a
6314 // non-trivial destructor.
6315 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006316 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redlc1839b12012-01-17 22:49:42 +00006317 break;
6318 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00006319
Guy Benyei61054192013-02-07 10:55:47 +00006320 case SK_OCLSamplerInit: {
6321 assert(Step->Type->isSamplerT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00006322 "Sampler initialization on non-sampler type.");
Guy Benyei61054192013-02-07 10:55:47 +00006323
6324 QualType SourceType = CurInit.get()->getType();
Guy Benyei61054192013-02-07 10:55:47 +00006325
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006326 if (Entity.isParameterKind()) {
Guy Benyei61054192013-02-07 10:55:47 +00006327 if (!SourceType->isSamplerT())
6328 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
6329 << SourceType;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006330 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
Guy Benyei61054192013-02-07 10:55:47 +00006331 llvm_unreachable("Invalid EntityKind!");
6332 }
6333
6334 break;
6335 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006336 case SK_OCLZeroEvent: {
6337 assert(Step->Type->isEventT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00006338 "Event initialization on non-event type.");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006339
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006340 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006341 CK_ZeroToOCLEvent,
6342 CurInit.get()->getValueKind());
6343 break;
6344 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006345 }
6346 }
John McCall1f425642010-11-11 03:21:53 +00006347
6348 // Diagnose non-fatal problems with the completed initialization.
6349 if (Entity.getKind() == InitializedEntity::EK_Member &&
6350 cast<FieldDecl>(Entity.getDecl())->isBitField())
6351 S.CheckBitFieldInitialization(Kind.getLocation(),
6352 cast<FieldDecl>(Entity.getDecl()),
6353 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006354
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006355 return CurInit;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006356}
6357
Richard Smith593f9932012-12-08 02:01:17 +00006358/// Somewhere within T there is an uninitialized reference subobject.
6359/// Dig it out and diagnose it.
Benjamin Kramer3e350262013-02-15 12:30:38 +00006360static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
6361 QualType T) {
Richard Smith593f9932012-12-08 02:01:17 +00006362 if (T->isReferenceType()) {
6363 S.Diag(Loc, diag::err_reference_without_init)
6364 << T.getNonReferenceType();
6365 return true;
6366 }
6367
6368 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6369 if (!RD || !RD->hasUninitializedReferenceMember())
6370 return false;
6371
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006372 for (const auto *FI : RD->fields()) {
Richard Smith593f9932012-12-08 02:01:17 +00006373 if (FI->isUnnamedBitfield())
6374 continue;
6375
6376 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
6377 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6378 return true;
6379 }
6380 }
6381
Aaron Ballman574705e2014-03-13 15:41:46 +00006382 for (const auto &BI : RD->bases()) {
6383 if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
Richard Smith593f9932012-12-08 02:01:17 +00006384 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6385 return true;
6386 }
6387 }
6388
6389 return false;
6390}
6391
6392
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006393//===----------------------------------------------------------------------===//
6394// Diagnose initialization failures
6395//===----------------------------------------------------------------------===//
John McCall5ec7e7d2013-03-19 07:04:25 +00006396
6397/// Emit notes associated with an initialization that failed due to a
6398/// "simple" conversion failure.
6399static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
6400 Expr *op) {
6401 QualType destType = entity.getType();
6402 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
6403 op->getType()->isObjCObjectPointerType()) {
6404
6405 // Emit a possible note about the conversion failing because the
6406 // operand is a message send with a related result type.
6407 S.EmitRelatedResultTypeNote(op);
6408
6409 // Emit a possible note about a return failing because we're
6410 // expecting a related result type.
6411 if (entity.getKind() == InitializedEntity::EK_Result)
6412 S.EmitRelatedResultTypeNoteForReturn(destType);
6413 }
6414}
6415
Richard Smith0449aaf2013-11-21 23:30:57 +00006416static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
6417 InitListExpr *InitList) {
6418 QualType DestType = Entity.getType();
6419
6420 QualType E;
6421 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
6422 QualType ArrayType = S.Context.getConstantArrayType(
6423 E.withConst(),
6424 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6425 InitList->getNumInits()),
6426 clang::ArrayType::Normal, 0);
6427 InitializedEntity HiddenArray =
6428 InitializedEntity::InitializeTemporary(ArrayType);
6429 return diagnoseListInit(S, HiddenArray, InitList);
6430 }
6431
6432 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
6433 /*VerifyOnly=*/false);
6434 assert(DiagnoseInitList.HadError() &&
6435 "Inconsistent init list check result.");
6436}
6437
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006438bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006439 const InitializedEntity &Entity,
6440 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006441 ArrayRef<Expr *> Args) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00006442 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006443 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006444
Douglas Gregor1b303932009-12-22 15:35:07 +00006445 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006446 switch (Failure) {
6447 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006448 // FIXME: Customize for the initialized entity?
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006449 if (Args.empty()) {
Richard Smith593f9932012-12-08 02:01:17 +00006450 // Dig out the reference subobject which is uninitialized and diagnose it.
6451 // If this is value-initialization, this could be nested some way within
6452 // the target type.
6453 assert(Kind.getKind() == InitializationKind::IK_Value ||
6454 DestType->isReferenceType());
6455 bool Diagnosed =
6456 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
6457 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
6458 (void)Diagnosed;
6459 } else // FIXME: diagnostic below could be better!
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006460 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006461 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006462 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006463
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006464 case FK_ArrayNeedsInitList:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006465 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006466 break;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006467 case FK_ArrayNeedsInitListOrStringLiteral:
6468 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
6469 break;
6470 case FK_ArrayNeedsInitListOrWideStringLiteral:
6471 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
6472 break;
6473 case FK_NarrowStringIntoWideCharArray:
6474 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
6475 break;
6476 case FK_WideStringIntoCharArray:
6477 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
6478 break;
6479 case FK_IncompatWideStringIntoWideChar:
6480 S.Diag(Kind.getLocation(),
6481 diag::err_array_init_incompat_wide_string_into_wchar);
6482 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006483 case FK_ArrayTypeMismatch:
6484 case FK_NonConstantArrayInit:
Richard Smith0449aaf2013-11-21 23:30:57 +00006485 S.Diag(Kind.getLocation(),
Douglas Gregore2f943b2011-02-22 18:29:51 +00006486 (Failure == FK_ArrayTypeMismatch
6487 ? diag::err_array_init_different_type
6488 : diag::err_array_init_non_constant_array))
6489 << DestType.getNonReferenceType()
6490 << Args[0]->getType()
6491 << Args[0]->getSourceRange();
6492 break;
6493
John McCalla59dc2f2012-01-05 00:13:19 +00006494 case FK_VariableLengthArrayHasInitializer:
6495 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
6496 << Args[0]->getSourceRange();
6497 break;
6498
John McCall16df1e52010-03-30 21:47:33 +00006499 case FK_AddressOfOverloadFailed: {
6500 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006501 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006502 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00006503 true,
6504 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006505 break;
John McCall16df1e52010-03-30 21:47:33 +00006506 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006507
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006508 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00006509 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006510 switch (FailedOverloadResult) {
6511 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00006512 if (Failure == FK_UserConversionOverloadFailed)
6513 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
6514 << Args[0]->getType() << DestType
6515 << Args[0]->getSourceRange();
6516 else
6517 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
6518 << DestType << Args[0]->getType()
6519 << Args[0]->getSourceRange();
6520
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006521 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006522 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006523
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006524 case OR_No_Viable_Function:
Larisse Voufo70bb43a2013-06-27 03:36:30 +00006525 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00006526 DestType.getNonReferenceType(),
6527 diag::err_typecheck_nonviable_condition_incomplete,
6528 Args[0]->getType(), Args[0]->getSourceRange()))
6529 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
6530 << Args[0]->getType() << Args[0]->getSourceRange()
6531 << DestType.getNonReferenceType();
6532
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006533 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006534 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006535
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006536 case OR_Deleted: {
6537 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
6538 << Args[0]->getType() << DestType.getNonReferenceType()
6539 << Args[0]->getSourceRange();
6540 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006541 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00006542 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
6543 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006544 if (Ovl == OR_Deleted) {
Richard Smith852265f2012-03-30 20:53:28 +00006545 S.NoteDeletedFunction(Best->Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006546 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00006547 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006548 }
6549 break;
6550 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006551
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006552 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00006553 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006554 }
6555 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006556
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006557 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00006558 if (isa<InitListExpr>(Args[0])) {
6559 S.Diag(Kind.getLocation(),
6560 diag::err_lvalue_reference_bind_to_initlist)
6561 << DestType.getNonReferenceType().isVolatileQualified()
6562 << DestType.getNonReferenceType()
6563 << Args[0]->getSourceRange();
6564 break;
6565 }
6566 // Intentional fallthrough
6567
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006568 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006569 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006570 Failure == FK_NonConstLValueReferenceBindingToTemporary
6571 ? diag::err_lvalue_reference_bind_to_temporary
6572 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00006573 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006574 << DestType.getNonReferenceType()
6575 << Args[0]->getType()
6576 << Args[0]->getSourceRange();
6577 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006578
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006579 case FK_RValueReferenceBindingToLValue:
6580 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00006581 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006582 << Args[0]->getSourceRange();
6583 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006584
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006585 case FK_ReferenceInitDropsQualifiers:
6586 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
6587 << DestType.getNonReferenceType()
6588 << Args[0]->getType()
6589 << Args[0]->getSourceRange();
6590 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006591
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006592 case FK_ReferenceInitFailed:
6593 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
6594 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00006595 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006596 << Args[0]->getType()
6597 << Args[0]->getSourceRange();
John McCall5ec7e7d2013-03-19 07:04:25 +00006598 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006599 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006600
Douglas Gregorb491ed32011-02-19 21:32:49 +00006601 case FK_ConversionFailed: {
6602 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00006603 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00006604 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006605 << DestType
John McCall086a4642010-11-24 05:12:34 +00006606 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00006607 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006608 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00006609 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
6610 S.Diag(Kind.getLocation(), PDiag);
John McCall5ec7e7d2013-03-19 07:04:25 +00006611 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00006612 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00006613 }
John Wiegley01296292011-04-08 18:41:53 +00006614
6615 case FK_ConversionFromPropertyFailed:
6616 // No-op. This error has already been reported.
6617 break;
6618
Douglas Gregor51e77d52009-12-10 17:56:55 +00006619 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00006620 SourceRange R;
6621
6622 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00006623 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00006624 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006625 else
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006626 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00006627
Alp Tokerb6cc5922014-05-03 03:45:55 +00006628 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
Douglas Gregor8ec51732010-09-08 21:40:08 +00006629 if (Kind.isCStyleOrFunctionalCast())
6630 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
6631 << R;
6632 else
6633 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6634 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00006635 break;
6636 }
6637
6638 case FK_ReferenceBindingToInitList:
6639 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
6640 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
6641 break;
6642
6643 case FK_InitListBadDestinationType:
6644 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
6645 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
6646 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006647
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006648 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006649 case FK_ConstructorOverloadFailed: {
6650 SourceRange ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006651 if (Args.size())
6652 ArgsRange = SourceRange(Args.front()->getLocStart(),
6653 Args.back()->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006654
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006655 if (Failure == FK_ListConstructorOverloadFailed) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006656 assert(Args.size() == 1 && "List construction from other than 1 argument.");
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006657 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006658 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006659 }
6660
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006661 // FIXME: Using "DestType" for the entity we're printing is probably
6662 // bad.
6663 switch (FailedOverloadResult) {
6664 case OR_Ambiguous:
6665 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
6666 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006667 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006668 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006669
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006670 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006671 if (Kind.getKind() == InitializationKind::IK_Default &&
6672 (Entity.getKind() == InitializedEntity::EK_Base ||
6673 Entity.getKind() == InitializedEntity::EK_Member) &&
6674 isa<CXXConstructorDecl>(S.CurContext)) {
6675 // This is implicit default initialization of a member or
6676 // base within a constructor. If no viable function was
6677 // found, notify the user that she needs to explicitly
6678 // initialize this base/member.
6679 CXXConstructorDecl *Constructor
6680 = cast<CXXConstructorDecl>(S.CurContext);
6681 if (Entity.getKind() == InitializedEntity::EK_Base) {
6682 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006683 << (Constructor->getInheritedConstructor() ? 2 :
6684 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006685 << S.Context.getTypeDeclType(Constructor->getParent())
6686 << /*base=*/0
6687 << Entity.getType();
6688
6689 RecordDecl *BaseDecl
6690 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6691 ->getDecl();
6692 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6693 << S.Context.getTagDeclType(BaseDecl);
6694 } else {
6695 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006696 << (Constructor->getInheritedConstructor() ? 2 :
6697 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006698 << S.Context.getTypeDeclType(Constructor->getParent())
6699 << /*member=*/1
6700 << Entity.getName();
Alp Toker2afa8782014-05-28 12:20:14 +00006701 S.Diag(Entity.getDecl()->getLocation(),
6702 diag::note_member_declared_at);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006703
6704 if (const RecordType *Record
6705 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006706 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006707 diag::note_previous_decl)
6708 << S.Context.getTagDeclType(Record->getDecl());
6709 }
6710 break;
6711 }
6712
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006713 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6714 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006715 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006716 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006717
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006718 case OR_Deleted: {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006719 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006720 OverloadingResult Ovl
6721 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor74f7d502012-02-15 19:33:52 +00006722 if (Ovl != OR_Deleted) {
6723 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6724 << true << DestType << ArgsRange;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006725 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor74f7d502012-02-15 19:33:52 +00006726 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006727 }
Douglas Gregor74f7d502012-02-15 19:33:52 +00006728
6729 // If this is a defaulted or implicitly-declared function, then
6730 // it was implicitly deleted. Make it clear that the deletion was
6731 // implicit.
Richard Smith852265f2012-03-30 20:53:28 +00006732 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00006733 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith852265f2012-03-30 20:53:28 +00006734 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00006735 << DestType << ArgsRange;
Richard Smith852265f2012-03-30 20:53:28 +00006736 else
6737 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6738 << true << DestType << ArgsRange;
6739
6740 S.NoteDeletedFunction(Best->Function);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006741 break;
6742 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006743
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006744 case OR_Success:
6745 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006746 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006747 }
David Blaikie60deeee2012-01-17 08:24:58 +00006748 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006749
Douglas Gregor85dabae2009-12-16 01:38:02 +00006750 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006751 if (Entity.getKind() == InitializedEntity::EK_Member &&
6752 isa<CXXConstructorDecl>(S.CurContext)) {
6753 // This is implicit default-initialization of a const member in
6754 // a constructor. Complain that it needs to be explicitly
6755 // initialized.
6756 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6757 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006758 << (Constructor->getInheritedConstructor() ? 2 :
6759 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006760 << S.Context.getTypeDeclType(Constructor->getParent())
6761 << /*const=*/1
6762 << Entity.getName();
6763 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6764 << Entity.getName();
6765 } else {
6766 S.Diag(Kind.getLocation(), diag::err_default_init_const)
6767 << DestType << (bool)DestType->getAs<RecordType>();
6768 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00006769 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006770
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006771 case FK_Incomplete:
Douglas Gregor85f34232012-04-10 20:43:46 +00006772 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006773 diag::err_init_incomplete_type);
6774 break;
6775
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006776 case FK_ListInitializationFailed: {
6777 // Run the init list checker again to emit diagnostics.
Richard Smith0449aaf2013-11-21 23:30:57 +00006778 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6779 diagnoseListInit(S, Entity, InitList);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006780 break;
6781 }
John McCall4124c492011-10-17 18:40:02 +00006782
6783 case FK_PlaceholderType: {
6784 // FIXME: Already diagnosed!
6785 break;
6786 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00006787
Sebastian Redl048a6d72012-04-01 19:54:59 +00006788 case FK_ExplicitConstructor: {
6789 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6790 << Args[0]->getSourceRange();
6791 OverloadCandidateSet::iterator Best;
6792 OverloadingResult Ovl
6793 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gay5dcce092012-04-02 19:05:35 +00006794 (void)Ovl;
Sebastian Redl048a6d72012-04-01 19:54:59 +00006795 assert(Ovl == OR_Success && "Inconsistent overload resolution");
6796 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6797 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6798 break;
6799 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006800 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006801
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006802 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006803 return true;
6804}
Douglas Gregore1314a62009-12-18 05:02:21 +00006805
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006806void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006807 switch (SequenceKind) {
6808 case FailedSequence: {
6809 OS << "Failed sequence: ";
6810 switch (Failure) {
6811 case FK_TooManyInitsForReference:
6812 OS << "too many initializers for reference";
6813 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006814
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006815 case FK_ArrayNeedsInitList:
6816 OS << "array requires initializer list";
6817 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006818
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006819 case FK_ArrayNeedsInitListOrStringLiteral:
6820 OS << "array requires initializer list or string literal";
6821 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006822
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006823 case FK_ArrayNeedsInitListOrWideStringLiteral:
6824 OS << "array requires initializer list or wide string literal";
6825 break;
6826
6827 case FK_NarrowStringIntoWideCharArray:
6828 OS << "narrow string into wide char array";
6829 break;
6830
6831 case FK_WideStringIntoCharArray:
6832 OS << "wide string into char array";
6833 break;
6834
6835 case FK_IncompatWideStringIntoWideChar:
6836 OS << "incompatible wide string into wide char array";
6837 break;
6838
Douglas Gregore2f943b2011-02-22 18:29:51 +00006839 case FK_ArrayTypeMismatch:
6840 OS << "array type mismatch";
6841 break;
6842
6843 case FK_NonConstantArrayInit:
6844 OS << "non-constant array initializer";
6845 break;
6846
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006847 case FK_AddressOfOverloadFailed:
6848 OS << "address of overloaded function failed";
6849 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006850
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006851 case FK_ReferenceInitOverloadFailed:
6852 OS << "overload resolution for reference initialization failed";
6853 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006854
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006855 case FK_NonConstLValueReferenceBindingToTemporary:
6856 OS << "non-const lvalue reference bound to temporary";
6857 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006858
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006859 case FK_NonConstLValueReferenceBindingToUnrelated:
6860 OS << "non-const lvalue reference bound to unrelated type";
6861 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006862
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006863 case FK_RValueReferenceBindingToLValue:
6864 OS << "rvalue reference bound to an lvalue";
6865 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006866
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006867 case FK_ReferenceInitDropsQualifiers:
6868 OS << "reference initialization drops qualifiers";
6869 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006870
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006871 case FK_ReferenceInitFailed:
6872 OS << "reference initialization failed";
6873 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006874
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006875 case FK_ConversionFailed:
6876 OS << "conversion failed";
6877 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006878
John Wiegley01296292011-04-08 18:41:53 +00006879 case FK_ConversionFromPropertyFailed:
6880 OS << "conversion from property failed";
6881 break;
6882
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006883 case FK_TooManyInitsForScalar:
6884 OS << "too many initializers for scalar";
6885 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006886
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006887 case FK_ReferenceBindingToInitList:
6888 OS << "referencing binding to initializer list";
6889 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006890
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006891 case FK_InitListBadDestinationType:
6892 OS << "initializer list for non-aggregate, non-scalar type";
6893 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006894
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006895 case FK_UserConversionOverloadFailed:
6896 OS << "overloading failed for user-defined conversion";
6897 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006898
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006899 case FK_ConstructorOverloadFailed:
6900 OS << "constructor overloading failed";
6901 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006902
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006903 case FK_DefaultInitOfConst:
6904 OS << "default initialization of a const variable";
6905 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006906
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00006907 case FK_Incomplete:
6908 OS << "initialization of incomplete type";
6909 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006910
6911 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006912 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00006913 break;
6914
John McCalla59dc2f2012-01-05 00:13:19 +00006915 case FK_VariableLengthArrayHasInitializer:
6916 OS << "variable length array has an initializer";
6917 break;
6918
John McCall4124c492011-10-17 18:40:02 +00006919 case FK_PlaceholderType:
6920 OS << "initializer expression isn't contextually valid";
6921 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00006922
6923 case FK_ListConstructorOverloadFailed:
6924 OS << "list constructor overloading failed";
6925 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00006926
Sebastian Redl048a6d72012-04-01 19:54:59 +00006927 case FK_ExplicitConstructor:
6928 OS << "list copy initialization chose explicit constructor";
6929 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006930 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006931 OS << '\n';
6932 return;
6933 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006934
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006935 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00006936 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006937 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006938
Sebastian Redld201edf2011-06-05 13:59:11 +00006939 case NormalSequence:
6940 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006941 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006942 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006943
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006944 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
6945 if (S != step_begin()) {
6946 OS << " -> ";
6947 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006948
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006949 switch (S->Kind) {
6950 case SK_ResolveAddressOfOverloadedFunction:
6951 OS << "resolve address of overloaded function";
6952 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006953
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006954 case SK_CastDerivedToBaseRValue:
6955 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
6956 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006957
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006958 case SK_CastDerivedToBaseXValue:
6959 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
6960 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006961
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006962 case SK_CastDerivedToBaseLValue:
6963 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
6964 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006965
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006966 case SK_BindReference:
6967 OS << "bind reference to lvalue";
6968 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006969
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006970 case SK_BindReferenceToTemporary:
6971 OS << "bind reference to a temporary";
6972 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006973
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006974 case SK_ExtraneousCopyToTemporary:
6975 OS << "extraneous C++03 copy to temporary";
6976 break;
6977
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006978 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00006979 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006980 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006981
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006982 case SK_QualificationConversionRValue:
6983 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00006984 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006985
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006986 case SK_QualificationConversionXValue:
6987 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00006988 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006989
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006990 case SK_QualificationConversionLValue:
6991 OS << "qualification conversion (lvalue)";
6992 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006993
Jordan Roseb1312a52013-04-11 00:58:58 +00006994 case SK_LValueToRValue:
6995 OS << "load (lvalue to rvalue)";
6996 break;
6997
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006998 case SK_ConversionSequence:
6999 OS << "implicit conversion sequence (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00007000 S->ICS->dump(); // FIXME: use OS
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007001 OS << ")";
7002 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007003
Richard Smithaaa0ec42013-09-21 21:19:19 +00007004 case SK_ConversionSequenceNoNarrowing:
7005 OS << "implicit conversion sequence with narrowing prohibited (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00007006 S->ICS->dump(); // FIXME: use OS
Richard Smithaaa0ec42013-09-21 21:19:19 +00007007 OS << ")";
7008 break;
7009
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007010 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007011 OS << "list aggregate initialization";
7012 break;
7013
7014 case SK_ListConstructorCall:
7015 OS << "list initialization via constructor";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007016 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007017
Sebastian Redl29526f02011-11-27 16:50:07 +00007018 case SK_UnwrapInitList:
7019 OS << "unwrap reference initializer list";
7020 break;
7021
7022 case SK_RewrapInitList:
7023 OS << "rewrap reference initializer list";
7024 break;
7025
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007026 case SK_ConstructorInitialization:
7027 OS << "constructor initialization";
7028 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007029
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007030 case SK_ZeroInitialization:
7031 OS << "zero initialization";
7032 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007033
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007034 case SK_CAssignment:
7035 OS << "C assignment";
7036 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007037
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007038 case SK_StringInit:
7039 OS << "string initialization";
7040 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007041
7042 case SK_ObjCObjectConversion:
7043 OS << "Objective-C object conversion";
7044 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007045
7046 case SK_ArrayInit:
7047 OS << "array initialization";
7048 break;
John McCall31168b02011-06-15 23:02:42 +00007049
Richard Smithebeed412012-02-15 22:38:09 +00007050 case SK_ParenthesizedArrayInit:
7051 OS << "parenthesized array initialization";
7052 break;
7053
John McCall31168b02011-06-15 23:02:42 +00007054 case SK_PassByIndirectCopyRestore:
7055 OS << "pass by indirect copy and restore";
7056 break;
7057
7058 case SK_PassByIndirectRestore:
7059 OS << "pass by indirect restore";
7060 break;
7061
7062 case SK_ProduceObjCObject:
7063 OS << "Objective-C object retension";
7064 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00007065
7066 case SK_StdInitializerList:
7067 OS << "std::initializer_list from initializer list";
7068 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007069
Guy Benyei61054192013-02-07 10:55:47 +00007070 case SK_OCLSamplerInit:
7071 OS << "OpenCL sampler_t from integer constant";
7072 break;
7073
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007074 case SK_OCLZeroEvent:
7075 OS << "OpenCL event_t from zero";
7076 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007077 }
Richard Smith6b216962013-02-05 05:52:24 +00007078
7079 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007080 }
Richard Smith6b216962013-02-05 05:52:24 +00007081
7082 OS << '\n';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007083}
7084
7085void InitializationSequence::dump() const {
7086 dump(llvm::errs());
7087}
7088
Richard Smithaaa0ec42013-09-21 21:19:19 +00007089static void DiagnoseNarrowingInInitList(Sema &S,
7090 const ImplicitConversionSequence &ICS,
7091 QualType PreNarrowingType,
Richard Smith66e05fe2012-01-18 05:21:49 +00007092 QualType EntityType,
Richard Smith66e05fe2012-01-18 05:21:49 +00007093 const Expr *PostInit) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007094 const StandardConversionSequence *SCS = nullptr;
Richard Smith66e05fe2012-01-18 05:21:49 +00007095 switch (ICS.getKind()) {
7096 case ImplicitConversionSequence::StandardConversion:
7097 SCS = &ICS.Standard;
7098 break;
7099 case ImplicitConversionSequence::UserDefinedConversion:
7100 SCS = &ICS.UserDefined.After;
7101 break;
7102 case ImplicitConversionSequence::AmbiguousConversion:
7103 case ImplicitConversionSequence::EllipsisConversion:
7104 case ImplicitConversionSequence::BadConversion:
7105 return;
7106 }
7107
Richard Smith66e05fe2012-01-18 05:21:49 +00007108 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
7109 APValue ConstantValue;
Richard Smith5614ca72012-03-23 23:55:39 +00007110 QualType ConstantType;
7111 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
7112 ConstantType)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00007113 case NK_Not_Narrowing:
7114 // No narrowing occurred.
7115 return;
7116
7117 case NK_Type_Narrowing:
7118 // This was a floating-to-integer conversion, which is always considered a
7119 // narrowing conversion even if the value is a constant and can be
7120 // represented exactly as an integer.
7121 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007122 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7123 ? diag::warn_init_list_type_narrowing
7124 : diag::ext_init_list_type_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007125 << PostInit->getSourceRange()
7126 << PreNarrowingType.getLocalUnqualifiedType()
7127 << EntityType.getLocalUnqualifiedType();
7128 break;
7129
7130 case NK_Constant_Narrowing:
7131 // A constant value was narrowed.
7132 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007133 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7134 ? diag::warn_init_list_constant_narrowing
7135 : diag::ext_init_list_constant_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007136 << PostInit->getSourceRange()
Richard Smith5614ca72012-03-23 23:55:39 +00007137 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007138 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007139 break;
7140
7141 case NK_Variable_Narrowing:
7142 // A variable's value may have been narrowed.
7143 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007144 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7145 ? diag::warn_init_list_variable_narrowing
7146 : diag::ext_init_list_variable_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007147 << PostInit->getSourceRange()
7148 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007149 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007150 break;
7151 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007152
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007153 SmallString<128> StaticCast;
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007154 llvm::raw_svector_ostream OS(StaticCast);
7155 OS << "static_cast<";
7156 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
7157 // It's important to use the typedef's name if there is one so that the
7158 // fixit doesn't break code using types like int64_t.
7159 //
7160 // FIXME: This will break if the typedef requires qualification. But
7161 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00007162 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007163 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikiebbafb8a2012-03-11 07:00:24 +00007164 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007165 else {
7166 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
7167 // with a broken cast.
7168 return;
7169 }
7170 OS << ">(";
Alp Tokerb0869032014-05-17 01:13:18 +00007171 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007172 << PostInit->getSourceRange()
7173 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
7174 << FixItHint::CreateInsertion(
7175 S.getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007176}
7177
Douglas Gregore1314a62009-12-18 05:02:21 +00007178//===----------------------------------------------------------------------===//
7179// Initialization helper functions
7180//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00007181bool
7182Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
7183 ExprResult Init) {
7184 if (Init.isInvalid())
7185 return false;
7186
7187 Expr *InitE = Init.get();
7188 assert(InitE && "No initialization expression");
7189
Douglas Gregorf4cc61d2012-07-31 22:15:04 +00007190 InitializationKind Kind
7191 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007192 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00007193 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00007194}
7195
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007196ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00007197Sema::PerformCopyInitialization(const InitializedEntity &Entity,
7198 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007199 ExprResult Init,
Douglas Gregor6073dca2012-02-24 23:56:31 +00007200 bool TopLevelOfInitList,
7201 bool AllowExplicit) {
Douglas Gregore1314a62009-12-18 05:02:21 +00007202 if (Init.isInvalid())
7203 return ExprError();
7204
John McCall1f425642010-11-11 03:21:53 +00007205 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00007206 assert(InitE && "No initialization expression?");
7207
7208 if (EqualLoc.isInvalid())
7209 EqualLoc = InitE->getLocStart();
7210
7211 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00007212 EqualLoc,
7213 AllowExplicit);
Richard Smithaaa0ec42013-09-21 21:19:19 +00007214 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007215 Init.get();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007216
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007217 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith66e05fe2012-01-18 05:21:49 +00007218
Richard Smith66e05fe2012-01-18 05:21:49 +00007219 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00007220}