blob: aa45c8333ad018231b01374a19c1f8940b2ca701 [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
John McCall8b0666c2010-08-20 18:27:03 +000014#include "clang/Sema/Designator.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
John McCall83024632010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Tanya Lattner5029d562010-03-07 04:17:15 +000018#include "clang/Lex/Preprocessor.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000019#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000023#include "clang/AST/TypeLoc.h"
Sebastian Redlc1839b12012-01-17 22:49:42 +000024#include "llvm/ADT/APInt.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000025#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskina6667812011-07-26 23:20:30 +000026#include "llvm/Support/raw_ostream.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000027#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000028using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000029
Chris Lattner0cb78032009-02-24 22:27:37 +000030//===----------------------------------------------------------------------===//
31// Sema Initialization Checking
32//===----------------------------------------------------------------------===//
33
John McCall66884dd2011-02-21 07:22:22 +000034static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
35 ASTContext &Context) {
Eli Friedman893abe42009-05-29 18:22:49 +000036 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
37 return 0;
38
Chris Lattnera9196812009-02-26 23:26:43 +000039 // See if this is a string literal or @encode.
40 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000041
Chris Lattnera9196812009-02-26 23:26:43 +000042 // Handle @encode, which is a narrow string.
43 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
44 return Init;
45
46 // Otherwise we can only handle string literals.
47 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000048 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000049
50 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Douglas Gregorfb65e592011-07-27 05:40:30 +000051
52 switch (SL->getKind()) {
53 case StringLiteral::Ascii:
54 case StringLiteral::UTF8:
55 // char array can be initialized with a narrow string.
56 // Only allow char x[] = "foo"; not char x[] = L"foo";
Eli Friedman42a84652009-05-31 10:54:53 +000057 return ElemTy->isCharType() ? Init : 0;
Douglas Gregorfb65e592011-07-27 05:40:30 +000058 case StringLiteral::UTF16:
59 return ElemTy->isChar16Type() ? Init : 0;
60 case StringLiteral::UTF32:
61 return ElemTy->isChar32Type() ? Init : 0;
62 case StringLiteral::Wide:
63 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
64 // correction from DR343): "An array with element type compatible with a
65 // qualified or unqualified version of wchar_t may be initialized by a wide
66 // string literal, optionally enclosed in braces."
67 if (Context.typesAreCompatible(Context.getWCharType(),
68 ElemTy.getUnqualifiedType()))
69 return Init;
Chris Lattnera9196812009-02-26 23:26:43 +000070
Douglas Gregorfb65e592011-07-27 05:40:30 +000071 return 0;
72 }
Mike Stump11289f42009-09-09 15:08:12 +000073
Douglas Gregorfb65e592011-07-27 05:40:30 +000074 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattner0cb78032009-02-24 22:27:37 +000075}
76
John McCall66884dd2011-02-21 07:22:22 +000077static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
78 const ArrayType *arrayType = Context.getAsArrayType(declType);
79 if (!arrayType) return 0;
80
81 return IsStringInit(init, arrayType, Context);
82}
83
John McCall5decec92011-02-21 07:57:55 +000084static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
85 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +000086 // Get the length of the string as parsed.
87 uint64_t StrLength =
88 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
89
Mike Stump11289f42009-09-09 15:08:12 +000090
Chris Lattner0cb78032009-02-24 22:27:37 +000091 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +000092 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +000093 // being initialized to a string literal.
94 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000095 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +000096 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +000097 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
98 ConstVal,
99 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000100 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000101 }
Mike Stump11289f42009-09-09 15:08:12 +0000102
Eli Friedman893abe42009-05-29 18:22:49 +0000103 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000104
Eli Friedman554eba92011-04-11 00:23:45 +0000105 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +0000106 // the size may be smaller or larger than the string we are initializing.
107 // FIXME: Avoid truncation for 64-bit length strings.
Eli Friedman554eba92011-04-11 00:23:45 +0000108 if (S.getLangOptions().CPlusPlus) {
Anders Carlssond162fb82011-04-14 00:41:11 +0000109 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
110 // For Pascal strings it's OK to strip off the terminating null character,
111 // so the example below is valid:
112 //
113 // unsigned char a[2] = "\pa";
114 if (SL->isPascal())
115 StrLength--;
116 }
117
Eli Friedman554eba92011-04-11 00:23:45 +0000118 // [dcl.init.string]p2
119 if (StrLength > CAT->getSize().getZExtValue())
120 S.Diag(Str->getSourceRange().getBegin(),
121 diag::err_initializer_string_for_char_array_too_long)
122 << Str->getSourceRange();
123 } else {
124 // C99 6.7.8p14.
125 if (StrLength-1 > CAT->getSize().getZExtValue())
126 S.Diag(Str->getSourceRange().getBegin(),
127 diag::warn_initializer_string_for_char_array_too_long)
128 << Str->getSourceRange();
129 }
Mike Stump11289f42009-09-09 15:08:12 +0000130
Eli Friedman893abe42009-05-29 18:22:49 +0000131 // Set the type to the actual size that we are initializing. If we have
132 // something like:
133 // char x[1] = "foo";
134 // then this will set the string literal's type to char[1].
135 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000136}
137
Chris Lattner0cb78032009-02-24 22:27:37 +0000138//===----------------------------------------------------------------------===//
139// Semantic checking for initializer lists.
140//===----------------------------------------------------------------------===//
141
Douglas Gregorcde232f2009-01-29 01:05:33 +0000142/// @brief Semantic checking for initializer lists.
143///
144/// The InitListChecker class contains a set of routines that each
145/// handle the initialization of a certain kind of entity, e.g.,
146/// arrays, vectors, struct/union types, scalars, etc. The
147/// InitListChecker itself performs a recursive walk of the subobject
148/// structure of the type to be initialized, while stepping through
149/// the initializer list one element at a time. The IList and Index
150/// parameters to each of the Check* routines contain the active
151/// (syntactic) initializer list and the index into that initializer
152/// list that represents the current initializer. Each routine is
153/// responsible for moving that Index forward as it consumes elements.
154///
155/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000156/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000157/// initializer list and the index into that initializer list where we
158/// are copying initializers as we map them over to the semantic
159/// list. Once we have completed our recursive walk of the subobject
160/// structure, we will have constructed a full semantic initializer
161/// list.
162///
163/// C99 designators cause changes in the initializer list traversal,
164/// because they make the initialization "jump" into a specific
165/// subobject and then continue the initialization from that
166/// point. CheckDesignatedInitializer() recursively steps into the
167/// designated subobject and manages backing out the recursion to
168/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000169namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000170class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000171 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000172 bool hadError;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000173 bool VerifyOnly; // no diagnostics, no structure building
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000174 bool AllowBraceElision;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000175 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
176 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000177
Anders Carlsson6cabf312010-01-23 23:23:01 +0000178 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000179 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000180 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000181 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000182 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000183 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000184 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000185 unsigned &StructuredIndex,
186 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000187 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000188 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000189 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000190 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000191 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000192 unsigned &StructuredIndex,
193 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000194 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000195 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000196 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000197 InitListExpr *StructuredList,
198 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000199 void CheckComplexType(const InitializedEntity &Entity,
200 InitListExpr *IList, QualType DeclType,
201 unsigned &Index,
202 InitListExpr *StructuredList,
203 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000204 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000205 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000206 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000207 InitListExpr *StructuredList,
208 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000209 void CheckReferenceType(const InitializedEntity &Entity,
210 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000211 unsigned &Index,
212 InitListExpr *StructuredList,
213 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000214 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000215 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000216 InitListExpr *StructuredList,
217 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000218 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000219 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000220 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000221 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000222 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000223 unsigned &StructuredIndex,
224 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000225 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000226 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000227 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000228 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000229 InitListExpr *StructuredList,
230 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000231 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000232 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000233 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000234 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000235 RecordDecl::field_iterator *NextField,
236 llvm::APSInt *NextElementIndex,
237 unsigned &Index,
238 InitListExpr *StructuredList,
239 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000240 bool FinishSubobjectInit,
241 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000242 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
243 QualType CurrentObjectType,
244 InitListExpr *StructuredList,
245 unsigned StructuredIndex,
246 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000247 void UpdateStructuredListElement(InitListExpr *StructuredList,
248 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000249 Expr *expr);
250 int numArrayElements(QualType DeclType);
251 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000252
Douglas Gregor2bb07652009-12-22 00:05:34 +0000253 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
254 const InitializedEntity &ParentEntity,
255 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000256 void FillInValueInitializations(const InitializedEntity &Entity,
257 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000258 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
259 Expr *InitExpr, FieldDecl *Field,
260 bool TopLevelObject);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000261 void CheckValueInitializable(const InitializedEntity &Entity);
262
Douglas Gregor85df8d82009-01-29 00:45:39 +0000263public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000264 InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000265 InitListExpr *IL, QualType &T, bool VerifyOnly,
266 bool AllowBraceElision);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000267 bool HadError() { return hadError; }
268
269 // @brief Retrieves the fully-structured initializer list used for
270 // semantic analysis and code generation.
271 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
272};
Chris Lattner9ececce2009-02-24 22:48:58 +0000273} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000274
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000275void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
276 assert(VerifyOnly &&
277 "CheckValueInitializable is only inteded for verification mode.");
278
279 SourceLocation Loc;
280 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
281 true);
282 InitializationSequence InitSeq(SemaRef, Entity, Kind, 0, 0);
283 if (InitSeq.Failed())
284 hadError = true;
285}
286
Douglas Gregor2bb07652009-12-22 00:05:34 +0000287void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
288 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000289 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000290 bool &RequiresSecondPass) {
291 SourceLocation Loc = ILE->getSourceRange().getBegin();
292 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000293 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000294 = InitializedEntity::InitializeMember(Field, &ParentEntity);
295 if (Init >= NumInits || !ILE->getInit(Init)) {
296 // FIXME: We probably don't need to handle references
297 // specially here, since value-initialization of references is
298 // handled in InitializationSequence.
299 if (Field->getType()->isReferenceType()) {
300 // C++ [dcl.init.aggr]p9:
301 // If an incomplete or empty initializer-list leaves a
302 // member of reference type uninitialized, the program is
303 // ill-formed.
304 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
305 << Field->getType()
306 << ILE->getSyntacticForm()->getSourceRange();
307 SemaRef.Diag(Field->getLocation(),
308 diag::note_uninit_reference_member);
309 hadError = true;
310 return;
311 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000312
Douglas Gregor2bb07652009-12-22 00:05:34 +0000313 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
314 true);
315 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
316 if (!InitSeq) {
317 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
318 hadError = true;
319 return;
320 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000321
John McCalldadc5752010-08-24 06:29:42 +0000322 ExprResult MemberInit
John McCallfaf5fb42010-08-26 23:41:50 +0000323 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000324 if (MemberInit.isInvalid()) {
325 hadError = true;
326 return;
327 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000328
Douglas Gregor2bb07652009-12-22 00:05:34 +0000329 if (hadError) {
330 // Do nothing
331 } else if (Init < NumInits) {
332 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redld201edf2011-06-05 13:59:11 +0000333 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000334 // Value-initialization requires a constructor call, so
335 // extend the initializer list to include the constructor
336 // call and make a note that we'll need to take another pass
337 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000338 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000339 RequiresSecondPass = true;
340 }
341 } else if (InitListExpr *InnerILE
342 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000343 FillInValueInitializations(MemberEntity, InnerILE,
344 RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000345}
346
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000347/// Recursively replaces NULL values within the given initializer list
348/// with expressions that perform value-initialization of the
349/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000350void
Douglas Gregor723796a2009-12-16 06:35:08 +0000351InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
352 InitListExpr *ILE,
353 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000354 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000355 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000356 SourceLocation Loc = ILE->getSourceRange().getBegin();
357 if (ILE->getSyntacticForm())
358 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000359
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000360 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000361 if (RType->getDecl()->isUnion() &&
362 ILE->getInitializedFieldInUnion())
363 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
364 Entity, ILE, RequiresSecondPass);
365 else {
366 unsigned Init = 0;
367 for (RecordDecl::field_iterator
368 Field = RType->getDecl()->field_begin(),
369 FieldEnd = RType->getDecl()->field_end();
370 Field != FieldEnd; ++Field) {
371 if (Field->isUnnamedBitfield())
372 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000373
Douglas Gregor2bb07652009-12-22 00:05:34 +0000374 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000375 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000376
377 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
378 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000379 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000380
Douglas Gregor2bb07652009-12-22 00:05:34 +0000381 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000382
Douglas Gregor2bb07652009-12-22 00:05:34 +0000383 // Only look at the first initialization of a union.
384 if (RType->getDecl()->isUnion())
385 break;
386 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000387 }
388
389 return;
Mike Stump11289f42009-09-09 15:08:12 +0000390 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000391
392 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000393
Douglas Gregor723796a2009-12-16 06:35:08 +0000394 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000395 unsigned NumInits = ILE->getNumInits();
396 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000397 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000398 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000399 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
400 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000401 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000402 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000403 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000404 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000405 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000406 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000407 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000408 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000409 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000410
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000411
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000412 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000413 if (hadError)
414 return;
415
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000416 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
417 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000418 ElementEntity.setElementIndex(Init);
419
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000420 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
421 if (!InitExpr && !ILE->hasArrayFiller()) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000422 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
423 true);
424 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
425 if (!InitSeq) {
426 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000427 hadError = true;
428 return;
429 }
430
John McCalldadc5752010-08-24 06:29:42 +0000431 ExprResult ElementInit
John McCallfaf5fb42010-08-26 23:41:50 +0000432 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregor723796a2009-12-16 06:35:08 +0000433 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000434 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000435 return;
436 }
437
438 if (hadError) {
439 // Do nothing
440 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000441 // For arrays, just set the expression used for value-initialization
442 // of the "holes" in the array.
443 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
444 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
445 else
446 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000447 } else {
448 // For arrays, just set the expression used for value-initialization
449 // of the rest of elements and exit.
450 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
451 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
452 return;
453 }
454
Sebastian Redld201edf2011-06-05 13:59:11 +0000455 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000456 // Value-initialization requires a constructor call, so
457 // extend the initializer list to include the constructor
458 // call and make a note that we'll need to take another pass
459 // through the initializer list.
460 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
461 RequiresSecondPass = true;
462 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000463 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000464 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000465 = dyn_cast_or_null<InitListExpr>(InitExpr))
Douglas Gregor723796a2009-12-16 06:35:08 +0000466 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000467 }
468}
469
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000470
Douglas Gregor723796a2009-12-16 06:35:08 +0000471InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000472 InitListExpr *IL, QualType &T,
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000473 bool VerifyOnly, bool AllowBraceElision)
Richard Smith0f8ede12011-12-20 04:00:21 +0000474 : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000475 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000476
Eli Friedman23a9e312008-05-19 19:16:24 +0000477 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000478 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000479 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000480 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000481 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000482 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000483 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000484
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000485 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000486 bool RequiresSecondPass = false;
487 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000488 if (RequiresSecondPass && !hadError)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000489 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000490 RequiresSecondPass);
491 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000492}
493
494int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000495 // FIXME: use a proper constant
496 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000497 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000498 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000499 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
500 }
501 return maxElements;
502}
503
504int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000505 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000506 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000507 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000508 Field = structDecl->field_begin(),
509 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000510 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +0000511 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000512 ++InitializableMembers;
513 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000514 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000515 return std::min(InitializableMembers, 1);
516 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000517}
518
Anders Carlsson6cabf312010-01-23 23:23:01 +0000519void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000520 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000521 QualType T, unsigned &Index,
522 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000523 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000524 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000525
Steve Narofff8ecff22008-05-01 22:18:59 +0000526 if (T->isArrayType())
527 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000528 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000529 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000530 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000531 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000532 else
David Blaikie83d382b2011-09-23 05:06:16 +0000533 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000534
Eli Friedmane0f832b2008-05-25 13:49:22 +0000535 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000536 if (!VerifyOnly)
537 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
538 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000539 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000540 hadError = true;
541 return;
542 }
543
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000544 // Build a structured initializer list corresponding to this subobject.
545 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000546 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
547 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000548 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
549 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000550 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000551
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000552 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000553 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000554 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000555 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000556 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000557 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000558
559 if (VerifyOnly) {
560 if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
561 hadError = true;
562 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000563 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000564
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000565 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000566 // Update the structured sub-object initializer so that it's ending
567 // range corresponds with the end of the last initializer it used.
568 if (EndIndex < ParentIList->getNumInits()) {
569 SourceLocation EndLoc
570 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
571 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
572 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000573
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000574 // Complain about missing braces.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000575 if (T->isArrayType() || T->isRecordType()) {
576 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000577 AllowBraceElision ? diag::warn_missing_braces :
578 diag::err_missing_braces)
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000579 << StructuredSubobjectInitList->getSourceRange()
580 << FixItHint::CreateInsertion(
581 StructuredSubobjectInitList->getLocStart(), "{")
582 << FixItHint::CreateInsertion(
583 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000584 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000585 "}");
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000586 if (!AllowBraceElision)
587 hadError = true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000588 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000589 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000590}
591
Anders Carlsson6cabf312010-01-23 23:23:01 +0000592void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000593 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000594 unsigned &Index,
595 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000596 unsigned &StructuredIndex,
597 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000598 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000599 if (!VerifyOnly) {
600 SyntacticToSemantic[IList] = StructuredList;
601 StructuredList->setSyntacticForm(IList);
602 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000603 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000604 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000605 if (!VerifyOnly) {
606 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
607 IList->setType(ExprTy);
608 StructuredList->setType(ExprTy);
609 }
Eli Friedman85f54972008-05-25 13:22:35 +0000610 if (hadError)
611 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000612
Eli Friedman85f54972008-05-25 13:22:35 +0000613 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000614 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000615 if (VerifyOnly) {
616 if (SemaRef.getLangOptions().CPlusPlus ||
617 (SemaRef.getLangOptions().OpenCL &&
618 IList->getType()->isVectorType())) {
619 hadError = true;
620 }
621 return;
622 }
623
Eli Friedmanbd327452009-05-29 20:20:05 +0000624 if (StructuredIndex == 1 &&
625 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000626 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000627 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000628 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000629 hadError = true;
630 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000631 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000632 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000633 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000634 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000635 // Don't complain for incomplete types, since we'll get an error
636 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000637 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000638 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000639 CurrentObjectType->isArrayType()? 0 :
640 CurrentObjectType->isVectorType()? 1 :
641 CurrentObjectType->isScalarType()? 2 :
642 CurrentObjectType->isUnionType()? 3 :
643 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000644
645 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000646 if (SemaRef.getLangOptions().CPlusPlus) {
647 DK = diag::err_excess_initializers;
648 hadError = true;
649 }
Nate Begeman425038c2009-07-07 21:53:06 +0000650 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
651 DK = diag::err_excess_initializers;
652 hadError = true;
653 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000654
Chris Lattnerb0912a52009-02-24 22:50:46 +0000655 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000656 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000657 }
658 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000659
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000660 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
661 !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000662 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000663 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000664 << FixItHint::CreateRemoval(IList->getLocStart())
665 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000666}
667
Anders Carlsson6cabf312010-01-23 23:23:01 +0000668void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000669 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000670 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000671 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000672 unsigned &Index,
673 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000674 unsigned &StructuredIndex,
675 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000676 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
677 // Explicitly braced initializer for complex type can be real+imaginary
678 // parts.
679 CheckComplexType(Entity, IList, DeclType, Index,
680 StructuredList, StructuredIndex);
681 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000682 CheckScalarType(Entity, IList, DeclType, Index,
683 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000684 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000685 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000686 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000687 } else if (DeclType->isAggregateType()) {
688 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000689 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000690 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000691 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000692 StructuredList, StructuredIndex,
693 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000694 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000695 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000696 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000697 false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000698 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000699 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000700 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000701 } else
David Blaikie83d382b2011-09-23 05:06:16 +0000702 llvm_unreachable("Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000703 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
704 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000705 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000706 if (!VerifyOnly)
707 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
708 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000709 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000710 } else if (DeclType->isRecordType()) {
711 // C++ [dcl.init]p14:
712 // [...] If the class is an aggregate (8.5.1), and the initializer
713 // is a brace-enclosed list, see 8.5.1.
714 //
715 // Note: 8.5.1 is handled below; here, we diagnose the case where
716 // we have an initializer list and a destination type that is not
717 // an aggregate.
718 // FIXME: In C++0x, this is yet another form of initialization.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000719 if (!VerifyOnly)
720 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
721 << DeclType << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +0000722 hadError = true;
723 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000724 CheckReferenceType(Entity, IList, DeclType, Index,
725 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000726 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000727 if (!VerifyOnly)
728 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
729 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000730 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000731 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000732 if (!VerifyOnly)
733 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
734 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000735 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000736 }
737}
738
Anders Carlsson6cabf312010-01-23 23:23:01 +0000739void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000740 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000741 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000742 unsigned &Index,
743 InitListExpr *StructuredList,
744 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000745 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000746 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
747 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000748 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000749 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000750 = getStructuredSubobjectInit(IList, Index, ElemType,
751 StructuredList, StructuredIndex,
752 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000753 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000754 newStructuredList, newStructuredIndex);
755 ++StructuredIndex;
756 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000757 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000758 } else if (ElemType->isScalarType()) {
John McCall5decec92011-02-21 07:57:55 +0000759 return CheckScalarType(Entity, IList, ElemType, Index,
760 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000761 } else if (ElemType->isReferenceType()) {
John McCall5decec92011-02-21 07:57:55 +0000762 return CheckReferenceType(Entity, IList, ElemType, Index,
763 StructuredList, StructuredIndex);
764 }
Anders Carlsson03068aa2009-08-27 17:18:13 +0000765
John McCall5decec92011-02-21 07:57:55 +0000766 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
767 // arrayType can be incomplete if we're initializing a flexible
768 // array member. There's nothing we can do with the completed
769 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000770
John McCall5decec92011-02-21 07:57:55 +0000771 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
Eli Friedmand8d7a372011-09-26 19:09:09 +0000772 if (!VerifyOnly) {
773 CheckStringInit(Str, ElemType, arrayType, SemaRef);
774 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
775 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000776 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000777 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000778 }
John McCall5decec92011-02-21 07:57:55 +0000779
780 // Fall through for subaggregate initialization.
781
782 } else if (SemaRef.getLangOptions().CPlusPlus) {
783 // C++ [dcl.init.aggr]p12:
784 // All implicit type conversions (clause 4) are considered when
Sebastian Redl26bcc942011-09-24 17:47:39 +0000785 // initializing the aggregate member with an initializer from
John McCall5decec92011-02-21 07:57:55 +0000786 // an initializer-list. If the initializer can initialize a
787 // member, the member is initialized. [...]
788
789 // FIXME: Better EqualLoc?
790 InitializationKind Kind =
791 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
792 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
793
794 if (Seq) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000795 if (!VerifyOnly) {
Richard Smith0f8ede12011-12-20 04:00:21 +0000796 ExprResult Result =
797 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
798 if (Result.isInvalid())
799 hadError = true;
John McCall5decec92011-02-21 07:57:55 +0000800
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000801 UpdateStructuredListElement(StructuredList, StructuredIndex,
Richard Smith0f8ede12011-12-20 04:00:21 +0000802 Result.takeAs<Expr>());
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000803 }
John McCall5decec92011-02-21 07:57:55 +0000804 ++Index;
805 return;
806 }
807
808 // Fall through for subaggregate initialization
809 } else {
810 // C99 6.7.8p13:
811 //
812 // The initializer for a structure or union object that has
813 // automatic storage duration shall be either an initializer
814 // list as described below, or a single expression that has
815 // compatible structure or union type. In the latter case, the
816 // initial value of the object, including unnamed members, is
817 // that of the expression.
John Wiegley01296292011-04-08 18:41:53 +0000818 ExprResult ExprRes = SemaRef.Owned(expr);
John McCall5decec92011-02-21 07:57:55 +0000819 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000820 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
821 !VerifyOnly)
John McCall5decec92011-02-21 07:57:55 +0000822 == Sema::Compatible) {
John Wiegley01296292011-04-08 18:41:53 +0000823 if (ExprRes.isInvalid())
824 hadError = true;
825 else {
826 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
827 if (ExprRes.isInvalid())
828 hadError = true;
829 }
830 UpdateStructuredListElement(StructuredList, StructuredIndex,
831 ExprRes.takeAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +0000832 ++Index;
833 return;
834 }
John Wiegley01296292011-04-08 18:41:53 +0000835 ExprRes.release();
John McCall5decec92011-02-21 07:57:55 +0000836 // Fall through for subaggregate initialization
837 }
838
839 // C++ [dcl.init.aggr]p12:
840 //
841 // [...] Otherwise, if the member is itself a non-empty
842 // subaggregate, brace elision is assumed and the initializer is
843 // considered for the initialization of the first member of
844 // the subaggregate.
Tanya Lattner83559382011-07-15 23:07:01 +0000845 if (!SemaRef.getLangOptions().OpenCL &&
846 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCall5decec92011-02-21 07:57:55 +0000847 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
848 StructuredIndex);
849 ++StructuredIndex;
850 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000851 if (!VerifyOnly) {
852 // We cannot initialize this element, so let
853 // PerformCopyInitialization produce the appropriate diagnostic.
854 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
855 SemaRef.Owned(expr),
856 /*TopLevelOfInitList=*/true);
857 }
John McCall5decec92011-02-21 07:57:55 +0000858 hadError = true;
859 ++Index;
860 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +0000861 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000862}
863
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000864void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
865 InitListExpr *IList, QualType DeclType,
866 unsigned &Index,
867 InitListExpr *StructuredList,
868 unsigned &StructuredIndex) {
869 assert(Index == 0 && "Index in explicit init list must be zero");
870
871 // As an extension, clang supports complex initializers, which initialize
872 // a complex number component-wise. When an explicit initializer list for
873 // a complex number contains two two initializers, this extension kicks in:
874 // it exepcts the initializer list to contain two elements convertible to
875 // the element type of the complex type. The first element initializes
876 // the real part, and the second element intitializes the imaginary part.
877
878 if (IList->getNumInits() != 2)
879 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
880 StructuredIndex);
881
882 // This is an extension in C. (The builtin _Complex type does not exist
883 // in the C++ standard.)
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000884 if (!SemaRef.getLangOptions().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000885 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
886 << IList->getSourceRange();
887
888 // Initialize the complex number.
889 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
890 InitializedEntity ElementEntity =
891 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
892
893 for (unsigned i = 0; i < 2; ++i) {
894 ElementEntity.setElementIndex(Index);
895 CheckSubElementType(ElementEntity, IList, elementType, Index,
896 StructuredList, StructuredIndex);
897 }
898}
899
900
Anders Carlsson6cabf312010-01-23 23:23:01 +0000901void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000902 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000903 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000904 InitListExpr *StructuredList,
905 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +0000906 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +0000907 if (!VerifyOnly)
908 SemaRef.Diag(IList->getLocStart(),
909 SemaRef.getLangOptions().CPlusPlus0x ?
910 diag::warn_cxx98_compat_empty_scalar_initializer :
911 diag::err_empty_scalar_initializer)
912 << IList->getSourceRange();
913 hadError = !SemaRef.getLangOptions().CPlusPlus0x;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000914 ++Index;
915 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000916 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000917 }
John McCall643169b2010-11-11 00:46:36 +0000918
919 Expr *expr = IList->getInit(Index);
920 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000921 if (!VerifyOnly)
922 SemaRef.Diag(SubIList->getLocStart(),
923 diag::warn_many_braces_around_scalar_init)
924 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +0000925
926 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
927 StructuredIndex);
928 return;
929 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000930 if (!VerifyOnly)
931 SemaRef.Diag(expr->getSourceRange().getBegin(),
932 diag::err_designator_for_scalar_init)
933 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +0000934 hadError = true;
935 ++Index;
936 ++StructuredIndex;
937 return;
938 }
939
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000940 if (VerifyOnly) {
941 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
942 hadError = true;
943 ++Index;
944 return;
945 }
946
John McCall643169b2010-11-11 00:46:36 +0000947 ExprResult Result =
948 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +0000949 SemaRef.Owned(expr),
950 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +0000951
952 Expr *ResultExpr = 0;
953
954 if (Result.isInvalid())
955 hadError = true; // types weren't compatible.
956 else {
957 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000958
John McCall643169b2010-11-11 00:46:36 +0000959 if (ResultExpr != expr) {
960 // The type was promoted, update initializer list.
961 IList->setInit(Index, ResultExpr);
962 }
963 }
964 if (hadError)
965 ++StructuredIndex;
966 else
967 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
968 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000969}
970
Anders Carlsson6cabf312010-01-23 23:23:01 +0000971void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
972 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000973 unsigned &Index,
974 InitListExpr *StructuredList,
975 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000976 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +0000977 // FIXME: It would be wonderful if we could point at the actual member. In
978 // general, it would be useful to pass location information down the stack,
979 // so that we know the location (or decl) of the "current object" being
980 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000981 if (!VerifyOnly)
982 SemaRef.Diag(IList->getLocStart(),
983 diag::err_init_reference_member_uninitialized)
984 << DeclType
985 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +0000986 hadError = true;
987 ++Index;
988 ++StructuredIndex;
989 return;
990 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000991
992 Expr *expr = IList->getInit(Index);
Sebastian Redl29526f02011-11-27 16:50:07 +0000993 if (isa<InitListExpr>(expr) && !SemaRef.getLangOptions().CPlusPlus0x) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000994 if (!VerifyOnly)
995 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
996 << DeclType << IList->getSourceRange();
997 hadError = true;
998 ++Index;
999 ++StructuredIndex;
1000 return;
1001 }
1002
1003 if (VerifyOnly) {
1004 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1005 hadError = true;
1006 ++Index;
1007 return;
1008 }
1009
1010 ExprResult Result =
1011 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1012 SemaRef.Owned(expr),
1013 /*TopLevelOfInitList=*/true);
1014
1015 if (Result.isInvalid())
1016 hadError = true;
1017
1018 expr = Result.takeAs<Expr>();
1019 IList->setInit(Index, expr);
1020
1021 if (hadError)
1022 ++StructuredIndex;
1023 else
1024 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1025 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001026}
1027
Anders Carlsson6cabf312010-01-23 23:23:01 +00001028void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001029 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001030 unsigned &Index,
1031 InitListExpr *StructuredList,
1032 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001033 const VectorType *VT = DeclType->getAs<VectorType>();
1034 unsigned maxElements = VT->getNumElements();
1035 unsigned numEltsInit = 0;
1036 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001037
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001038 if (Index >= IList->getNumInits()) {
1039 // Make sure the element type can be value-initialized.
1040 if (VerifyOnly)
1041 CheckValueInitializable(
1042 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1043 return;
1044 }
1045
John McCall6a16b2f2010-10-30 00:11:39 +00001046 if (!SemaRef.getLangOptions().OpenCL) {
1047 // If the initializing element is a vector, try to copy-initialize
1048 // instead of breaking it apart (which is doomed to failure anyway).
1049 Expr *Init = IList->getInit(Index);
1050 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001051 if (VerifyOnly) {
1052 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1053 hadError = true;
1054 ++Index;
1055 return;
1056 }
1057
John McCall6a16b2f2010-10-30 00:11:39 +00001058 ExprResult Result =
1059 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001060 SemaRef.Owned(Init),
1061 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001062
1063 Expr *ResultExpr = 0;
1064 if (Result.isInvalid())
1065 hadError = true; // types weren't compatible.
1066 else {
1067 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001068
John McCall6a16b2f2010-10-30 00:11:39 +00001069 if (ResultExpr != Init) {
1070 // The type was promoted, update initializer list.
1071 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001072 }
1073 }
John McCall6a16b2f2010-10-30 00:11:39 +00001074 if (hadError)
1075 ++StructuredIndex;
1076 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001077 UpdateStructuredListElement(StructuredList, StructuredIndex,
1078 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001079 ++Index;
1080 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001081 }
Mike Stump11289f42009-09-09 15:08:12 +00001082
John McCall6a16b2f2010-10-30 00:11:39 +00001083 InitializedEntity ElementEntity =
1084 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001085
John McCall6a16b2f2010-10-30 00:11:39 +00001086 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1087 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001088 if (Index >= IList->getNumInits()) {
1089 if (VerifyOnly)
1090 CheckValueInitializable(ElementEntity);
John McCall6a16b2f2010-10-30 00:11:39 +00001091 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001092 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001093
John McCall6a16b2f2010-10-30 00:11:39 +00001094 ElementEntity.setElementIndex(Index);
1095 CheckSubElementType(ElementEntity, IList, elementType, Index,
1096 StructuredList, StructuredIndex);
1097 }
1098 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001099 }
John McCall6a16b2f2010-10-30 00:11:39 +00001100
1101 InitializedEntity ElementEntity =
1102 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001103
John McCall6a16b2f2010-10-30 00:11:39 +00001104 // OpenCL initializers allows vectors to be constructed from vectors.
1105 for (unsigned i = 0; i < maxElements; ++i) {
1106 // Don't attempt to go past the end of the init list
1107 if (Index >= IList->getNumInits())
1108 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001109
John McCall6a16b2f2010-10-30 00:11:39 +00001110 ElementEntity.setElementIndex(Index);
1111
1112 QualType IType = IList->getInit(Index)->getType();
1113 if (!IType->isVectorType()) {
1114 CheckSubElementType(ElementEntity, IList, elementType, Index,
1115 StructuredList, StructuredIndex);
1116 ++numEltsInit;
1117 } else {
1118 QualType VecType;
1119 const VectorType *IVT = IType->getAs<VectorType>();
1120 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001121
John McCall6a16b2f2010-10-30 00:11:39 +00001122 if (IType->isExtVectorType())
1123 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1124 else
1125 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001126 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001127 CheckSubElementType(ElementEntity, IList, VecType, Index,
1128 StructuredList, StructuredIndex);
1129 numEltsInit += numIElts;
1130 }
1131 }
1132
1133 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001134 if (numEltsInit != maxElements) {
1135 if (!VerifyOnly)
1136 SemaRef.Diag(IList->getSourceRange().getBegin(),
1137 diag::err_vector_incorrect_num_initializers)
1138 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1139 hadError = true;
1140 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001141}
1142
Anders Carlsson6cabf312010-01-23 23:23:01 +00001143void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001144 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001145 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001146 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001147 unsigned &Index,
1148 InitListExpr *StructuredList,
1149 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001150 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1151
Steve Narofff8ecff22008-05-01 22:18:59 +00001152 // Check for the special-case of initializing an array with a string.
1153 if (Index < IList->getNumInits()) {
John McCall66884dd2011-02-21 07:22:22 +00001154 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattnerd8b741c82009-02-24 23:10:27 +00001155 SemaRef.Context)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001156 // We place the string literal directly into the resulting
1157 // initializer list. This is the only place where the structure
1158 // of the structured initializer list doesn't match exactly,
1159 // because doing so would involve allocating one character
1160 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001161 if (!VerifyOnly) {
Eli Friedmand8d7a372011-09-26 19:09:09 +00001162 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001163 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1164 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1165 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001166 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001167 return;
1168 }
1169 }
John McCall66884dd2011-02-21 07:22:22 +00001170 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001171 // Check for VLAs; in standard C it would be possible to check this
1172 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1173 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001174 if (!VerifyOnly)
1175 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1176 diag::err_variable_object_no_init)
1177 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001178 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001179 ++Index;
1180 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001181 return;
1182 }
1183
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001184 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001185 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1186 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001187 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001188 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001189 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001190 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001191 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001192 maxElementsKnown = true;
1193 }
1194
John McCall66884dd2011-02-21 07:22:22 +00001195 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001196 while (Index < IList->getNumInits()) {
1197 Expr *Init = IList->getInit(Index);
1198 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001199 // If we're not the subobject that matches up with the '{' for
1200 // the designator, we shouldn't be handling the
1201 // designator. Return immediately.
1202 if (!SubobjectIsDesignatorContext)
1203 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001204
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001205 // Handle this designated initializer. elementIndex will be
1206 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001207 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001208 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001209 StructuredList, StructuredIndex, true,
1210 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001211 hadError = true;
1212 continue;
1213 }
1214
Douglas Gregor033d1252009-01-23 16:54:12 +00001215 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001216 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001217 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001218 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001219 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001220
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001221 // If the array is of incomplete type, keep track of the number of
1222 // elements in the initializer.
1223 if (!maxElementsKnown && elementIndex > maxElements)
1224 maxElements = elementIndex;
1225
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001226 continue;
1227 }
1228
1229 // If we know the maximum number of elements, and we've already
1230 // hit it, stop consuming elements in the initializer list.
1231 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001232 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001233
Anders Carlsson6cabf312010-01-23 23:23:01 +00001234 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001235 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001236 Entity);
1237 // Check this element.
1238 CheckSubElementType(ElementEntity, IList, elementType, Index,
1239 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001240 ++elementIndex;
1241
1242 // If the array is of incomplete type, keep track of the number of
1243 // elements in the initializer.
1244 if (!maxElementsKnown && elementIndex > maxElements)
1245 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001246 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001247 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001248 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001249 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001250 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001251 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001252 // Sizing an array implicitly to zero is not allowed by ISO C,
1253 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001254 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001255 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001256 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001257
Mike Stump11289f42009-09-09 15:08:12 +00001258 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001259 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001260 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001261 if (!hadError && VerifyOnly) {
1262 // Check if there are any members of the array that get value-initialized.
1263 // If so, check if doing that is possible.
1264 // FIXME: This needs to detect holes left by designated initializers too.
1265 if (maxElementsKnown && elementIndex < maxElements)
1266 CheckValueInitializable(InitializedEntity::InitializeElement(
1267 SemaRef.Context, 0, Entity));
1268 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001269}
1270
Eli Friedman3fa64df2011-08-23 22:24:57 +00001271bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1272 Expr *InitExpr,
1273 FieldDecl *Field,
1274 bool TopLevelObject) {
1275 // Handle GNU flexible array initializers.
1276 unsigned FlexArrayDiag;
1277 if (isa<InitListExpr>(InitExpr) &&
1278 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1279 // Empty flexible array init always allowed as an extension
1280 FlexArrayDiag = diag::ext_flexible_array_init;
1281 } else if (SemaRef.getLangOptions().CPlusPlus) {
1282 // Disallow flexible array init in C++; it is not required for gcc
1283 // compatibility, and it needs work to IRGen correctly in general.
1284 FlexArrayDiag = diag::err_flexible_array_init;
1285 } else if (!TopLevelObject) {
1286 // Disallow flexible array init on non-top-level object
1287 FlexArrayDiag = diag::err_flexible_array_init;
1288 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1289 // Disallow flexible array init on anything which is not a variable.
1290 FlexArrayDiag = diag::err_flexible_array_init;
1291 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1292 // Disallow flexible array init on local variables.
1293 FlexArrayDiag = diag::err_flexible_array_init;
1294 } else {
1295 // Allow other cases.
1296 FlexArrayDiag = diag::ext_flexible_array_init;
1297 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001298
1299 if (!VerifyOnly) {
1300 SemaRef.Diag(InitExpr->getSourceRange().getBegin(),
1301 FlexArrayDiag)
1302 << InitExpr->getSourceRange().getBegin();
1303 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1304 << Field;
1305 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001306
1307 return FlexArrayDiag != diag::ext_flexible_array_init;
1308}
1309
Anders Carlsson6cabf312010-01-23 23:23:01 +00001310void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001311 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001312 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001313 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001314 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001315 unsigned &Index,
1316 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001317 unsigned &StructuredIndex,
1318 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001319 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001320
Eli Friedman23a9e312008-05-19 19:16:24 +00001321 // If the record is invalid, some of it's members are invalid. To avoid
1322 // confusion, we forgo checking the intializer for the entire record.
1323 if (structDecl->isInvalidDecl()) {
1324 hadError = true;
1325 return;
Mike Stump11289f42009-09-09 15:08:12 +00001326 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001327
1328 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001329 // Value-initialize the first named member of the union.
1330 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1331 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1332 Field != FieldEnd; ++Field) {
1333 if (Field->getDeclName()) {
1334 if (VerifyOnly)
1335 CheckValueInitializable(
1336 InitializedEntity::InitializeMember(*Field, &Entity));
1337 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001338 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001339 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001340 }
1341 }
1342 return;
1343 }
1344
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001345 // If structDecl is a forward declaration, this loop won't do
1346 // anything except look at designated initializers; That's okay,
1347 // because an error should get printed out elsewhere. It might be
1348 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001349 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001350 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001351 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001352 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001353 while (Index < IList->getNumInits()) {
1354 Expr *Init = IList->getInit(Index);
1355
1356 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001357 // If we're not the subobject that matches up with the '{' for
1358 // the designator, we shouldn't be handling the
1359 // designator. Return immediately.
1360 if (!SubobjectIsDesignatorContext)
1361 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001362
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001363 // Handle this designated initializer. Field will be updated to
1364 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001365 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001366 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001367 StructuredList, StructuredIndex,
1368 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001369 hadError = true;
1370
Douglas Gregora9add4e2009-02-12 19:00:39 +00001371 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001372
1373 // Disable check for missing fields when designators are used.
1374 // This matches gcc behaviour.
1375 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001376 continue;
1377 }
1378
1379 if (Field == FieldEnd) {
1380 // We've run out of fields. We're done.
1381 break;
1382 }
1383
Douglas Gregora9add4e2009-02-12 19:00:39 +00001384 // We've already initialized a member of a union. We're done.
1385 if (InitializedSomething && DeclType->isUnionType())
1386 break;
1387
Douglas Gregor91f84212008-12-11 16:49:14 +00001388 // If we've hit the flexible array member at the end, we're done.
1389 if (Field->getType()->isIncompleteArrayType())
1390 break;
1391
Douglas Gregor51695702009-01-29 16:53:55 +00001392 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001393 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001394 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001395 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001396 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001397
Douglas Gregora82064c2011-06-29 21:51:31 +00001398 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001399 bool InvalidUse;
1400 if (VerifyOnly)
1401 InvalidUse = !SemaRef.CanUseDecl(*Field);
1402 else
1403 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1404 IList->getInit(Index)->getLocStart());
1405 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001406 ++Index;
1407 ++Field;
1408 hadError = true;
1409 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001410 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001411
Anders Carlsson6cabf312010-01-23 23:23:01 +00001412 InitializedEntity MemberEntity =
1413 InitializedEntity::InitializeMember(*Field, &Entity);
1414 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1415 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001416 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001417
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001418 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001419 // Initialize the first field within the union.
1420 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001421 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001422
1423 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001424 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001425
John McCalle40b58e2010-03-11 19:32:38 +00001426 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001427 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1428 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1429 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001430 // It is possible we have one or more unnamed bitfields remaining.
1431 // Find first (if any) named field and emit warning.
1432 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1433 it != end; ++it) {
1434 if (!it->isUnnamedBitfield()) {
1435 SemaRef.Diag(IList->getSourceRange().getEnd(),
1436 diag::warn_missing_field_initializers) << it->getName();
1437 break;
1438 }
1439 }
1440 }
1441
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001442 // Check that any remaining fields can be value-initialized.
1443 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1444 !Field->getType()->isIncompleteArrayType()) {
1445 // FIXME: Should check for holes left by designated initializers too.
1446 for (; Field != FieldEnd && !hadError; ++Field) {
1447 if (!Field->isUnnamedBitfield())
1448 CheckValueInitializable(
1449 InitializedEntity::InitializeMember(*Field, &Entity));
1450 }
1451 }
1452
Mike Stump11289f42009-09-09 15:08:12 +00001453 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001454 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001455 return;
1456
Eli Friedman3fa64df2011-08-23 22:24:57 +00001457 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1458 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001459 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001460 ++Index;
1461 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001462 }
1463
Anders Carlsson6cabf312010-01-23 23:23:01 +00001464 InitializedEntity MemberEntity =
1465 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001466
Anders Carlsson6cabf312010-01-23 23:23:01 +00001467 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001468 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001469 StructuredList, StructuredIndex);
1470 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001471 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001472 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001473}
Steve Narofff8ecff22008-05-01 22:18:59 +00001474
Douglas Gregord5846a12009-04-15 06:41:24 +00001475/// \brief Expand a field designator that refers to a member of an
1476/// anonymous struct or union into a series of field designators that
1477/// refers to the field within the appropriate subobject.
1478///
Douglas Gregord5846a12009-04-15 06:41:24 +00001479static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001480 DesignatedInitExpr *DIE,
1481 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001482 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001483 typedef DesignatedInitExpr::Designator Designator;
1484
Douglas Gregord5846a12009-04-15 06:41:24 +00001485 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001486 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001487 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1488 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1489 if (PI + 1 == PE)
Mike Stump11289f42009-09-09 15:08:12 +00001490 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001491 DIE->getDesignator(DesigIdx)->getDotLoc(),
1492 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1493 else
1494 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1495 SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001496 assert(isa<FieldDecl>(*PI));
1497 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001498 }
1499
1500 // Expand the current designator into the set of replacement
1501 // designators, so we have a full subobject path down to where the
1502 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001503 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001504 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001505}
Mike Stump11289f42009-09-09 15:08:12 +00001506
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001507/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001508/// corresponds to FieldName.
1509static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1510 IdentifierInfo *FieldName) {
1511 assert(AnonField->isAnonymousStructOrUnion());
1512 Decl *NextDecl = AnonField->getNextDeclInContext();
1513 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1514 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1515 return IF;
1516 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001517 }
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001518 return 0;
Douglas Gregord5846a12009-04-15 06:41:24 +00001519}
1520
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001521static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1522 DesignatedInitExpr *DIE) {
1523 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1524 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1525 for (unsigned I = 0; I < NumIndexExprs; ++I)
1526 IndexExprs[I] = DIE->getSubExpr(I + 1);
1527 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1528 DIE->size(), IndexExprs.data(),
1529 NumIndexExprs, DIE->getEqualOrColonLoc(),
1530 DIE->usesGNUSyntax(), DIE->getInit());
1531}
1532
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001533namespace {
1534
1535// Callback to only accept typo corrections that are for field members of
1536// the given struct or union.
1537class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1538 public:
1539 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1540 : Record(RD) {}
1541
1542 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1543 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1544 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1545 }
1546
1547 private:
1548 RecordDecl *Record;
1549};
1550
1551}
1552
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001553/// @brief Check the well-formedness of a C99 designated initializer.
1554///
1555/// Determines whether the designated initializer @p DIE, which
1556/// resides at the given @p Index within the initializer list @p
1557/// IList, is well-formed for a current object of type @p DeclType
1558/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001559/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001560/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001561///
1562/// @param IList The initializer list in which this designated
1563/// initializer occurs.
1564///
Douglas Gregora5324162009-04-15 04:56:10 +00001565/// @param DIE The designated initializer expression.
1566///
1567/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001568///
1569/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1570/// into which the designation in @p DIE should refer.
1571///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001572/// @param NextField If non-NULL and the first designator in @p DIE is
1573/// a field, this will be set to the field declaration corresponding
1574/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001575///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001576/// @param NextElementIndex If non-NULL and the first designator in @p
1577/// DIE is an array designator or GNU array-range designator, this
1578/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001579///
1580/// @param Index Index into @p IList where the designated initializer
1581/// @p DIE occurs.
1582///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001583/// @param StructuredList The initializer list expression that
1584/// describes all of the subobject initializers in the order they'll
1585/// actually be initialized.
1586///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001587/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001588bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001589InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001590 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001591 DesignatedInitExpr *DIE,
1592 unsigned DesigIdx,
1593 QualType &CurrentObjectType,
1594 RecordDecl::field_iterator *NextField,
1595 llvm::APSInt *NextElementIndex,
1596 unsigned &Index,
1597 InitListExpr *StructuredList,
1598 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001599 bool FinishSubobjectInit,
1600 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001601 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001602 // Check the actual initialization for the designated object type.
1603 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001604
1605 // Temporarily remove the designator expression from the
1606 // initializer list that the child calls see, so that we don't try
1607 // to re-process the designator.
1608 unsigned OldIndex = Index;
1609 IList->setInit(OldIndex, DIE->getInit());
1610
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001611 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001612 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001613
1614 // Restore the designated initializer expression in the syntactic
1615 // form of the initializer list.
1616 if (IList->getInit(OldIndex) != DIE->getInit())
1617 DIE->setInit(IList->getInit(OldIndex));
1618 IList->setInit(OldIndex, DIE);
1619
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001620 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001621 }
1622
Douglas Gregora5324162009-04-15 04:56:10 +00001623 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001624 bool IsFirstDesignator = (DesigIdx == 0);
1625 if (!VerifyOnly) {
1626 assert((IsFirstDesignator || StructuredList) &&
1627 "Need a non-designated initializer list to start from");
1628
1629 // Determine the structural initializer list that corresponds to the
1630 // current subobject.
1631 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1632 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1633 StructuredList, StructuredIndex,
1634 SourceRange(D->getStartLocation(),
1635 DIE->getSourceRange().getEnd()));
1636 assert(StructuredList && "Expected a structured initializer list");
1637 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001638
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001639 if (D->isFieldDesignator()) {
1640 // C99 6.7.8p7:
1641 //
1642 // If a designator has the form
1643 //
1644 // . identifier
1645 //
1646 // then the current object (defined below) shall have
1647 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001648 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001649 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001650 if (!RT) {
1651 SourceLocation Loc = D->getDotLoc();
1652 if (Loc.isInvalid())
1653 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001654 if (!VerifyOnly)
1655 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1656 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001657 ++Index;
1658 return true;
1659 }
1660
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001661 // Note: we perform a linear search of the fields here, despite
1662 // the fact that we have a faster lookup method, because we always
1663 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001664 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001665 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001666 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001667 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001668 Field = RT->getDecl()->field_begin(),
1669 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001670 for (; Field != FieldEnd; ++Field) {
1671 if (Field->isUnnamedBitfield())
1672 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001673
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001674 // If we find a field representing an anonymous field, look in the
1675 // IndirectFieldDecl that follow for the designated initializer.
1676 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1677 if (IndirectFieldDecl *IF =
1678 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001679 // In verify mode, don't modify the original.
1680 if (VerifyOnly)
1681 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001682 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1683 D = DIE->getDesignator(DesigIdx);
1684 break;
1685 }
1686 }
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001687 if (KnownField && KnownField == *Field)
1688 break;
1689 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001690 break;
1691
1692 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001693 }
1694
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001695 if (Field == FieldEnd) {
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001696 if (VerifyOnly) {
1697 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001698 return true; // No typo correction when just trying this out.
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001699 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001700
Douglas Gregord5846a12009-04-15 06:41:24 +00001701 // There was no normal field in the struct with the designated
1702 // name. Perform another lookup for this name, which may find
1703 // something that we can't designate (e.g., a member function),
1704 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001705 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001706 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001707 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001708 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001709 // Name lookup didn't find anything. Determine whether this
1710 // was a typo for another field name.
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001711 FieldInitializerValidatorCCC Validator(RT->getDecl());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001712 TypoCorrection Corrected = SemaRef.CorrectTypo(
1713 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001714 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator,
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001715 RT->getDecl());
1716 if (Corrected) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001717 std::string CorrectedStr(
1718 Corrected.getAsString(SemaRef.getLangOptions()));
1719 std::string CorrectedQuotedStr(
1720 Corrected.getQuoted(SemaRef.getLangOptions()));
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001721 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001722 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001723 diag::err_field_designator_unknown_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001724 << FieldName << CurrentObjectType << CorrectedQuotedStr
1725 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001726 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001727 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001728 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001729 } else {
1730 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1731 << FieldName << CurrentObjectType;
1732 ++Index;
1733 return true;
1734 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001735 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001736
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001737 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001738 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001739 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001740 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001741 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001742 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001743 ++Index;
1744 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001745 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001746
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001747 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001748 // The replacement field comes from typo correction; find it
1749 // in the list of fields.
1750 FieldIndex = 0;
1751 Field = RT->getDecl()->field_begin();
1752 for (; Field != FieldEnd; ++Field) {
1753 if (Field->isUnnamedBitfield())
1754 continue;
1755
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001756 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001757 Field->getIdentifier() == ReplacementField->getIdentifier())
1758 break;
1759
1760 ++FieldIndex;
1761 }
1762 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001763 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001764
1765 // All of the fields of a union are located at the same place in
1766 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001767 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001768 FieldIndex = 0;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001769 if (!VerifyOnly)
1770 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001771 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001772
Douglas Gregora82064c2011-06-29 21:51:31 +00001773 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001774 bool InvalidUse;
1775 if (VerifyOnly)
1776 InvalidUse = !SemaRef.CanUseDecl(*Field);
1777 else
1778 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1779 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001780 ++Index;
1781 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001782 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001783
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001784 if (!VerifyOnly) {
1785 // Update the designator with the field declaration.
1786 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001787
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001788 // Make sure that our non-designated initializer list has space
1789 // for a subobject corresponding to this field.
1790 if (FieldIndex >= StructuredList->getNumInits())
1791 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1792 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001793
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001794 // This designator names a flexible array member.
1795 if (Field->getType()->isIncompleteArrayType()) {
1796 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001797 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001798 // We can't designate an object within the flexible array
1799 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001800 if (!VerifyOnly) {
1801 DesignatedInitExpr::Designator *NextD
1802 = DIE->getDesignator(DesigIdx + 1);
1803 SemaRef.Diag(NextD->getStartLocation(),
1804 diag::err_designator_into_flexible_array_member)
1805 << SourceRange(NextD->getStartLocation(),
1806 DIE->getSourceRange().getEnd());
1807 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1808 << *Field;
1809 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001810 Invalid = true;
1811 }
1812
Chris Lattner001b29c2010-10-10 17:49:49 +00001813 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1814 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001815 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001816 if (!VerifyOnly) {
1817 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
1818 diag::err_flexible_array_init_needs_braces)
1819 << DIE->getInit()->getSourceRange();
1820 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1821 << *Field;
1822 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001823 Invalid = true;
1824 }
1825
Eli Friedman3fa64df2011-08-23 22:24:57 +00001826 // Check GNU flexible array initializer.
1827 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1828 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001829 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001830
1831 if (Invalid) {
1832 ++Index;
1833 return true;
1834 }
1835
1836 // Initialize the array.
1837 bool prevHadError = hadError;
1838 unsigned newStructuredIndex = FieldIndex;
1839 unsigned OldIndex = Index;
1840 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001841
1842 InitializedEntity MemberEntity =
1843 InitializedEntity::InitializeMember(*Field, &Entity);
1844 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001845 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001846
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001847 IList->setInit(OldIndex, DIE);
1848 if (hadError && !prevHadError) {
1849 ++Field;
1850 ++FieldIndex;
1851 if (NextField)
1852 *NextField = Field;
1853 StructuredIndex = FieldIndex;
1854 return true;
1855 }
1856 } else {
1857 // Recurse to check later designated subobjects.
1858 QualType FieldType = (*Field)->getType();
1859 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001860
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001861 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001862 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001863 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1864 FieldType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001865 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001866 true, false))
1867 return true;
1868 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001869
1870 // Find the position of the next field to be initialized in this
1871 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001872 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001873 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001874
1875 // If this the first designator, our caller will continue checking
1876 // the rest of this struct/class/union subobject.
1877 if (IsFirstDesignator) {
1878 if (NextField)
1879 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001880 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001881 return false;
1882 }
1883
Douglas Gregor17bd0942009-01-28 23:36:17 +00001884 if (!FinishSubobjectInit)
1885 return false;
1886
Douglas Gregord5846a12009-04-15 06:41:24 +00001887 // We've already initialized something in the union; we're done.
1888 if (RT->getDecl()->isUnion())
1889 return hadError;
1890
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001891 // Check the remaining fields within this class/struct/union subobject.
1892 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001893
Anders Carlsson6cabf312010-01-23 23:23:01 +00001894 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001895 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001896 return hadError && !prevHadError;
1897 }
1898
1899 // C99 6.7.8p6:
1900 //
1901 // If a designator has the form
1902 //
1903 // [ constant-expression ]
1904 //
1905 // then the current object (defined below) shall have array
1906 // type and the expression shall be an integer constant
1907 // expression. If the array is of unknown size, any
1908 // nonnegative value is valid.
1909 //
1910 // Additionally, cope with the GNU extension that permits
1911 // designators of the form
1912 //
1913 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001914 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001915 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001916 if (!VerifyOnly)
1917 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1918 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001919 ++Index;
1920 return true;
1921 }
1922
1923 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001924 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1925 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001926 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00001927 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001928 DesignatedEndIndex = DesignatedStartIndex;
1929 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001930 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001931
Mike Stump11289f42009-09-09 15:08:12 +00001932 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00001933 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001934 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00001935 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001936 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001937
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00001938 // Codegen can't handle evaluating array range designators that have side
1939 // effects, because we replicate the AST value for each initialized element.
1940 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1941 // elements with something that has a side effect, so codegen can emit an
1942 // "error unsupported" error instead of miscompiling the app.
1943 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001944 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001945 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001946 }
1947
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001948 if (isa<ConstantArrayType>(AT)) {
1949 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001950 DesignatedStartIndex
1951 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001952 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00001953 DesignatedEndIndex
1954 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001955 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1956 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00001957 if (!VerifyOnly)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001958 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
1959 diag::err_array_designator_too_large)
1960 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1961 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001962 ++Index;
1963 return true;
1964 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001965 } else {
1966 // Make sure the bit-widths and signedness match.
1967 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001968 DesignatedEndIndex
1969 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001970 else if (DesignatedStartIndex.getBitWidth() <
1971 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001972 DesignatedStartIndex
1973 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001974 DesignatedStartIndex.setIsUnsigned(true);
1975 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001976 }
Mike Stump11289f42009-09-09 15:08:12 +00001977
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001978 // Make sure that our non-designated initializer list has space
1979 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001980 if (!VerifyOnly &&
1981 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001982 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001983 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001984
Douglas Gregor17bd0942009-01-28 23:36:17 +00001985 // Repeatedly perform subobject initializations in the range
1986 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001987
Douglas Gregor17bd0942009-01-28 23:36:17 +00001988 // Move to the next designator
1989 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1990 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001991
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001992 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001993 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001994
Douglas Gregor17bd0942009-01-28 23:36:17 +00001995 while (DesignatedStartIndex <= DesignatedEndIndex) {
1996 // Recurse to check later designated subobjects.
1997 QualType ElementType = AT->getElementType();
1998 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001999
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002000 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002001 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2002 ElementType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002003 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002004 (DesignatedStartIndex == DesignatedEndIndex),
2005 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002006 return true;
2007
2008 // Move to the next index in the array that we'll be initializing.
2009 ++DesignatedStartIndex;
2010 ElementIndex = DesignatedStartIndex.getZExtValue();
2011 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002012
2013 // If this the first designator, our caller will continue checking
2014 // the rest of this array subobject.
2015 if (IsFirstDesignator) {
2016 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002017 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002018 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002019 return false;
2020 }
Mike Stump11289f42009-09-09 15:08:12 +00002021
Douglas Gregor17bd0942009-01-28 23:36:17 +00002022 if (!FinishSubobjectInit)
2023 return false;
2024
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002025 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002026 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002027 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002028 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002029 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002030 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002031}
2032
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002033// Get the structured initializer list for a subobject of type
2034// @p CurrentObjectType.
2035InitListExpr *
2036InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2037 QualType CurrentObjectType,
2038 InitListExpr *StructuredList,
2039 unsigned StructuredIndex,
2040 SourceRange InitRange) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002041 if (VerifyOnly)
2042 return 0; // No structured list in verification-only mode.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002043 Expr *ExistingInit = 0;
2044 if (!StructuredList)
2045 ExistingInit = SyntacticToSemantic[IList];
2046 else if (StructuredIndex < StructuredList->getNumInits())
2047 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002048
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002049 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2050 return Result;
2051
2052 if (ExistingInit) {
2053 // We are creating an initializer list that initializes the
2054 // subobjects of the current object, but there was already an
2055 // initialization that completely initialized the current
2056 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002057 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002058 // struct X { int a, b; };
2059 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002060 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002061 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2062 // designated initializer re-initializes the whole
2063 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002064 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002065 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002066 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00002067 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002068 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002069 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002070 << ExistingInit->getSourceRange();
2071 }
2072
Mike Stump11289f42009-09-09 15:08:12 +00002073 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002074 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2075 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00002076 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002077
Douglas Gregora8a089b2010-07-13 18:40:04 +00002078 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002079
Douglas Gregor6d00c992009-03-20 23:58:33 +00002080 // Pre-allocate storage for the structured initializer list.
2081 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002082 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002083 bool GotNumInits = false;
2084 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002085 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002086 GotNumInits = true;
2087 } else if (Index < IList->getNumInits()) {
2088 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002089 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002090 GotNumInits = true;
2091 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002092 }
2093
Mike Stump11289f42009-09-09 15:08:12 +00002094 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002095 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2096 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2097 NumElements = CAType->getSize().getZExtValue();
2098 // Simple heuristic so that we don't allocate a very large
2099 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002100 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002101 NumElements = 0;
2102 }
John McCall9dd450b2009-09-21 23:43:11 +00002103 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002104 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002105 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002106 RecordDecl *RDecl = RType->getDecl();
2107 if (RDecl->isUnion())
2108 NumElements = 1;
2109 else
Mike Stump11289f42009-09-09 15:08:12 +00002110 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002111 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002112 }
2113
Ted Kremenekac034612010-04-13 23:39:13 +00002114 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002115
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002116 // Link this new initializer list into the structured initializer
2117 // lists.
2118 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002119 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002120 else {
2121 Result->setSyntacticForm(IList);
2122 SyntacticToSemantic[IList] = Result;
2123 }
2124
2125 return Result;
2126}
2127
2128/// Update the initializer at index @p StructuredIndex within the
2129/// structured initializer list to the value @p expr.
2130void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2131 unsigned &StructuredIndex,
2132 Expr *expr) {
2133 // No structured initializer list to update
2134 if (!StructuredList)
2135 return;
2136
Ted Kremenekac034612010-04-13 23:39:13 +00002137 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2138 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002139 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00002140 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002141 diag::warn_initializer_overrides)
2142 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002143 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002144 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002145 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002146 << PrevInit->getSourceRange();
2147 }
Mike Stump11289f42009-09-09 15:08:12 +00002148
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002149 ++StructuredIndex;
2150}
2151
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002152/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002153/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002154/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002155/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002156/// failure. Returns the index expression, possibly with an implicit cast
2157/// added, on success. If everything went okay, Value will receive the
2158/// value of the constant expression.
2159static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002160CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002161 SourceLocation Loc = Index->getSourceRange().getBegin();
2162
2163 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002164 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2165 if (Result.isInvalid())
2166 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002167
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002168 if (Value.isSigned() && Value.isNegative())
2169 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002170 << Value.toString(10) << Index->getSourceRange();
2171
Douglas Gregor51650d32009-01-23 21:04:18 +00002172 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002173 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002174}
2175
John McCalldadc5752010-08-24 06:29:42 +00002176ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002177 SourceLocation Loc,
2178 bool GNUSyntax,
2179 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002180 typedef DesignatedInitExpr::Designator ASTDesignator;
2181
2182 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002183 SmallVector<ASTDesignator, 32> Designators;
2184 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002185
2186 // Build designators and check array designator expressions.
2187 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2188 const Designator &D = Desig.getDesignator(Idx);
2189 switch (D.getKind()) {
2190 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002191 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002192 D.getFieldLoc()));
2193 break;
2194
2195 case Designator::ArrayDesignator: {
2196 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2197 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00002198 if (!Index->isTypeDependent() && !Index->isValueDependent())
2199 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2200 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002201 Invalid = true;
2202 else {
2203 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002204 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002205 D.getRBracketLoc()));
2206 InitExpressions.push_back(Index);
2207 }
2208 break;
2209 }
2210
2211 case Designator::ArrayRangeDesignator: {
2212 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2213 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2214 llvm::APSInt StartValue;
2215 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002216 bool StartDependent = StartIndex->isTypeDependent() ||
2217 StartIndex->isValueDependent();
2218 bool EndDependent = EndIndex->isTypeDependent() ||
2219 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00002220 if (!StartDependent)
2221 StartIndex =
2222 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2223 if (!EndDependent)
2224 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2225
2226 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002227 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002228 else {
2229 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002230 if (StartDependent || EndDependent) {
2231 // Nothing to compute.
2232 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002233 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002234 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002235 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002236
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002237 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002238 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002239 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002240 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2241 Invalid = true;
2242 } else {
2243 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002244 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002245 D.getEllipsisLoc(),
2246 D.getRBracketLoc()));
2247 InitExpressions.push_back(StartIndex);
2248 InitExpressions.push_back(EndIndex);
2249 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002250 }
2251 break;
2252 }
2253 }
2254 }
2255
2256 if (Invalid || Init.isInvalid())
2257 return ExprError();
2258
2259 // Clear out the expressions within the designation.
2260 Desig.ClearExprs(*this);
2261
2262 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002263 = DesignatedInitExpr::Create(Context,
2264 Designators.data(), Designators.size(),
2265 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00002266 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002267
Richard Smithe4345902011-12-29 21:57:33 +00002268 if (!getLangOptions().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002269 Diag(DIE->getLocStart(), diag::ext_designated_init)
2270 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002271
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002272 return Owned(DIE);
2273}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002274
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002275//===----------------------------------------------------------------------===//
2276// Initialization entity
2277//===----------------------------------------------------------------------===//
2278
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002279InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002280 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002281 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002282{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002283 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2284 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002285 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002286 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002287 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002288 Type = VT->getElementType();
2289 } else {
2290 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2291 assert(CT && "Unexpected type");
2292 Kind = EK_ComplexElement;
2293 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002294 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002295}
2296
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002297InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002298 CXXBaseSpecifier *Base,
2299 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002300{
2301 InitializedEntity Result;
2302 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002303 Result.Base = reinterpret_cast<uintptr_t>(Base);
2304 if (IsInheritedVirtualBase)
2305 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002306
Douglas Gregor1b303932009-12-22 15:35:07 +00002307 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002308 return Result;
2309}
2310
Douglas Gregor85dabae2009-12-16 01:38:02 +00002311DeclarationName InitializedEntity::getName() const {
2312 switch (getKind()) {
John McCall31168b02011-06-15 23:02:42 +00002313 case EK_Parameter: {
2314 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2315 return (D ? D->getDeclName() : DeclarationName());
2316 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002317
2318 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002319 case EK_Member:
2320 return VariableOrMember->getDeclName();
2321
2322 case EK_Result:
2323 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002324 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002325 case EK_Temporary:
2326 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002327 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002328 case EK_ArrayElement:
2329 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002330 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002331 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002332 return DeclarationName();
2333 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002334
David Blaikie8a40f702012-01-17 06:56:22 +00002335 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00002336}
2337
Douglas Gregora4b592a2009-12-19 03:01:41 +00002338DeclaratorDecl *InitializedEntity::getDecl() const {
2339 switch (getKind()) {
2340 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002341 case EK_Member:
2342 return VariableOrMember;
2343
John McCall31168b02011-06-15 23:02:42 +00002344 case EK_Parameter:
2345 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2346
Douglas Gregora4b592a2009-12-19 03:01:41 +00002347 case EK_Result:
2348 case EK_Exception:
2349 case EK_New:
2350 case EK_Temporary:
2351 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002352 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002353 case EK_ArrayElement:
2354 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002355 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002356 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002357 return 0;
2358 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002359
David Blaikie8a40f702012-01-17 06:56:22 +00002360 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00002361}
2362
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002363bool InitializedEntity::allowsNRVO() const {
2364 switch (getKind()) {
2365 case EK_Result:
2366 case EK_Exception:
2367 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002368
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002369 case EK_Variable:
2370 case EK_Parameter:
2371 case EK_Member:
2372 case EK_New:
2373 case EK_Temporary:
2374 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002375 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002376 case EK_ArrayElement:
2377 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002378 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002379 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002380 break;
2381 }
2382
2383 return false;
2384}
2385
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002386//===----------------------------------------------------------------------===//
2387// Initialization sequence
2388//===----------------------------------------------------------------------===//
2389
2390void InitializationSequence::Step::Destroy() {
2391 switch (Kind) {
2392 case SK_ResolveAddressOfOverloadedFunction:
2393 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002394 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002395 case SK_CastDerivedToBaseLValue:
2396 case SK_BindReference:
2397 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002398 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002399 case SK_UserConversion:
2400 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002401 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002402 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002403 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002404 case SK_ListConstructorCall:
Sebastian Redl29526f02011-11-27 16:50:07 +00002405 case SK_UnwrapInitList:
2406 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002407 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002408 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002409 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002410 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002411 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002412 case SK_ArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002413 case SK_PassByIndirectCopyRestore:
2414 case SK_PassByIndirectRestore:
2415 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00002416 case SK_StdInitializerList:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002417 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002418
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002419 case SK_ConversionSequence:
2420 delete ICS;
2421 }
2422}
2423
Douglas Gregor838fcc32010-03-26 20:14:36 +00002424bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002425 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002426}
2427
2428bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002429 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002430 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002431
Douglas Gregor838fcc32010-03-26 20:14:36 +00002432 switch (getFailureKind()) {
2433 case FK_TooManyInitsForReference:
2434 case FK_ArrayNeedsInitList:
2435 case FK_ArrayNeedsInitListOrStringLiteral:
2436 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2437 case FK_NonConstLValueReferenceBindingToTemporary:
2438 case FK_NonConstLValueReferenceBindingToUnrelated:
2439 case FK_RValueReferenceBindingToLValue:
2440 case FK_ReferenceInitDropsQualifiers:
2441 case FK_ReferenceInitFailed:
2442 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002443 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002444 case FK_TooManyInitsForScalar:
2445 case FK_ReferenceBindingToInitList:
2446 case FK_InitListBadDestinationType:
2447 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002448 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002449 case FK_ArrayTypeMismatch:
2450 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002451 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00002452 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00002453 case FK_PlaceholderType:
Sebastian Redlc1839b12012-01-17 22:49:42 +00002454 case FK_InitListElementCopyFailure:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002455 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002456
Douglas Gregor838fcc32010-03-26 20:14:36 +00002457 case FK_ReferenceInitOverloadFailed:
2458 case FK_UserConversionOverloadFailed:
2459 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002460 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002461 return FailedOverloadResult == OR_Ambiguous;
2462 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002463
David Blaikie8a40f702012-01-17 06:56:22 +00002464 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00002465}
2466
Douglas Gregorb33eed02010-04-16 22:09:46 +00002467bool InitializationSequence::isConstructorInitialization() const {
2468 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2469}
2470
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002471void
2472InitializationSequence
2473::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2474 DeclAccessPair Found,
2475 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002476 Step S;
2477 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2478 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002479 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002480 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002481 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002482 Steps.push_back(S);
2483}
2484
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002485void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002486 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002487 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002488 switch (VK) {
2489 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2490 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2491 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002492 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002493 S.Type = BaseType;
2494 Steps.push_back(S);
2495}
2496
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002497void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002498 bool BindingTemporary) {
2499 Step S;
2500 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2501 S.Type = T;
2502 Steps.push_back(S);
2503}
2504
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002505void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2506 Step S;
2507 S.Kind = SK_ExtraneousCopyToTemporary;
2508 S.Type = T;
2509 Steps.push_back(S);
2510}
2511
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002512void
2513InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2514 DeclAccessPair FoundDecl,
2515 QualType T,
2516 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002517 Step S;
2518 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002519 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002520 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002521 S.Function.Function = Function;
2522 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002523 Steps.push_back(S);
2524}
2525
2526void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002527 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002528 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002529 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002530 switch (VK) {
2531 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002532 S.Kind = SK_QualificationConversionRValue;
2533 break;
John McCall2536c6d2010-08-25 10:28:54 +00002534 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002535 S.Kind = SK_QualificationConversionXValue;
2536 break;
John McCall2536c6d2010-08-25 10:28:54 +00002537 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002538 S.Kind = SK_QualificationConversionLValue;
2539 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002540 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002541 S.Type = Ty;
2542 Steps.push_back(S);
2543}
2544
2545void InitializationSequence::AddConversionSequenceStep(
2546 const ImplicitConversionSequence &ICS,
2547 QualType T) {
2548 Step S;
2549 S.Kind = SK_ConversionSequence;
2550 S.Type = T;
2551 S.ICS = new ImplicitConversionSequence(ICS);
2552 Steps.push_back(S);
2553}
2554
Douglas Gregor51e77d52009-12-10 17:56:55 +00002555void InitializationSequence::AddListInitializationStep(QualType T) {
2556 Step S;
2557 S.Kind = SK_ListInitialization;
2558 S.Type = T;
2559 Steps.push_back(S);
2560}
2561
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002562void
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002563InitializationSequence
2564::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2565 AccessSpecifier Access,
2566 QualType T,
Sebastian Redled2e5322011-12-22 14:44:04 +00002567 bool HadMultipleCandidates,
2568 bool FromInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002569 Step S;
Sebastian Redled2e5322011-12-22 14:44:04 +00002570 S.Kind = FromInitList ? SK_ListConstructorCall : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002571 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002572 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002573 S.Function.Function = Constructor;
2574 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002575 Steps.push_back(S);
2576}
2577
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002578void InitializationSequence::AddZeroInitializationStep(QualType T) {
2579 Step S;
2580 S.Kind = SK_ZeroInitialization;
2581 S.Type = T;
2582 Steps.push_back(S);
2583}
2584
Douglas Gregore1314a62009-12-18 05:02:21 +00002585void InitializationSequence::AddCAssignmentStep(QualType T) {
2586 Step S;
2587 S.Kind = SK_CAssignment;
2588 S.Type = T;
2589 Steps.push_back(S);
2590}
2591
Eli Friedman78275202009-12-19 08:11:05 +00002592void InitializationSequence::AddStringInitStep(QualType T) {
2593 Step S;
2594 S.Kind = SK_StringInit;
2595 S.Type = T;
2596 Steps.push_back(S);
2597}
2598
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002599void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2600 Step S;
2601 S.Kind = SK_ObjCObjectConversion;
2602 S.Type = T;
2603 Steps.push_back(S);
2604}
2605
Douglas Gregore2f943b2011-02-22 18:29:51 +00002606void InitializationSequence::AddArrayInitStep(QualType T) {
2607 Step S;
2608 S.Kind = SK_ArrayInit;
2609 S.Type = T;
2610 Steps.push_back(S);
2611}
2612
John McCall31168b02011-06-15 23:02:42 +00002613void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2614 bool shouldCopy) {
2615 Step s;
2616 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2617 : SK_PassByIndirectRestore);
2618 s.Type = type;
2619 Steps.push_back(s);
2620}
2621
2622void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2623 Step S;
2624 S.Kind = SK_ProduceObjCObject;
2625 S.Type = T;
2626 Steps.push_back(S);
2627}
2628
Sebastian Redlc1839b12012-01-17 22:49:42 +00002629void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2630 Step S;
2631 S.Kind = SK_StdInitializerList;
2632 S.Type = T;
2633 Steps.push_back(S);
2634}
2635
Sebastian Redl29526f02011-11-27 16:50:07 +00002636void InitializationSequence::RewrapReferenceInitList(QualType T,
2637 InitListExpr *Syntactic) {
2638 assert(Syntactic->getNumInits() == 1 &&
2639 "Can only rewrap trivial init lists.");
2640 Step S;
2641 S.Kind = SK_UnwrapInitList;
2642 S.Type = Syntactic->getInit(0)->getType();
2643 Steps.insert(Steps.begin(), S);
2644
2645 S.Kind = SK_RewrapInitList;
2646 S.Type = T;
2647 S.WrappingSyntacticList = Syntactic;
2648 Steps.push_back(S);
2649}
2650
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002651void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002652 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00002653 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002654 this->Failure = Failure;
2655 this->FailedOverloadResult = Result;
2656}
2657
2658//===----------------------------------------------------------------------===//
2659// Attempt initialization
2660//===----------------------------------------------------------------------===//
2661
John McCall31168b02011-06-15 23:02:42 +00002662static void MaybeProduceObjCObject(Sema &S,
2663 InitializationSequence &Sequence,
2664 const InitializedEntity &Entity) {
2665 if (!S.getLangOptions().ObjCAutoRefCount) return;
2666
2667 /// When initializing a parameter, produce the value if it's marked
2668 /// __attribute__((ns_consumed)).
2669 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2670 if (!Entity.isParameterConsumed())
2671 return;
2672
2673 assert(Entity.getType()->isObjCRetainableType() &&
2674 "consuming an object of unretainable type?");
2675 Sequence.AddProduceObjCObjectStep(Entity.getType());
2676
2677 /// When initializing a return value, if the return type is a
2678 /// retainable type, then returns need to immediately retain the
2679 /// object. If an autorelease is required, it will be done at the
2680 /// last instant.
2681 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2682 if (!Entity.getType()->isObjCRetainableType())
2683 return;
2684
2685 Sequence.AddProduceObjCObjectStep(Entity.getType());
2686 }
2687}
2688
Sebastian Redled2e5322011-12-22 14:44:04 +00002689/// \brief When initializing from init list via constructor, deal with the
2690/// empty init list and std::initializer_list special cases.
2691///
2692/// \return True if this was a special case, false otherwise.
2693static bool TryListConstructionSpecialCases(Sema &S,
2694 Expr **Args, unsigned NumArgs,
2695 CXXRecordDecl *DestRecordDecl,
2696 QualType DestType,
2697 InitializationSequence &Sequence) {
Sebastian Redlc1839b12012-01-17 22:49:42 +00002698 // C++11 [dcl.init.list]p3:
Sebastian Redled2e5322011-12-22 14:44:04 +00002699 // List-initialization of an object of type T is defined as follows:
2700 // - If the initializer list has no elements and T is a class type with
2701 // a default constructor, the object is value-initialized.
2702 if (NumArgs == 0) {
2703 if (CXXConstructorDecl *DefaultConstructor =
2704 S.LookupDefaultConstructor(DestRecordDecl)) {
2705 if (DefaultConstructor->isDeleted() ||
2706 S.isFunctionConsideredUnavailable(DefaultConstructor)) {
2707 // Fake an overload resolution failure.
2708 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2709 DeclAccessPair FoundDecl = DeclAccessPair::make(DefaultConstructor,
2710 DefaultConstructor->getAccess());
2711 if (FunctionTemplateDecl *ConstructorTmpl =
2712 dyn_cast<FunctionTemplateDecl>(DefaultConstructor))
2713 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2714 /*ExplicitArgs*/ 0,
2715 Args, NumArgs, CandidateSet,
2716 /*SuppressUserConversions*/ false);
2717 else
2718 S.AddOverloadCandidate(DefaultConstructor, FoundDecl,
2719 Args, NumArgs, CandidateSet,
2720 /*SuppressUserConversions*/ false);
2721 Sequence.SetOverloadFailure(
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002722 InitializationSequence::FK_ListConstructorOverloadFailed,
2723 OR_Deleted);
Sebastian Redled2e5322011-12-22 14:44:04 +00002724 } else
2725 Sequence.AddConstructorInitializationStep(DefaultConstructor,
2726 DefaultConstructor->getAccess(),
2727 DestType,
2728 /*MultipleCandidates=*/false,
2729 /*FromInitList=*/true);
2730 return true;
2731 }
2732 }
2733
2734 // - Otherwise, if T is a specialization of std::initializer_list, [...]
Sebastian Redlc1839b12012-01-17 22:49:42 +00002735 QualType E;
2736 if (S.isStdInitializerList(DestType, &E)) {
2737 // Check that each individual element can be copy-constructed. But since we
2738 // have no place to store further information, we'll recalculate everything
2739 // later.
2740 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2741 S.Context.getConstantArrayType(E,
2742 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),NumArgs),
2743 ArrayType::Normal, 0));
2744 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2745 0, HiddenArray);
2746 for (unsigned i = 0; i < NumArgs; ++i) {
2747 Element.setElementIndex(i);
2748 if (!S.CanPerformCopyInitialization(Element, Args[i])) {
2749 Sequence.SetFailed(
2750 InitializationSequence::FK_InitListElementCopyFailure);
2751 return true;
2752 }
2753 }
2754 Sequence.AddStdInitializerListConstructionStep(DestType);
2755 return true;
2756 }
Sebastian Redled2e5322011-12-22 14:44:04 +00002757
2758 // Not a special case.
2759 return false;
2760}
2761
2762/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2763/// enumerates the constructors of the initialized entity and performs overload
2764/// resolution to select the best.
2765/// If FromInitList is true, this is list-initialization of a non-aggregate
2766/// class type.
2767static void TryConstructorInitialization(Sema &S,
2768 const InitializedEntity &Entity,
2769 const InitializationKind &Kind,
2770 Expr **Args, unsigned NumArgs,
2771 QualType DestType,
2772 InitializationSequence &Sequence,
2773 bool FromInitList = false) {
2774 // Check constructor arguments for self reference.
2775 if (DeclaratorDecl *DD = Entity.getDecl())
2776 // Parameters arguments are occassionially constructed with itself,
2777 // for instance, in recursive functions. Skip them.
2778 if (!isa<ParmVarDecl>(DD))
2779 for (unsigned i = 0; i < NumArgs; ++i)
2780 S.CheckSelfReference(DD, Args[i]);
2781
2782 // Build the candidate set directly in the initialization sequence
2783 // structure, so that it will persist if we fail.
2784 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2785 CandidateSet.clear();
2786
2787 // Determine whether we are allowed to call explicit constructors or
2788 // explicit conversion operators.
2789 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2790 Kind.getKind() == InitializationKind::IK_Value ||
2791 Kind.getKind() == InitializationKind::IK_Default);
2792
2793 // The type we're constructing needs to be complete.
2794 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
2795 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
2796 }
2797
2798 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2799 assert(DestRecordType && "Constructor initialization requires record type");
2800 CXXRecordDecl *DestRecordDecl
2801 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2802
2803 if (FromInitList &&
2804 TryListConstructionSpecialCases(S, Args, NumArgs, DestRecordDecl,
2805 DestType, Sequence))
2806 return;
2807
2808 // - Otherwise, if T is a class type, constructors are considered. The
2809 // applicable constructors are enumerated, and the best one is chosen
2810 // through overload resolution.
2811 DeclContext::lookup_iterator Con, ConEnd;
2812 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
2813 Con != ConEnd; ++Con) {
2814 NamedDecl *D = *Con;
2815 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2816 bool SuppressUserConversions = false;
2817
2818 // Find the constructor (which may be a template).
2819 CXXConstructorDecl *Constructor = 0;
2820 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2821 if (ConstructorTmpl)
2822 Constructor = cast<CXXConstructorDecl>(
2823 ConstructorTmpl->getTemplatedDecl());
2824 else {
2825 Constructor = cast<CXXConstructorDecl>(D);
2826
2827 // If we're performing copy initialization using a copy constructor, we
2828 // suppress user-defined conversions on the arguments.
2829 // FIXME: Move constructors?
2830 if (Kind.getKind() == InitializationKind::IK_Copy &&
2831 Constructor->isCopyConstructor())
2832 SuppressUserConversions = true;
2833 }
2834
2835 if (!Constructor->isInvalidDecl() &&
2836 (AllowExplicit || !Constructor->isExplicit())) {
2837 if (ConstructorTmpl)
2838 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2839 /*ExplicitArgs*/ 0,
2840 Args, NumArgs, CandidateSet,
2841 SuppressUserConversions);
2842 else
2843 S.AddOverloadCandidate(Constructor, FoundDecl,
2844 Args, NumArgs, CandidateSet,
2845 SuppressUserConversions);
2846 }
2847 }
2848
2849 SourceLocation DeclLoc = Kind.getLocation();
2850
2851 // Perform overload resolution. If it fails, return the failed result.
2852 OverloadCandidateSet::iterator Best;
2853 if (OverloadingResult Result
2854 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002855 Sequence.SetOverloadFailure(FromInitList ?
2856 InitializationSequence::FK_ListConstructorOverloadFailed :
2857 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00002858 Result);
2859 return;
2860 }
2861
2862 // C++0x [dcl.init]p6:
2863 // If a program calls for the default initialization of an object
2864 // of a const-qualified type T, T shall be a class type with a
2865 // user-provided default constructor.
2866 if (Kind.getKind() == InitializationKind::IK_Default &&
2867 Entity.getType().isConstQualified() &&
2868 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2869 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2870 return;
2871 }
2872
2873 // Add the constructor initialization step. Any cv-qualification conversion is
2874 // subsumed by the initialization.
2875 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2876 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
2877 Sequence.AddConstructorInitializationStep(CtorDecl,
2878 Best->FoundDecl.getAccess(),
2879 DestType, HadMultipleCandidates,
2880 FromInitList);
2881}
2882
Sebastian Redl29526f02011-11-27 16:50:07 +00002883static bool
2884ResolveOverloadedFunctionForReferenceBinding(Sema &S,
2885 Expr *Initializer,
2886 QualType &SourceType,
2887 QualType &UnqualifiedSourceType,
2888 QualType UnqualifiedTargetType,
2889 InitializationSequence &Sequence) {
2890 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
2891 S.Context.OverloadTy) {
2892 DeclAccessPair Found;
2893 bool HadMultipleCandidates = false;
2894 if (FunctionDecl *Fn
2895 = S.ResolveAddressOfOverloadedFunction(Initializer,
2896 UnqualifiedTargetType,
2897 false, Found,
2898 &HadMultipleCandidates)) {
2899 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
2900 HadMultipleCandidates);
2901 SourceType = Fn->getType();
2902 UnqualifiedSourceType = SourceType.getUnqualifiedType();
2903 } else if (!UnqualifiedTargetType->isRecordType()) {
2904 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2905 return true;
2906 }
2907 }
2908 return false;
2909}
2910
2911static void TryReferenceInitializationCore(Sema &S,
2912 const InitializedEntity &Entity,
2913 const InitializationKind &Kind,
2914 Expr *Initializer,
2915 QualType cv1T1, QualType T1,
2916 Qualifiers T1Quals,
2917 QualType cv2T2, QualType T2,
2918 Qualifiers T2Quals,
2919 InitializationSequence &Sequence);
2920
2921static void TryListInitialization(Sema &S,
2922 const InitializedEntity &Entity,
2923 const InitializationKind &Kind,
2924 InitListExpr *InitList,
2925 InitializationSequence &Sequence);
2926
2927/// \brief Attempt list initialization of a reference.
2928static void TryReferenceListInitialization(Sema &S,
2929 const InitializedEntity &Entity,
2930 const InitializationKind &Kind,
2931 InitListExpr *InitList,
2932 InitializationSequence &Sequence)
2933{
2934 // First, catch C++03 where this isn't possible.
2935 if (!S.getLangOptions().CPlusPlus0x) {
2936 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2937 return;
2938 }
2939
2940 QualType DestType = Entity.getType();
2941 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2942 Qualifiers T1Quals;
2943 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
2944
2945 // Reference initialization via an initializer list works thus:
2946 // If the initializer list consists of a single element that is
2947 // reference-related to the referenced type, bind directly to that element
2948 // (possibly creating temporaries).
2949 // Otherwise, initialize a temporary with the initializer list and
2950 // bind to that.
2951 if (InitList->getNumInits() == 1) {
2952 Expr *Initializer = InitList->getInit(0);
2953 QualType cv2T2 = Initializer->getType();
2954 Qualifiers T2Quals;
2955 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
2956
2957 // If this fails, creating a temporary wouldn't work either.
2958 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
2959 T1, Sequence))
2960 return;
2961
2962 SourceLocation DeclLoc = Initializer->getLocStart();
2963 bool dummy1, dummy2, dummy3;
2964 Sema::ReferenceCompareResult RefRelationship
2965 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
2966 dummy2, dummy3);
2967 if (RefRelationship >= Sema::Ref_Related) {
2968 // Try to bind the reference here.
2969 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
2970 T1Quals, cv2T2, T2, T2Quals, Sequence);
2971 if (Sequence)
2972 Sequence.RewrapReferenceInitList(cv1T1, InitList);
2973 return;
2974 }
2975 }
2976
2977 // Not reference-related. Create a temporary and bind to that.
2978 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2979
2980 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
2981 if (Sequence) {
2982 if (DestType->isRValueReferenceType() ||
2983 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
2984 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2985 else
2986 Sequence.SetFailed(
2987 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2988 }
2989}
2990
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002991/// \brief Attempt list initialization (C++0x [dcl.init.list])
2992static void TryListInitialization(Sema &S,
2993 const InitializedEntity &Entity,
2994 const InitializationKind &Kind,
2995 InitListExpr *InitList,
2996 InitializationSequence &Sequence) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002997 QualType DestType = Entity.getType();
2998
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002999 // C++ doesn't allow scalar initialization with more than one argument.
3000 // But C99 complex numbers are scalars and it makes sense there.
3001 if (S.getLangOptions().CPlusPlus && DestType->isScalarType() &&
3002 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3003 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3004 return;
3005 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003006 if (DestType->isReferenceType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003007 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003008 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003009 }
3010 if (DestType->isRecordType() && !DestType->isAggregateType()) {
Sebastian Redled2e5322011-12-22 14:44:04 +00003011 if (S.getLangOptions().CPlusPlus0x)
3012 TryConstructorInitialization(S, Entity, Kind, InitList->getInits(),
3013 InitList->getNumInits(), DestType, Sequence,
3014 /*FromInitList=*/true);
3015 else
3016 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003017 return;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003018 }
3019
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003020 InitListChecker CheckInitList(S, Entity, InitList,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00003021 DestType, /*VerifyOnly=*/true,
3022 Kind.getKind() != InitializationKind::IK_Direct ||
3023 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003024 if (CheckInitList.HadError()) {
3025 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3026 return;
3027 }
3028
3029 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003030 Sequence.AddListInitializationStep(DestType);
3031}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003032
3033/// \brief Try a reference initialization that involves calling a conversion
3034/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003035static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3036 const InitializedEntity &Entity,
3037 const InitializationKind &Kind,
3038 Expr *Initializer,
3039 bool AllowRValues,
3040 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003041 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003042 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3043 QualType T1 = cv1T1.getUnqualifiedType();
3044 QualType cv2T2 = Initializer->getType();
3045 QualType T2 = cv2T2.getUnqualifiedType();
3046
3047 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003048 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003049 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003050 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003051 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003052 ObjCConversion,
3053 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003054 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00003055 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003056 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003057 (void)ObjCLifetimeConversion;
3058
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003059 // Build the candidate set directly in the initialization sequence
3060 // structure, so that it will persist if we fail.
3061 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3062 CandidateSet.clear();
3063
3064 // Determine whether we are allowed to call explicit constructors or
3065 // explicit conversion operators.
3066 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003067
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003068 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003069 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3070 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003071 // The type we're converting to is a class type. Enumerate its constructors
3072 // to see if there is a suitable conversion.
3073 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00003074
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003075 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003076 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003077 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003078 NamedDecl *D = *Con;
3079 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3080
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003081 // Find the constructor (which may be a template).
3082 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00003083 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003084 if (ConstructorTmpl)
3085 Constructor = cast<CXXConstructorDecl>(
3086 ConstructorTmpl->getTemplatedDecl());
3087 else
John McCalla0296f72010-03-19 07:35:19 +00003088 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003089
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003090 if (!Constructor->isInvalidDecl() &&
3091 Constructor->isConvertingConstructor(AllowExplicit)) {
3092 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003093 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003094 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003095 &Initializer, 1, CandidateSet,
3096 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003097 else
John McCalla0296f72010-03-19 07:35:19 +00003098 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003099 &Initializer, 1, CandidateSet,
3100 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003101 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003102 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003103 }
John McCall3696dcb2010-08-17 07:23:57 +00003104 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3105 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003106
Douglas Gregor496e8b342010-05-07 19:42:26 +00003107 const RecordType *T2RecordType = 0;
3108 if ((T2RecordType = T2->getAs<RecordType>()) &&
3109 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003110 // The type we're converting from is a class type, enumerate its conversion
3111 // functions.
3112 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3113
John McCallad371252010-01-20 00:46:10 +00003114 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003115 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003116 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
3117 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003118 NamedDecl *D = *I;
3119 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3120 if (isa<UsingShadowDecl>(D))
3121 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003122
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003123 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3124 CXXConversionDecl *Conv;
3125 if (ConvTemplate)
3126 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3127 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003128 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003129
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003130 // If the conversion function doesn't return a reference type,
3131 // it can't be considered for this conversion unless we're allowed to
3132 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003133 // FIXME: Do we need to make sure that we only consider conversion
3134 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003135 // break recursion.
3136 if ((AllowExplicit || !Conv->isExplicit()) &&
3137 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3138 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003139 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003140 ActingDC, Initializer,
Douglas Gregord412fe52011-01-21 00:27:08 +00003141 DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003142 else
John McCalla0296f72010-03-19 07:35:19 +00003143 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregord412fe52011-01-21 00:27:08 +00003144 Initializer, DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003145 }
3146 }
3147 }
John McCall3696dcb2010-08-17 07:23:57 +00003148 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3149 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003150
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003151 SourceLocation DeclLoc = Initializer->getLocStart();
3152
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003153 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003154 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003155 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003156 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003157 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003158
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003159 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003160
Chandler Carruth30141632011-02-25 19:41:05 +00003161 // This is the overload that will actually be used for the initialization, so
3162 // mark it as used.
Eli Friedmanfa0df832012-02-02 03:46:19 +00003163 S.MarkFunctionReferenced(DeclLoc, Function);
Chandler Carruth30141632011-02-25 19:41:05 +00003164
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003165 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003166 if (isa<CXXConversionDecl>(Function))
3167 T2 = Function->getResultType();
3168 else
3169 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003170
3171 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003172 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCalla0296f72010-03-19 07:35:19 +00003173 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003174 T2.getNonLValueExprType(S.Context),
3175 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003176
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003177 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003178 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00003179 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003180 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00003181 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003182 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00003183 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003184
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003185 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003186 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003187 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003188 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003189 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003190 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00003191 NewDerivedToBase, NewObjCConversion,
3192 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00003193 if (NewRefRelationship == Sema::Ref_Incompatible) {
3194 // If the type we've converted to is not reference-related to the
3195 // type we're looking for, then there is another conversion step
3196 // we need to perform to produce a temporary of the right type
3197 // that we'll be binding to.
3198 ImplicitConversionSequence ICS;
3199 ICS.setStandard();
3200 ICS.Standard = Best->FinalConversion;
3201 T2 = ICS.Standard.getToType(2);
3202 Sequence.AddConversionSequenceStep(ICS, T2);
3203 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003204 Sequence.AddDerivedToBaseCastStep(
3205 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003206 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00003207 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003208 else if (NewObjCConversion)
3209 Sequence.AddObjCObjectConversionStep(
3210 S.Context.getQualifiedType(T1,
3211 T2.getNonReferenceType().getQualifiers()));
3212
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003213 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00003214 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003215
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003216 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3217 return OR_Success;
3218}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003219
Richard Smithc620f552011-10-19 16:55:56 +00003220static void CheckCXX98CompatAccessibleCopy(Sema &S,
3221 const InitializedEntity &Entity,
3222 Expr *CurInitExpr);
3223
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003224/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3225static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003226 const InitializedEntity &Entity,
3227 const InitializationKind &Kind,
3228 Expr *Initializer,
3229 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003230 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003231 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003232 Qualifiers T1Quals;
3233 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003234 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003235 Qualifiers T2Quals;
3236 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00003237
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003238 // If the initializer is the address of an overloaded function, try
3239 // to resolve the overloaded function. If all goes well, T2 is the
3240 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00003241 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3242 T1, Sequence))
3243 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00003244
Sebastian Redl29526f02011-11-27 16:50:07 +00003245 // Delegate everything else to a subfunction.
3246 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3247 T1Quals, cv2T2, T2, T2Quals, Sequence);
3248}
3249
3250/// \brief Reference initialization without resolving overloaded functions.
3251static void TryReferenceInitializationCore(Sema &S,
3252 const InitializedEntity &Entity,
3253 const InitializationKind &Kind,
3254 Expr *Initializer,
3255 QualType cv1T1, QualType T1,
3256 Qualifiers T1Quals,
3257 QualType cv2T2, QualType T2,
3258 Qualifiers T2Quals,
3259 InitializationSequence &Sequence) {
3260 QualType DestType = Entity.getType();
3261 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003262 // Compute some basic properties of the types and the initializer.
3263 bool isLValueRef = DestType->isLValueReferenceType();
3264 bool isRValueRef = !isLValueRef;
3265 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003266 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003267 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003268 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003269 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003270 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003271 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00003272
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003273 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003274 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003275 // "cv2 T2" as follows:
3276 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003277 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003278 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00003279 // Note the analogous bullet points for rvlaue refs to functions. Because
3280 // there are no function rvalues in C++, rvalue refs to functions are treated
3281 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003282 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00003283 bool T1Function = T1->isFunctionType();
3284 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003285 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003286 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003287 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003288 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003289 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003290 // reference-compatible with "cv2 T2," or
3291 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003292 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003293 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003294 // can occur. However, we do pay attention to whether it is a bit-field
3295 // to decide whether we're actually binding to a temporary created from
3296 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003297 if (DerivedToBase)
3298 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003299 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00003300 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003301 else if (ObjCConversion)
3302 Sequence.AddObjCObjectConversionStep(
3303 S.Context.getQualifiedType(T1, T2Quals));
3304
Chandler Carruth04bdce62010-01-12 20:32:25 +00003305 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00003306 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003307 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003308 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003309 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003310 return;
3311 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003312
3313 // - has a class type (i.e., T2 is a class type), where T1 is not
3314 // reference-related to T2, and can be implicitly converted to an
3315 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3316 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003317 // applicable conversion functions (13.3.1.6) and choosing the best
3318 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00003319 // If we have an rvalue ref to function type here, the rhs must be
3320 // an rvalue.
3321 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3322 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003323 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003324 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00003325 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003326 Sequence);
3327 if (ConvOvlResult == OR_Success)
3328 return;
John McCall0d1da222010-01-12 00:44:57 +00003329 if (ConvOvlResult != OR_No_Viable_Function) {
3330 Sequence.SetOverloadFailure(
3331 InitializationSequence::FK_ReferenceInitOverloadFailed,
3332 ConvOvlResult);
3333 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003334 }
3335 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003336
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003337 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003338 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00003339 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003340 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00003341 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3342 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3343 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003344 Sequence.SetOverloadFailure(
3345 InitializationSequence::FK_ReferenceInitOverloadFailed,
3346 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003347 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003348 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003349 ? (RefRelationship == Sema::Ref_Related
3350 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3351 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3352 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00003353
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003354 return;
3355 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003356
Douglas Gregor92e460e2011-01-20 16:44:54 +00003357 // - If the initializer expression
3358 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3359 // "cv1 T1" is reference-compatible with "cv2 T2"
3360 // Note: functions are handled below.
3361 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00003362 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003363 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003364 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00003365 (InitCategory.isXValue() ||
3366 (InitCategory.isPRValue() && T2->isRecordType()) ||
3367 (InitCategory.isPRValue() && T2->isArrayType()))) {
3368 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3369 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003370 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3371 // compiler the freedom to perform a copy here or bind to the
3372 // object, while C++0x requires that we bind directly to the
3373 // object. Hence, we always bind to the object without making an
3374 // extra copy. However, in C++03 requires that we check for the
3375 // presence of a suitable copy constructor:
3376 //
3377 // The constructor that would be used to make the copy shall
3378 // be callable whether or not the copy is actually done.
Francois Pichet0706d202011-09-17 17:15:52 +00003379 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003380 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smithc620f552011-10-19 16:55:56 +00003381 else if (S.getLangOptions().CPlusPlus0x)
3382 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003383 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003384
Douglas Gregor92e460e2011-01-20 16:44:54 +00003385 if (DerivedToBase)
3386 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3387 ValueKind);
3388 else if (ObjCConversion)
3389 Sequence.AddObjCObjectConversionStep(
3390 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003391
Douglas Gregor92e460e2011-01-20 16:44:54 +00003392 if (T1Quals != T2Quals)
3393 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003394 Sequence.AddReferenceBindingStep(cv1T1,
Peter Collingbournefcc764d2011-11-13 00:51:30 +00003395 /*bindingTemporary=*/InitCategory.isPRValue());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003396 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00003397 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003398
3399 // - has a class type (i.e., T2 is a class type), where T1 is not
3400 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00003401 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3402 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregor92e460e2011-01-20 16:44:54 +00003403 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003404 if (RefRelationship == Sema::Ref_Incompatible) {
3405 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3406 Kind, Initializer,
3407 /*AllowRValues=*/true,
3408 Sequence);
3409 if (ConvOvlResult)
3410 Sequence.SetOverloadFailure(
3411 InitializationSequence::FK_ReferenceInitOverloadFailed,
3412 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003413
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003414 return;
3415 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003416
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003417 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3418 return;
3419 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003420
3421 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003422 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003423 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003424 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00003425
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003426 // Determine whether we are allowed to call explicit constructors or
3427 // explicit conversion operators.
3428 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00003429
3430 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3431
John McCall31168b02011-06-15 23:02:42 +00003432 ImplicitConversionSequence ICS
3433 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCallec6f4e92010-06-04 02:29:22 +00003434 /*SuppressUserConversions*/ false,
3435 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00003436 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003437 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3438 /*AllowObjCWritebackConversion=*/false);
3439
3440 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003441 // FIXME: Use the conversion function set stored in ICS to turn
3442 // this into an overloading ambiguity diagnostic. However, we need
3443 // to keep that set as an OverloadCandidateSet rather than as some
3444 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00003445 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3446 Sequence.SetOverloadFailure(
3447 InitializationSequence::FK_ReferenceInitOverloadFailed,
3448 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00003449 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3450 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00003451 else
3452 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003453 return;
John McCall31168b02011-06-15 23:02:42 +00003454 } else {
3455 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003456 }
3457
3458 // [...] If T1 is reference-related to T2, cv1 must be the
3459 // same cv-qualification as, or greater cv-qualification
3460 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00003461 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3462 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003463 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00003464 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003465 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3466 return;
3467 }
3468
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003469 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003470 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003471 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003472 InitCategory.isLValue()) {
3473 Sequence.SetFailed(
3474 InitializationSequence::FK_RValueReferenceBindingToLValue);
3475 return;
3476 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003477
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003478 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3479 return;
3480}
3481
3482/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003483/// (C++ [dcl.init.string], C99 6.7.8).
3484static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003485 const InitializedEntity &Entity,
3486 const InitializationKind &Kind,
3487 Expr *Initializer,
3488 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003489 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003490}
3491
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003492/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003493static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003494 const InitializedEntity &Entity,
3495 const InitializationKind &Kind,
3496 InitializationSequence &Sequence) {
3497 // C++ [dcl.init]p5:
3498 //
3499 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00003500 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003501
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003502 // -- if T is an array type, then each element is value-initialized;
3503 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3504 T = AT->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003505
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003506 if (const RecordType *RT = T->getAs<RecordType>()) {
3507 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3508 // -- if T is a class type (clause 9) with a user-declared
3509 // constructor (12.1), then the default constructor for T is
3510 // called (and the initialization is ill-formed if T has no
3511 // accessible default constructor);
3512 //
3513 // FIXME: we really want to refer to a single subobject of the array,
3514 // but Entity doesn't have a way to capture that (yet).
3515 if (ClassDecl->hasUserDeclaredConstructor())
3516 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003517
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003518 // -- if T is a (possibly cv-qualified) non-union class type
3519 // without a user-provided constructor, then the object is
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003520 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003521 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003522 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00003523 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003524 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003525 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003526 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003527 }
3528 }
3529
Douglas Gregor1b303932009-12-22 15:35:07 +00003530 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003531}
3532
Douglas Gregor85dabae2009-12-16 01:38:02 +00003533/// \brief Attempt default initialization (C++ [dcl.init]p6).
3534static void TryDefaultInitialization(Sema &S,
3535 const InitializedEntity &Entity,
3536 const InitializationKind &Kind,
3537 InitializationSequence &Sequence) {
3538 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003539
Douglas Gregor85dabae2009-12-16 01:38:02 +00003540 // C++ [dcl.init]p6:
3541 // To default-initialize an object of type T means:
3542 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00003543 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3544
Douglas Gregor85dabae2009-12-16 01:38:02 +00003545 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3546 // constructor for T is called (and the initialization is ill-formed if
3547 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00003548 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00003549 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3550 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003551 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003552
Douglas Gregor85dabae2009-12-16 01:38:02 +00003553 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003554
Douglas Gregor85dabae2009-12-16 01:38:02 +00003555 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003556 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00003557 // default constructor.
John McCall31168b02011-06-15 23:02:42 +00003558 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003559 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00003560 return;
3561 }
3562
3563 // If the destination type has a lifetime property, zero-initialize it.
3564 if (DestType.getQualifiers().hasObjCLifetime()) {
3565 Sequence.AddZeroInitializationStep(Entity.getType());
3566 return;
3567 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003568}
3569
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003570/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3571/// which enumerates all conversion functions and performs overload resolution
3572/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003573static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003574 const InitializedEntity &Entity,
3575 const InitializationKind &Kind,
3576 Expr *Initializer,
3577 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003578 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003579 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3580 QualType SourceType = Initializer->getType();
3581 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3582 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003583
Douglas Gregor540c3b02009-12-14 17:27:33 +00003584 // Build the candidate set directly in the initialization sequence
3585 // structure, so that it will persist if we fail.
3586 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3587 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003588
Douglas Gregor540c3b02009-12-14 17:27:33 +00003589 // Determine whether we are allowed to call explicit constructors or
3590 // explicit conversion operators.
3591 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003592
Douglas Gregor540c3b02009-12-14 17:27:33 +00003593 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3594 // The type we're converting to is a class type. Enumerate its constructors
3595 // to see if there is a suitable conversion.
3596 CXXRecordDecl *DestRecordDecl
3597 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003598
Douglas Gregord9848152010-04-26 14:36:57 +00003599 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003600 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00003601 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003602 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00003603 Con != ConEnd; ++Con) {
3604 NamedDecl *D = *Con;
3605 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003606
Douglas Gregord9848152010-04-26 14:36:57 +00003607 // Find the constructor (which may be a template).
3608 CXXConstructorDecl *Constructor = 0;
3609 FunctionTemplateDecl *ConstructorTmpl
3610 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003611 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00003612 Constructor = cast<CXXConstructorDecl>(
3613 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00003614 else
Douglas Gregord9848152010-04-26 14:36:57 +00003615 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003616
Douglas Gregord9848152010-04-26 14:36:57 +00003617 if (!Constructor->isInvalidDecl() &&
3618 Constructor->isConvertingConstructor(AllowExplicit)) {
3619 if (ConstructorTmpl)
3620 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3621 /*ExplicitArgs*/ 0,
3622 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003623 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003624 else
3625 S.AddOverloadCandidate(Constructor, FoundDecl,
3626 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003627 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003628 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003629 }
Douglas Gregord9848152010-04-26 14:36:57 +00003630 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003631 }
Eli Friedman78275202009-12-19 08:11:05 +00003632
3633 SourceLocation DeclLoc = Initializer->getLocStart();
3634
Douglas Gregor540c3b02009-12-14 17:27:33 +00003635 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3636 // The type we're converting from is a class type, enumerate its conversion
3637 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00003638
Eli Friedman4afe9a32009-12-20 22:12:03 +00003639 // We can only enumerate the conversion functions for a complete type; if
3640 // the type isn't complete, simply skip this step.
3641 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3642 CXXRecordDecl *SourceRecordDecl
3643 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003644
John McCallad371252010-01-20 00:46:10 +00003645 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00003646 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003647 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003648 E = Conversions->end();
Eli Friedman4afe9a32009-12-20 22:12:03 +00003649 I != E; ++I) {
3650 NamedDecl *D = *I;
3651 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3652 if (isa<UsingShadowDecl>(D))
3653 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003654
Eli Friedman4afe9a32009-12-20 22:12:03 +00003655 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3656 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003657 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003658 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003659 else
John McCallda4458e2010-03-31 01:36:47 +00003660 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003661
Eli Friedman4afe9a32009-12-20 22:12:03 +00003662 if (AllowExplicit || !Conv->isExplicit()) {
3663 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003664 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003665 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003666 CandidateSet);
3667 else
John McCalla0296f72010-03-19 07:35:19 +00003668 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003669 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003670 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003671 }
3672 }
3673 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003674
3675 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003676 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003677 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003678 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003679 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003680 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00003681 Result);
3682 return;
3683 }
John McCall0d1da222010-01-12 00:44:57 +00003684
Douglas Gregor540c3b02009-12-14 17:27:33 +00003685 FunctionDecl *Function = Best->Function;
Eli Friedmanfa0df832012-02-02 03:46:19 +00003686 S.MarkFunctionReferenced(DeclLoc, Function);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003687 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003688
Douglas Gregor540c3b02009-12-14 17:27:33 +00003689 if (isa<CXXConstructorDecl>(Function)) {
3690 // Add the user-defined conversion step. Any cv-qualification conversion is
3691 // subsumed by the initialization.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003692 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3693 HadMultipleCandidates);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003694 return;
3695 }
3696
3697 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003698 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003699 if (ConvType->getAs<RecordType>()) {
3700 // If we're converting to a class type, there may be an copy if
3701 // the resulting temporary object (possible to create an object of
3702 // a base class type). That copy is not a separate conversion, so
3703 // we just make a note of the actual destination type (possibly a
3704 // base class of the type returned by the conversion function) and
3705 // let the user-defined conversion step handle the conversion.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003706 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3707 HadMultipleCandidates);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003708 return;
3709 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003710
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003711 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3712 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003713
Douglas Gregor5ab11652010-04-17 22:01:05 +00003714 // If the conversion following the call to the conversion function
3715 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003716 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3717 Best->FinalConversion.Third) {
3718 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003719 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003720 ICS.Standard = Best->FinalConversion;
3721 Sequence.AddConversionSequenceStep(ICS, DestType);
3722 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003723}
3724
John McCall31168b02011-06-15 23:02:42 +00003725/// The non-zero enum values here are indexes into diagnostic alternatives.
3726enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3727
3728/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00003729static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3730 bool isAddressOf) {
John McCall31168b02011-06-15 23:02:42 +00003731 // Skip parens.
3732 e = e->IgnoreParens();
3733
3734 // Skip address-of nodes.
3735 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3736 if (op->getOpcode() == UO_AddrOf)
John McCall63f84442011-06-27 23:59:58 +00003737 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCall31168b02011-06-15 23:02:42 +00003738
3739 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00003740 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3741 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00003742 case CK_Dependent:
3743 case CK_BitCast:
3744 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00003745 case CK_NoOp:
John McCall63f84442011-06-27 23:59:58 +00003746 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003747
3748 case CK_ArrayToPointerDecay:
3749 return IIK_nonscalar;
3750
3751 case CK_NullToPointer:
3752 return IIK_okay;
3753
3754 default:
3755 break;
3756 }
3757
3758 // If we have a declaration reference, it had better be a local variable.
John McCall63f84442011-06-27 23:59:58 +00003759 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3760 if (!isAddressOf) return IIK_nonlocal;
3761
3762 VarDecl *var;
3763 if (isa<DeclRefExpr>(e)) {
3764 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3765 if (!var) return IIK_nonlocal;
3766 } else {
3767 var = cast<BlockDeclRefExpr>(e)->getDecl();
3768 }
3769
3770 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00003771
3772 // If we have a conditional operator, check both sides.
3773 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCall63f84442011-06-27 23:59:58 +00003774 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCall31168b02011-06-15 23:02:42 +00003775 return iik;
3776
John McCall63f84442011-06-27 23:59:58 +00003777 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003778
3779 // These are never scalar.
3780 } else if (isa<ArraySubscriptExpr>(e)) {
3781 return IIK_nonscalar;
3782
3783 // Otherwise, it needs to be a null pointer constant.
3784 } else {
3785 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3786 ? IIK_okay : IIK_nonlocal);
3787 }
3788
3789 return IIK_nonlocal;
3790}
3791
3792/// Check whether the given expression is a valid operand for an
3793/// indirect copy/restore.
3794static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3795 assert(src->isRValue());
3796
John McCall63f84442011-06-27 23:59:58 +00003797 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCall31168b02011-06-15 23:02:42 +00003798 if (iik == IIK_okay) return;
3799
3800 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3801 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3802 << src->getSourceRange();
3803}
3804
Douglas Gregore2f943b2011-02-22 18:29:51 +00003805/// \brief Determine whether we have compatible array types for the
3806/// purposes of GNU by-copy array initialization.
3807static bool hasCompatibleArrayTypes(ASTContext &Context,
3808 const ArrayType *Dest,
3809 const ArrayType *Source) {
3810 // If the source and destination array types are equivalent, we're
3811 // done.
3812 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3813 return true;
3814
3815 // Make sure that the element types are the same.
3816 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3817 return false;
3818
3819 // The only mismatch we allow is when the destination is an
3820 // incomplete array type and the source is a constant array type.
3821 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3822}
3823
John McCall31168b02011-06-15 23:02:42 +00003824static bool tryObjCWritebackConversion(Sema &S,
3825 InitializationSequence &Sequence,
3826 const InitializedEntity &Entity,
3827 Expr *Initializer) {
3828 bool ArrayDecay = false;
3829 QualType ArgType = Initializer->getType();
3830 QualType ArgPointee;
3831 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3832 ArrayDecay = true;
3833 ArgPointee = ArgArrayType->getElementType();
3834 ArgType = S.Context.getPointerType(ArgPointee);
3835 }
3836
3837 // Handle write-back conversion.
3838 QualType ConvertedArgType;
3839 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3840 ConvertedArgType))
3841 return false;
3842
3843 // We should copy unless we're passing to an argument explicitly
3844 // marked 'out'.
3845 bool ShouldCopy = true;
3846 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3847 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3848
3849 // Do we need an lvalue conversion?
3850 if (ArrayDecay || Initializer->isGLValue()) {
3851 ImplicitConversionSequence ICS;
3852 ICS.setStandard();
3853 ICS.Standard.setAsIdentityConversion();
3854
3855 QualType ResultType;
3856 if (ArrayDecay) {
3857 ICS.Standard.First = ICK_Array_To_Pointer;
3858 ResultType = S.Context.getPointerType(ArgPointee);
3859 } else {
3860 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3861 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3862 }
3863
3864 Sequence.AddConversionSequenceStep(ICS, ResultType);
3865 }
3866
3867 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3868 return true;
3869}
3870
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003871InitializationSequence::InitializationSequence(Sema &S,
3872 const InitializedEntity &Entity,
3873 const InitializationKind &Kind,
3874 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003875 unsigned NumArgs)
3876 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003877 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003878
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003879 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003880 // The semantics of initializers are as follows. The destination type is
3881 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003882 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003883 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003884 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003885 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003886
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003887 if (DestType->isDependentType() ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003888 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3889 SequenceKind = DependentSequence;
3890 return;
3891 }
3892
Sebastian Redld201edf2011-06-05 13:59:11 +00003893 // Almost everything is a normal sequence.
3894 setSequenceKind(NormalSequence);
3895
John McCalled75c092010-12-07 22:54:16 +00003896 for (unsigned I = 0; I != NumArgs; ++I)
John McCalld5c98ae2011-11-15 01:35:18 +00003897 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall4124c492011-10-17 18:40:02 +00003898 // FIXME: should we be doing this here?
John McCalld5c98ae2011-11-15 01:35:18 +00003899 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
3900 if (result.isInvalid()) {
3901 SetFailed(FK_PlaceholderType);
3902 return;
John McCall4124c492011-10-17 18:40:02 +00003903 }
John McCalld5c98ae2011-11-15 01:35:18 +00003904 Args[I] = result.take();
John Wiegley01296292011-04-08 18:41:53 +00003905 }
John McCalled75c092010-12-07 22:54:16 +00003906
John McCall4124c492011-10-17 18:40:02 +00003907
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003908 QualType SourceType;
3909 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003910 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003911 Initializer = Args[0];
3912 if (!isa<InitListExpr>(Initializer))
3913 SourceType = Initializer->getType();
3914 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003915
3916 // - If the initializer is a braced-init-list, the object is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003917 // list-initialized (8.5.4).
3918 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003919 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00003920 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003921 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003922
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003923 // - If the destination type is a reference type, see 8.5.3.
3924 if (DestType->isReferenceType()) {
3925 // C++0x [dcl.init.ref]p1:
3926 // A variable declared to be a T& or T&&, that is, "reference to type T"
3927 // (8.3.2), shall be initialized by an object, or function, of type T or
3928 // by an object that can be converted into a T.
3929 // (Therefore, multiple arguments are not permitted.)
3930 if (NumArgs != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003931 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003932 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003933 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003934 return;
3935 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003936
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003937 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003938 if (Kind.getKind() == InitializationKind::IK_Value ||
3939 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003940 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003941 return;
3942 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003943
Douglas Gregor85dabae2009-12-16 01:38:02 +00003944 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00003945 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003946 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003947 return;
3948 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003949
John McCall66884dd2011-02-21 07:22:22 +00003950 // - If the destination type is an array of characters, an array of
3951 // char16_t, an array of char32_t, or an array of wchar_t, and the
3952 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003953 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003954 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00003955 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00003956 if (Initializer && isa<VariableArrayType>(DestAT)) {
3957 SetFailed(FK_VariableLengthArrayHasInitializer);
3958 return;
3959 }
3960
Douglas Gregore2f943b2011-02-22 18:29:51 +00003961 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003962 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCall66884dd2011-02-21 07:22:22 +00003963 return;
3964 }
3965
Douglas Gregore2f943b2011-02-22 18:29:51 +00003966 // Note: as an GNU C extension, we allow initialization of an
3967 // array from a compound literal that creates an array of the same
3968 // type, so long as the initializer has no side effects.
3969 if (!S.getLangOptions().CPlusPlus && Initializer &&
3970 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3971 Initializer->getType()->isArrayType()) {
3972 const ArrayType *SourceAT
3973 = Context.getAsArrayType(Initializer->getType());
3974 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003975 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003976 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003977 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003978 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003979 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003980 }
3981 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003982 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003983 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003984 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003985
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003986 return;
3987 }
Eli Friedman78275202009-12-19 08:11:05 +00003988
John McCall31168b02011-06-15 23:02:42 +00003989 // Determine whether we should consider writeback conversions for
3990 // Objective-C ARC.
3991 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
3992 Entity.getKind() == InitializedEntity::EK_Parameter;
3993
3994 // We're at the end of the line for C: it's either a write-back conversion
3995 // or it's a C assignment. There's no need to check anything else.
Eli Friedman78275202009-12-19 08:11:05 +00003996 if (!S.getLangOptions().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00003997 // If allowed, check whether this is an Objective-C writeback conversion.
3998 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003999 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00004000 return;
4001 }
4002
4003 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004004 AddCAssignmentStep(DestType);
4005 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00004006 return;
4007 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004008
John McCall31168b02011-06-15 23:02:42 +00004009 assert(S.getLangOptions().CPlusPlus);
4010
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004011 // - If the destination type is a (possibly cv-qualified) class type:
4012 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004013 // - If the initialization is direct-initialization, or if it is
4014 // copy-initialization where the cv-unqualified version of the
4015 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004016 // class of the destination, constructors are considered. [...]
4017 if (Kind.getKind() == InitializationKind::IK_Direct ||
4018 (Kind.getKind() == InitializationKind::IK_Copy &&
4019 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4020 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004021 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004022 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004023 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004024 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004025 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004026 // used) to a derived class thereof are enumerated as described in
4027 // 13.3.1.4, and the best one is chosen through overload resolution
4028 // (13.3).
4029 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004030 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004031 return;
4032 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004033
Douglas Gregor85dabae2009-12-16 01:38:02 +00004034 if (NumArgs > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004035 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004036 return;
4037 }
4038 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004039
4040 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004041 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004042 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004043 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4044 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004045 return;
4046 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004047
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004048 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00004049 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004050 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004051 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004052 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00004053
4054 ImplicitConversionSequence ICS
4055 = S.TryImplicitConversion(Initializer, Entity.getType(),
4056 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00004057 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00004058 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00004059 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4060 allowObjCWritebackConversion);
4061
4062 if (ICS.isStandard() &&
4063 ICS.Standard.Second == ICK_Writeback_Conversion) {
4064 // Objective-C ARC writeback conversion.
4065
4066 // We should copy unless we're passing to an argument explicitly
4067 // marked 'out'.
4068 bool ShouldCopy = true;
4069 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4070 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4071
4072 // If there was an lvalue adjustment, add it as a separate conversion.
4073 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4074 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4075 ImplicitConversionSequence LvalueICS;
4076 LvalueICS.setStandard();
4077 LvalueICS.Standard.setAsIdentityConversion();
4078 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4079 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004080 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00004081 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004082
4083 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00004084 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004085 DeclAccessPair dap;
4086 if (Initializer->getType() == Context.OverloadTy &&
4087 !S.ResolveAddressOfOverloadedFunction(Initializer
4088 , DestType, false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004089 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004090 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004091 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00004092 } else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004093 AddConversionSequenceStep(ICS, Entity.getType());
John McCallfa272342011-06-16 23:24:51 +00004094
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004095 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004096 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004097}
4098
4099InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004100 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004101 StepEnd = Steps.end();
4102 Step != StepEnd; ++Step)
4103 Step->Destroy();
4104}
4105
4106//===----------------------------------------------------------------------===//
4107// Perform initialization
4108//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004109static Sema::AssignmentAction
Douglas Gregore1314a62009-12-18 05:02:21 +00004110getAssignmentAction(const InitializedEntity &Entity) {
4111 switch(Entity.getKind()) {
4112 case InitializedEntity::EK_Variable:
4113 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004114 case InitializedEntity::EK_Exception:
4115 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004116 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00004117 return Sema::AA_Initializing;
4118
4119 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004120 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00004121 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4122 return Sema::AA_Sending;
4123
Douglas Gregore1314a62009-12-18 05:02:21 +00004124 return Sema::AA_Passing;
4125
4126 case InitializedEntity::EK_Result:
4127 return Sema::AA_Returning;
4128
Douglas Gregore1314a62009-12-18 05:02:21 +00004129 case InitializedEntity::EK_Temporary:
4130 // FIXME: Can we tell apart casting vs. converting?
4131 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004132
Douglas Gregore1314a62009-12-18 05:02:21 +00004133 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004134 case InitializedEntity::EK_ArrayElement:
4135 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004136 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004137 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00004138 return Sema::AA_Initializing;
4139 }
4140
David Blaikie8a40f702012-01-17 06:56:22 +00004141 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00004142}
4143
Douglas Gregor95562572010-04-24 23:45:46 +00004144/// \brief Whether we should binding a created object as a temporary when
4145/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004146static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004147 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00004148 case InitializedEntity::EK_ArrayElement:
4149 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004150 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004151 case InitializedEntity::EK_New:
4152 case InitializedEntity::EK_Variable:
4153 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004154 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004155 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004156 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00004157 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004158 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00004159 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004160
Douglas Gregore1314a62009-12-18 05:02:21 +00004161 case InitializedEntity::EK_Parameter:
4162 case InitializedEntity::EK_Temporary:
4163 return true;
4164 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004165
Douglas Gregore1314a62009-12-18 05:02:21 +00004166 llvm_unreachable("missed an InitializedEntity kind?");
4167}
4168
Douglas Gregor95562572010-04-24 23:45:46 +00004169/// \brief Whether the given entity, when initialized with an object
4170/// created for that initialization, requires destruction.
4171static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4172 switch (Entity.getKind()) {
4173 case InitializedEntity::EK_Member:
4174 case InitializedEntity::EK_Result:
4175 case InitializedEntity::EK_New:
4176 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004177 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00004178 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004179 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004180 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00004181 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004182
Douglas Gregor95562572010-04-24 23:45:46 +00004183 case InitializedEntity::EK_Variable:
4184 case InitializedEntity::EK_Parameter:
4185 case InitializedEntity::EK_Temporary:
4186 case InitializedEntity::EK_ArrayElement:
4187 case InitializedEntity::EK_Exception:
4188 return true;
4189 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004190
4191 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00004192}
4193
Richard Smithc620f552011-10-19 16:55:56 +00004194/// \brief Look for copy and move constructors and constructor templates, for
4195/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4196static void LookupCopyAndMoveConstructors(Sema &S,
4197 OverloadCandidateSet &CandidateSet,
4198 CXXRecordDecl *Class,
4199 Expr *CurInitExpr) {
4200 DeclContext::lookup_iterator Con, ConEnd;
4201 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
4202 Con != ConEnd; ++Con) {
4203 CXXConstructorDecl *Constructor = 0;
4204
4205 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
4206 // Handle copy/moveconstructors, only.
4207 if (!Constructor || Constructor->isInvalidDecl() ||
4208 !Constructor->isCopyOrMoveConstructor() ||
4209 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4210 continue;
4211
4212 DeclAccessPair FoundDecl
4213 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4214 S.AddOverloadCandidate(Constructor, FoundDecl,
4215 &CurInitExpr, 1, CandidateSet);
4216 continue;
4217 }
4218
4219 // Handle constructor templates.
4220 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4221 if (ConstructorTmpl->isInvalidDecl())
4222 continue;
4223
4224 Constructor = cast<CXXConstructorDecl>(
4225 ConstructorTmpl->getTemplatedDecl());
4226 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4227 continue;
4228
4229 // FIXME: Do we need to limit this to copy-constructor-like
4230 // candidates?
4231 DeclAccessPair FoundDecl
4232 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4233 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4234 &CurInitExpr, 1, CandidateSet, true);
4235 }
4236}
4237
4238/// \brief Get the location at which initialization diagnostics should appear.
4239static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4240 Expr *Initializer) {
4241 switch (Entity.getKind()) {
4242 case InitializedEntity::EK_Result:
4243 return Entity.getReturnLoc();
4244
4245 case InitializedEntity::EK_Exception:
4246 return Entity.getThrowLoc();
4247
4248 case InitializedEntity::EK_Variable:
4249 return Entity.getDecl()->getLocation();
4250
4251 case InitializedEntity::EK_ArrayElement:
4252 case InitializedEntity::EK_Member:
4253 case InitializedEntity::EK_Parameter:
4254 case InitializedEntity::EK_Temporary:
4255 case InitializedEntity::EK_New:
4256 case InitializedEntity::EK_Base:
4257 case InitializedEntity::EK_Delegating:
4258 case InitializedEntity::EK_VectorElement:
4259 case InitializedEntity::EK_ComplexElement:
4260 case InitializedEntity::EK_BlockElement:
4261 return Initializer->getLocStart();
4262 }
4263 llvm_unreachable("missed an InitializedEntity kind?");
4264}
4265
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004266/// \brief Make a (potentially elidable) temporary copy of the object
4267/// provided by the given initializer by calling the appropriate copy
4268/// constructor.
4269///
4270/// \param S The Sema object used for type-checking.
4271///
Abramo Bagnara92141d22011-01-27 19:55:10 +00004272/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004273/// the type of the initializer expression or a superclass thereof.
4274///
4275/// \param Enter The entity being initialized.
4276///
4277/// \param CurInit The initializer expression.
4278///
4279/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4280/// is permitted in C++03 (but not C++0x) when binding a reference to
4281/// an rvalue.
4282///
4283/// \returns An expression that copies the initializer expression into
4284/// a temporary object, or an error expression if a copy could not be
4285/// created.
John McCalldadc5752010-08-24 06:29:42 +00004286static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00004287 QualType T,
4288 const InitializedEntity &Entity,
4289 ExprResult CurInit,
4290 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00004291 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00004292 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004293 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004294 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004295 Class = cast<CXXRecordDecl>(Record->getDecl());
4296 if (!Class)
4297 return move(CurInit);
4298
Douglas Gregor5d369002011-01-21 18:05:27 +00004299 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004300 // When certain criteria are met, an implementation is allowed to
4301 // omit the copy/move construction of a class object, even if the
4302 // copy/move constructor and/or destructor for the object have
4303 // side effects. [...]
4304 // - when a temporary class object that has not been bound to a
4305 // reference (12.2) would be copied/moved to a class object
4306 // with the same cv-unqualified type, the copy/move operation
4307 // can be omitted by constructing the temporary object
4308 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004309 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004310 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004311 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004312 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004313 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00004314 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smithc620f552011-10-19 16:55:56 +00004315 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00004316
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004317 // Make sure that the type we are copying is complete.
Douglas Gregord5c231e2010-04-24 21:09:25 +00004318 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4319 return move(CurInit);
4320
Douglas Gregorf282a762011-01-21 19:38:21 +00004321 // Perform overload resolution using the class's copy/move constructors.
Richard Smithc620f552011-10-19 16:55:56 +00004322 // Only consider constructors and constructor templates. Per
4323 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4324 // is direct-initialization.
John McCallbc077cf2010-02-08 23:07:23 +00004325 OverloadCandidateSet CandidateSet(Loc);
Richard Smithc620f552011-10-19 16:55:56 +00004326 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004327
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004328 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4329
Douglas Gregore1314a62009-12-18 05:02:21 +00004330 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00004331 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004332 case OR_Success:
4333 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004334
Douglas Gregore1314a62009-12-18 05:02:21 +00004335 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004336 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4337 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4338 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004339 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004340 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004341 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004342 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00004343 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004344 return move(CurInit);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004345
Douglas Gregore1314a62009-12-18 05:02:21 +00004346 case OR_Ambiguous:
4347 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004348 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004349 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004350 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00004351 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004352
Douglas Gregore1314a62009-12-18 05:02:21 +00004353 case OR_Deleted:
4354 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004355 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004356 << CurInitExpr->getSourceRange();
4357 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004358 << 1 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00004359 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004360 }
4361
Douglas Gregor5ab11652010-04-17 22:01:05 +00004362 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00004363 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004364 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004365
Anders Carlssona01874b2010-04-21 18:47:17 +00004366 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004367 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004368
4369 if (IsExtraneousCopy) {
4370 // If this is a totally extraneous copy for C++03 reference
4371 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00004372 // expression. We don't generate an (elided) copy operation here
4373 // because doing so would require us to pass down a flag to avoid
4374 // infinite recursion, where each step adds another extraneous,
4375 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004376
Douglas Gregor30b52772010-04-18 07:57:34 +00004377 // Instantiate the default arguments of any extra parameters in
4378 // the selected copy constructor, as if we were going to create a
4379 // proper call to the copy constructor.
4380 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4381 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4382 if (S.RequireCompleteType(Loc, Parm->getType(),
4383 S.PDiag(diag::err_call_incomplete_argument)))
4384 break;
4385
4386 // Build the default argument expression; we don't actually care
4387 // if this succeeds or not, because this routine will complain
4388 // if there was a problem.
4389 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4390 }
4391
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004392 return S.Owned(CurInitExpr);
4393 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004394
Eli Friedmanfa0df832012-02-02 03:46:19 +00004395 S.MarkFunctionReferenced(Loc, Constructor);
Chandler Carruth30141632011-02-25 19:41:05 +00004396
Douglas Gregor5ab11652010-04-17 22:01:05 +00004397 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004398 // constructor call (we might have derived-to-base conversions, or
4399 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00004400 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00004401 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004402 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004403
Douglas Gregord0ace022010-04-25 00:55:24 +00004404 // Actually perform the constructor call.
4405 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00004406 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004407 HadMultipleCandidates,
John McCallbfd822c2010-08-24 07:32:53 +00004408 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004409 CXXConstructExpr::CK_Complete,
4410 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004411
Douglas Gregord0ace022010-04-25 00:55:24 +00004412 // If we're supposed to bind temporaries, do so.
4413 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4414 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4415 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004416}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004417
Richard Smithc620f552011-10-19 16:55:56 +00004418/// \brief Check whether elidable copy construction for binding a reference to
4419/// a temporary would have succeeded if we were building in C++98 mode, for
4420/// -Wc++98-compat.
4421static void CheckCXX98CompatAccessibleCopy(Sema &S,
4422 const InitializedEntity &Entity,
4423 Expr *CurInitExpr) {
4424 assert(S.getLangOptions().CPlusPlus0x);
4425
4426 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4427 if (!Record)
4428 return;
4429
4430 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4431 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4432 == DiagnosticsEngine::Ignored)
4433 return;
4434
4435 // Find constructors which would have been considered.
4436 OverloadCandidateSet CandidateSet(Loc);
4437 LookupCopyAndMoveConstructors(
4438 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4439
4440 // Perform overload resolution.
4441 OverloadCandidateSet::iterator Best;
4442 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4443
4444 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4445 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4446 << CurInitExpr->getSourceRange();
4447
4448 switch (OR) {
4449 case OR_Success:
4450 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
4451 Best->FoundDecl.getAccess(), Diag);
4452 // FIXME: Check default arguments as far as that's possible.
4453 break;
4454
4455 case OR_No_Viable_Function:
4456 S.Diag(Loc, Diag);
4457 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
4458 break;
4459
4460 case OR_Ambiguous:
4461 S.Diag(Loc, Diag);
4462 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
4463 break;
4464
4465 case OR_Deleted:
4466 S.Diag(Loc, Diag);
4467 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4468 << 1 << Best->Function->isDeleted();
4469 break;
4470 }
4471}
4472
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004473void InitializationSequence::PrintInitLocationNote(Sema &S,
4474 const InitializedEntity &Entity) {
4475 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4476 if (Entity.getDecl()->getLocation().isInvalid())
4477 return;
4478
4479 if (Entity.getDecl()->getDeclName())
4480 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4481 << Entity.getDecl()->getDeclName();
4482 else
4483 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4484 }
4485}
4486
Sebastian Redl112aa822011-07-14 19:07:55 +00004487static bool isReferenceBinding(const InitializationSequence::Step &s) {
4488 return s.Kind == InitializationSequence::SK_BindReference ||
4489 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4490}
4491
Sebastian Redled2e5322011-12-22 14:44:04 +00004492static ExprResult
4493PerformConstructorInitialization(Sema &S,
4494 const InitializedEntity &Entity,
4495 const InitializationKind &Kind,
4496 MultiExprArg Args,
4497 const InitializationSequence::Step& Step,
4498 bool &ConstructorInitRequiresZeroInit) {
4499 unsigned NumArgs = Args.size();
4500 CXXConstructorDecl *Constructor
4501 = cast<CXXConstructorDecl>(Step.Function.Function);
4502 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4503
4504 // Build a call to the selected constructor.
4505 ASTOwningVector<Expr*> ConstructorArgs(S);
4506 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4507 ? Kind.getEqualLoc()
4508 : Kind.getLocation();
4509
4510 if (Kind.getKind() == InitializationKind::IK_Default) {
4511 // Force even a trivial, implicit default constructor to be
4512 // semantically checked. We do this explicitly because we don't build
4513 // the definition for completely trivial constructors.
4514 CXXRecordDecl *ClassDecl = Constructor->getParent();
4515 assert(ClassDecl && "No parent class for constructor.");
4516 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
4517 ClassDecl->hasTrivialDefaultConstructor() &&
4518 !Constructor->isUsed(false))
4519 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4520 }
4521
4522 ExprResult CurInit = S.Owned((Expr *)0);
4523
4524 // Determine the arguments required to actually perform the constructor
4525 // call.
4526 if (S.CompleteConstructorCall(Constructor, move(Args),
4527 Loc, ConstructorArgs))
4528 return ExprError();
4529
4530
4531 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
4532 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4533 (Kind.getKind() == InitializationKind::IK_Direct ||
4534 Kind.getKind() == InitializationKind::IK_Value)) {
4535 // An explicitly-constructed temporary, e.g., X(1, 2).
4536 unsigned NumExprs = ConstructorArgs.size();
4537 Expr **Exprs = (Expr **)ConstructorArgs.take();
Eli Friedmanfa0df832012-02-02 03:46:19 +00004538 S.MarkFunctionReferenced(Loc, Constructor);
Sebastian Redled2e5322011-12-22 14:44:04 +00004539 S.DiagnoseUseOfDecl(Constructor, Loc);
4540
4541 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4542 if (!TSInfo)
4543 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
4544
4545 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4546 Constructor,
4547 TSInfo,
4548 Exprs,
4549 NumExprs,
4550 Kind.getParenRange(),
4551 HadMultipleCandidates,
4552 ConstructorInitRequiresZeroInit));
4553 } else {
4554 CXXConstructExpr::ConstructionKind ConstructKind =
4555 CXXConstructExpr::CK_Complete;
4556
4557 if (Entity.getKind() == InitializedEntity::EK_Base) {
4558 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4559 CXXConstructExpr::CK_VirtualBase :
4560 CXXConstructExpr::CK_NonVirtualBase;
4561 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4562 ConstructKind = CXXConstructExpr::CK_Delegating;
4563 }
4564
4565 // Only get the parenthesis range if it is a direct construction.
4566 SourceRange parenRange =
4567 Kind.getKind() == InitializationKind::IK_Direct ?
4568 Kind.getParenRange() : SourceRange();
4569
4570 // If the entity allows NRVO, mark the construction as elidable
4571 // unconditionally.
4572 if (Entity.allowsNRVO())
4573 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4574 Constructor, /*Elidable=*/true,
4575 move_arg(ConstructorArgs),
4576 HadMultipleCandidates,
4577 ConstructorInitRequiresZeroInit,
4578 ConstructKind,
4579 parenRange);
4580 else
4581 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4582 Constructor,
4583 move_arg(ConstructorArgs),
4584 HadMultipleCandidates,
4585 ConstructorInitRequiresZeroInit,
4586 ConstructKind,
4587 parenRange);
4588 }
4589 if (CurInit.isInvalid())
4590 return ExprError();
4591
4592 // Only check access if all of that succeeded.
4593 S.CheckConstructorAccess(Loc, Constructor, Entity,
4594 Step.Function.FoundDecl.getAccess());
4595 S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc);
4596
4597 if (shouldBindAsTemporary(Entity))
4598 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4599
4600 return move(CurInit);
4601}
4602
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004603ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004604InitializationSequence::Perform(Sema &S,
4605 const InitializedEntity &Entity,
4606 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00004607 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00004608 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004609 if (Failed()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004610 unsigned NumArgs = Args.size();
4611 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00004612 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004613 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004614
Sebastian Redld201edf2011-06-05 13:59:11 +00004615 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00004616 // If the declaration is a non-dependent, incomplete array type
4617 // that has an initializer, then its type will be completed once
4618 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00004619 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00004620 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004621 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004622 if (const IncompleteArrayType *ArrayT
4623 = S.Context.getAsIncompleteArrayType(DeclType)) {
4624 // FIXME: We don't currently have the ability to accurately
4625 // compute the length of an initializer list without
4626 // performing full type-checking of the initializer list
4627 // (since we have to determine where braces are implicitly
4628 // introduced and such). So, we fall back to making the array
4629 // type a dependently-sized array type with no specified
4630 // bound.
4631 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4632 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00004633
Douglas Gregor51e77d52009-12-10 17:56:55 +00004634 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00004635 if (DeclaratorDecl *DD = Entity.getDecl()) {
4636 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4637 TypeLoc TL = TInfo->getTypeLoc();
4638 if (IncompleteArrayTypeLoc *ArrayLoc
4639 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4640 Brackets = ArrayLoc->getBracketsRange();
4641 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00004642 }
4643
4644 *ResultType
4645 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4646 /*NumElts=*/0,
4647 ArrayT->getSizeModifier(),
4648 ArrayT->getIndexTypeCVRQualifiers(),
4649 Brackets);
4650 }
4651
4652 }
4653 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004654 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4655 Kind.isExplicitCast());
4656 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004657 }
4658
Sebastian Redld201edf2011-06-05 13:59:11 +00004659 // No steps means no initialization.
4660 if (Steps.empty())
Douglas Gregor85dabae2009-12-16 01:38:02 +00004661 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004662
Douglas Gregor1b303932009-12-22 15:35:07 +00004663 QualType DestType = Entity.getType().getNonReferenceType();
4664 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00004665 // the same as Entity.getDecl()->getType() in cases involving type merging,
4666 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00004667 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00004668 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00004669 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004670
John McCalldadc5752010-08-24 06:29:42 +00004671 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004672
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004673 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00004674 // grab the only argument out the Args and place it into the "current"
4675 // initializer.
4676 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004677 case SK_ResolveAddressOfOverloadedFunction:
4678 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004679 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004680 case SK_CastDerivedToBaseLValue:
4681 case SK_BindReference:
4682 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004683 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00004684 case SK_UserConversion:
4685 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004686 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004687 case SK_QualificationConversionRValue:
4688 case SK_ConversionSequence:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00004689 case SK_ListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00004690 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00004691 case SK_UnwrapInitList:
4692 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00004693 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00004694 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00004695 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00004696 case SK_ArrayInit:
4697 case SK_PassByIndirectCopyRestore:
4698 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00004699 case SK_ProduceObjCObject:
4700 case SK_StdInitializerList: {
Douglas Gregore1314a62009-12-18 05:02:21 +00004701 assert(Args.size() == 1);
John Wiegley01296292011-04-08 18:41:53 +00004702 CurInit = Args.get()[0];
4703 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004704 break;
John McCall34376a62010-12-04 03:47:34 +00004705 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004706
Douglas Gregore1314a62009-12-18 05:02:21 +00004707 case SK_ConstructorInitialization:
4708 case SK_ZeroInitialization:
4709 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004710 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004711
4712 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004713 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004714 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004715 for (step_iterator Step = step_begin(), StepEnd = step_end();
4716 Step != StepEnd; ++Step) {
4717 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004718 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004719
John Wiegley01296292011-04-08 18:41:53 +00004720 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004721
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004722 switch (Step->Kind) {
4723 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004724 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004725 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00004726 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00004727 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00004728 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00004729 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00004730 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004731 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004732
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004733 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004734 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004735 case SK_CastDerivedToBaseLValue: {
4736 // We have a derived-to-base cast that produces either an rvalue or an
4737 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004738
John McCallcf142162010-08-07 06:22:56 +00004739 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00004740
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004741 // Casts to inaccessible base classes are allowed with C-style casts.
4742 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4743 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00004744 CurInit.get()->getLocStart(),
4745 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00004746 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00004747 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004748
Douglas Gregor88d292c2010-05-13 16:44:06 +00004749 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4750 QualType T = SourceType;
4751 if (const PointerType *Pointer = T->getAs<PointerType>())
4752 T = Pointer->getPointeeType();
4753 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00004754 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00004755 cast<CXXRecordDecl>(RecordTy->getDecl()));
4756 }
4757
John McCall2536c6d2010-08-25 10:28:54 +00004758 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004759 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004760 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004761 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004762 VK_XValue :
4763 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00004764 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4765 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004766 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00004767 CurInit.get(),
4768 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004769 break;
4770 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004771
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004772 case SK_BindReference:
John Wiegley01296292011-04-08 18:41:53 +00004773 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004774 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4775 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00004776 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004777 << BitField->getDeclName()
John Wiegley01296292011-04-08 18:41:53 +00004778 << CurInit.get()->getSourceRange();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004779 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00004780 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004781 }
Anders Carlssona91be642010-01-29 02:47:33 +00004782
John Wiegley01296292011-04-08 18:41:53 +00004783 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00004784 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004785 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4786 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00004787 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004788 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004789 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004790 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004791
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004792 // Reference binding does not have any corresponding ASTs.
4793
4794 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004795 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004796 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004797
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004798 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004799
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004800 case SK_BindReferenceToTemporary:
4801 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004802 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004803 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004804
Douglas Gregorfe314812011-06-21 17:03:29 +00004805 // Materialize the temporary into memory.
Douglas Gregor2fa40a32011-06-22 15:05:02 +00004806 CurInit = new (S.Context) MaterializeTemporaryExpr(
4807 Entity.getType().getNonReferenceType(),
4808 CurInit.get(),
Douglas Gregorfe314812011-06-21 17:03:29 +00004809 Entity.getType()->isLValueReferenceType());
Douglas Gregor58df5092011-06-22 16:12:01 +00004810
4811 // If we're binding to an Objective-C object that has lifetime, we
4812 // need cleanups.
4813 if (S.getLangOptions().ObjCAutoRefCount &&
4814 CurInit.get()->getType()->isObjCLifetimeType())
4815 S.ExprNeedsCleanups = true;
4816
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004817 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004818
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004819 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004820 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004821 /*IsExtraneousCopy=*/true);
4822 break;
4823
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004824 case SK_UserConversion: {
4825 // We have a user-defined conversion that invokes either a constructor
4826 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00004827 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00004828 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00004829 FunctionDecl *Fn = Step->Function.Function;
4830 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004831 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00004832 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00004833 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004834 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004835 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley01296292011-04-08 18:41:53 +00004836 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004837 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00004838
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004839 // Determine the arguments required to actually perform the constructor
4840 // call.
John Wiegley01296292011-04-08 18:41:53 +00004841 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004842 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00004843 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004844 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004845 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004846
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004847 // Build the an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004848 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00004849 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004850 HadMultipleCandidates,
John McCallbfd822c2010-08-24 07:32:53 +00004851 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004852 CXXConstructExpr::CK_Complete,
4853 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004854 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004855 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004856
Anders Carlssona01874b2010-04-21 18:47:17 +00004857 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004858 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004859 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004860
John McCalle3027922010-08-25 11:45:40 +00004861 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00004862 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4863 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4864 S.IsDerivedFrom(SourceType, Class))
4865 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004866
Douglas Gregor95562572010-04-24 23:45:46 +00004867 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004868 } else {
4869 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00004870 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley01296292011-04-08 18:41:53 +00004871 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00004872 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00004873 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004874
4875 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004876 // derived-to-base conversion? I believe the answer is "no", because
4877 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00004878 ExprResult CurInitExprRes =
4879 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4880 FoundFn, Conversion);
4881 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004882 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004883 CurInit = move(CurInitExprRes);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004884
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004885 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004886 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
4887 HadMultipleCandidates);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004888 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00004889 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004890
John McCalle3027922010-08-25 11:45:40 +00004891 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004892
Douglas Gregor95562572010-04-24 23:45:46 +00004893 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004894 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004895
Sebastian Redl112aa822011-07-14 19:07:55 +00004896 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004897 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
4898
4899 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00004900 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00004901 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004902 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00004903 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00004904 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00004905 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00004906 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
John Wiegley01296292011-04-08 18:41:53 +00004907 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00004908 }
4909 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004910
John McCallcf142162010-08-07 06:22:56 +00004911 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00004912 CurInit.get()->getType(),
4913 CastKind, CurInit.get(), 0,
Eli Friedmanf272d402011-09-27 01:11:35 +00004914 CurInit.get()->getValueKind()));
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004915 if (MaybeBindToTemp)
4916 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004917 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004918 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4919 move(CurInit), /*IsExtraneousCopy=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004920 break;
4921 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004922
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004923 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004924 case SK_QualificationConversionXValue:
4925 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004926 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00004927 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004928 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004929 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004930 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004931 VK_XValue :
4932 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00004933 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004934 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004935 }
4936
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004937 case SK_ConversionSequence: {
John McCall31168b02011-06-15 23:02:42 +00004938 Sema::CheckedConversionKind CCK
4939 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4940 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00004941 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00004942 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00004943 ExprResult CurInitExprRes =
4944 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00004945 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00004946 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004947 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004948 CurInit = move(CurInitExprRes);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004949 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004950 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004951
Douglas Gregor51e77d52009-12-10 17:56:55 +00004952 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00004953 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Sebastian Redl29526f02011-11-27 16:50:07 +00004954 // Hack: We must pass *ResultType if available in order to set the type
4955 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
4956 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
4957 // temporary, not a reference, so we should pass Ty.
4958 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
4959 // Since this step is never used for a reference directly, we explicitly
4960 // unwrap references here and rewrap them afterwards.
4961 // We also need to create a InitializeTemporary entity for this.
4962 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
4963 bool IsTemporary = ResultType && (*ResultType)->isReferenceType();
4964 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
4965 InitListChecker PerformInitList(S, IsTemporary ? TempEntity : Entity,
4966 InitList, Ty, /*VerifyOnly=*/false,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00004967 Kind.getKind() != InitializationKind::IK_Direct ||
4968 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004969 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00004970 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004971
Sebastian Redl29526f02011-11-27 16:50:07 +00004972 if (ResultType) {
4973 if ((*ResultType)->isRValueReferenceType())
4974 Ty = S.Context.getRValueReferenceType(Ty);
4975 else if ((*ResultType)->isLValueReferenceType())
4976 Ty = S.Context.getLValueReferenceType(Ty,
4977 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
4978 *ResultType = Ty;
4979 }
4980
4981 InitListExpr *StructuredInitList =
4982 PerformInitList.getFullyStructuredList();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004983 CurInit.release();
Sebastian Redl29526f02011-11-27 16:50:07 +00004984 CurInit = S.Owned(StructuredInitList);
Douglas Gregor51e77d52009-12-10 17:56:55 +00004985 break;
4986 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004987
Sebastian Redled2e5322011-12-22 14:44:04 +00004988 case SK_ListConstructorCall: {
4989 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
4990 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
4991 CurInit = PerformConstructorInitialization(S, Entity, Kind,
4992 move(Arg), *Step,
4993 ConstructorInitRequiresZeroInit);
4994 break;
4995 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00004996
Sebastian Redl29526f02011-11-27 16:50:07 +00004997 case SK_UnwrapInitList:
4998 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
4999 break;
5000
5001 case SK_RewrapInitList: {
5002 Expr *E = CurInit.take();
5003 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5004 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
5005 Syntactic->getLBraceLoc(), &E, 1, Syntactic->getRBraceLoc());
5006 ILE->setSyntacticForm(Syntactic);
5007 ILE->setType(E->getType());
5008 ILE->setValueKind(E->getValueKind());
5009 CurInit = S.Owned(ILE);
5010 break;
5011 }
5012
Sebastian Redled2e5322011-12-22 14:44:04 +00005013 case SK_ConstructorInitialization:
5014 CurInit = PerformConstructorInitialization(S, Entity, Kind, move(Args),
5015 *Step,
5016 ConstructorInitRequiresZeroInit);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005017 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005018
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005019 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005020 step_iterator NextStep = Step;
5021 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005022 if (NextStep != StepEnd &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005023 NextStep->Kind == SK_ConstructorInitialization) {
5024 // The need for zero-initialization is recorded directly into
5025 // the call to the object's constructor within the next step.
5026 ConstructorInitRequiresZeroInit = true;
5027 } else if (Kind.getKind() == InitializationKind::IK_Value &&
5028 S.getLangOptions().CPlusPlus &&
5029 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00005030 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5031 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005032 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00005033 Kind.getRange().getBegin());
5034
5035 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5036 TSInfo->getType().getNonLValueExprType(S.Context),
5037 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005038 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005039 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005040 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005041 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005042 break;
5043 }
Douglas Gregore1314a62009-12-18 05:02:21 +00005044
5045 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00005046 QualType SourceType = CurInit.get()->getType();
5047 ExprResult Result = move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00005048 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00005049 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5050 if (Result.isInvalid())
5051 return ExprError();
5052 CurInit = move(Result);
Douglas Gregor96596c92009-12-22 07:24:36 +00005053
5054 // If this is a call, allow conversion to a transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005055 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregor96596c92009-12-22 07:24:36 +00005056 if (ConvTy != Sema::Compatible &&
5057 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley01296292011-04-08 18:41:53 +00005058 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00005059 == Sema::Compatible)
5060 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00005061 if (CurInitExprRes.isInvalid())
5062 return ExprError();
5063 CurInit = move(CurInitExprRes);
Douglas Gregor96596c92009-12-22 07:24:36 +00005064
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005065 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00005066 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5067 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00005068 CurInit.get(),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005069 getAssignmentAction(Entity),
5070 &Complained)) {
5071 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00005072 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005073 } else if (Complained)
5074 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00005075 break;
5076 }
Eli Friedman78275202009-12-19 08:11:05 +00005077
5078 case SK_StringInit: {
5079 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00005080 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00005081 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00005082 break;
5083 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005084
5085 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00005086 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00005087 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005088 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005089 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005090
5091 case SK_ArrayInit:
5092 // Okay: we checked everything before creating this step. Note that
5093 // this is a GNU extension.
5094 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00005095 << Step->Type << CurInit.get()->getType()
5096 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00005097
5098 // If the destination type is an incomplete array type, update the
5099 // type accordingly.
5100 if (ResultType) {
5101 if (const IncompleteArrayType *IncompleteDest
5102 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5103 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00005104 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00005105 *ResultType = S.Context.getConstantArrayType(
5106 IncompleteDest->getElementType(),
5107 ConstantSource->getSize(),
5108 ArrayType::Normal, 0);
5109 }
5110 }
5111 }
John McCall31168b02011-06-15 23:02:42 +00005112 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005113
John McCall31168b02011-06-15 23:02:42 +00005114 case SK_PassByIndirectCopyRestore:
5115 case SK_PassByIndirectRestore:
5116 checkIndirectCopyRestoreSource(S, CurInit.get());
5117 CurInit = S.Owned(new (S.Context)
5118 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5119 Step->Kind == SK_PassByIndirectCopyRestore));
5120 break;
5121
5122 case SK_ProduceObjCObject:
5123 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall2d637d22011-09-10 06:18:15 +00005124 CK_ARCProduceObject,
John McCall31168b02011-06-15 23:02:42 +00005125 CurInit.take(), 0, VK_RValue));
Douglas Gregore2f943b2011-02-22 18:29:51 +00005126 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00005127
5128 case SK_StdInitializerList: {
5129 QualType Dest = Step->Type;
5130 QualType E;
5131 bool Success = S.isStdInitializerList(Dest, &E);
5132 (void)Success;
5133 assert(Success && "Destination type changed?");
5134 InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
5135 unsigned NumInits = ILE->getNumInits();
5136 SmallVector<Expr*, 16> Converted(NumInits);
5137 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5138 S.Context.getConstantArrayType(E,
5139 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5140 NumInits),
5141 ArrayType::Normal, 0));
5142 InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5143 0, HiddenArray);
5144 for (unsigned i = 0; i < NumInits; ++i) {
5145 Element.setElementIndex(i);
5146 ExprResult Init = S.Owned(ILE->getInit(i));
5147 ExprResult Res = S.PerformCopyInitialization(Element,
5148 Init.get()->getExprLoc(),
5149 Init);
5150 assert(!Res.isInvalid() && "Result changed since try phase.");
5151 Converted[i] = Res.take();
5152 }
5153 InitListExpr *Semantic = new (S.Context)
5154 InitListExpr(S.Context, ILE->getLBraceLoc(),
5155 Converted.data(), NumInits, ILE->getRBraceLoc());
5156 Semantic->setSyntacticForm(ILE);
5157 Semantic->setType(Dest);
5158 CurInit = S.Owned(Semantic);
5159 break;
5160 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005161 }
5162 }
John McCall1f425642010-11-11 03:21:53 +00005163
5164 // Diagnose non-fatal problems with the completed initialization.
5165 if (Entity.getKind() == InitializedEntity::EK_Member &&
5166 cast<FieldDecl>(Entity.getDecl())->isBitField())
5167 S.CheckBitFieldInitialization(Kind.getLocation(),
5168 cast<FieldDecl>(Entity.getDecl()),
5169 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005170
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005171 return move(CurInit);
5172}
5173
5174//===----------------------------------------------------------------------===//
5175// Diagnose initialization failures
5176//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005177bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005178 const InitializedEntity &Entity,
5179 const InitializationKind &Kind,
5180 Expr **Args, unsigned NumArgs) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00005181 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005182 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005183
Douglas Gregor1b303932009-12-22 15:35:07 +00005184 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005185 switch (Failure) {
5186 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005187 // FIXME: Customize for the initialized entity?
5188 if (NumArgs == 0)
5189 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
5190 << DestType.getNonReferenceType();
5191 else // FIXME: diagnostic below could be better!
5192 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
5193 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005194 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005195
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005196 case FK_ArrayNeedsInitList:
5197 case FK_ArrayNeedsInitListOrStringLiteral:
5198 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5199 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5200 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005201
Douglas Gregore2f943b2011-02-22 18:29:51 +00005202 case FK_ArrayTypeMismatch:
5203 case FK_NonConstantArrayInit:
5204 S.Diag(Kind.getLocation(),
5205 (Failure == FK_ArrayTypeMismatch
5206 ? diag::err_array_init_different_type
5207 : diag::err_array_init_non_constant_array))
5208 << DestType.getNonReferenceType()
5209 << Args[0]->getType()
5210 << Args[0]->getSourceRange();
5211 break;
5212
John McCalla59dc2f2012-01-05 00:13:19 +00005213 case FK_VariableLengthArrayHasInitializer:
5214 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5215 << Args[0]->getSourceRange();
5216 break;
5217
John McCall16df1e52010-03-30 21:47:33 +00005218 case FK_AddressOfOverloadFailed: {
5219 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005220 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005221 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00005222 true,
5223 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005224 break;
John McCall16df1e52010-03-30 21:47:33 +00005225 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005226
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005227 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00005228 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005229 switch (FailedOverloadResult) {
5230 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00005231 if (Failure == FK_UserConversionOverloadFailed)
5232 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5233 << Args[0]->getType() << DestType
5234 << Args[0]->getSourceRange();
5235 else
5236 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5237 << DestType << Args[0]->getType()
5238 << Args[0]->getSourceRange();
5239
John McCall5c32be02010-08-24 20:38:10 +00005240 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005241 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005242
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005243 case OR_No_Viable_Function:
5244 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5245 << Args[0]->getType() << DestType.getNonReferenceType()
5246 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00005247 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005248 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005249
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005250 case OR_Deleted: {
5251 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5252 << Args[0]->getType() << DestType.getNonReferenceType()
5253 << Args[0]->getSourceRange();
5254 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00005255 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00005256 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5257 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005258 if (Ovl == OR_Deleted) {
5259 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00005260 << 1 << Best->Function->isDeleted();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005261 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005262 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005263 }
5264 break;
5265 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005266
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005267 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005268 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005269 }
5270 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005271
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005272 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00005273 if (isa<InitListExpr>(Args[0])) {
5274 S.Diag(Kind.getLocation(),
5275 diag::err_lvalue_reference_bind_to_initlist)
5276 << DestType.getNonReferenceType().isVolatileQualified()
5277 << DestType.getNonReferenceType()
5278 << Args[0]->getSourceRange();
5279 break;
5280 }
5281 // Intentional fallthrough
5282
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005283 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005284 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005285 Failure == FK_NonConstLValueReferenceBindingToTemporary
5286 ? diag::err_lvalue_reference_bind_to_temporary
5287 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00005288 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005289 << DestType.getNonReferenceType()
5290 << Args[0]->getType()
5291 << Args[0]->getSourceRange();
5292 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005293
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005294 case FK_RValueReferenceBindingToLValue:
5295 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00005296 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005297 << Args[0]->getSourceRange();
5298 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005299
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005300 case FK_ReferenceInitDropsQualifiers:
5301 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5302 << DestType.getNonReferenceType()
5303 << Args[0]->getType()
5304 << Args[0]->getSourceRange();
5305 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005306
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005307 case FK_ReferenceInitFailed:
5308 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5309 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00005310 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005311 << Args[0]->getType()
5312 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00005313 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5314 Args[0]->getType()->isObjCObjectPointerType())
5315 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005316 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005317
Douglas Gregorb491ed32011-02-19 21:32:49 +00005318 case FK_ConversionFailed: {
5319 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00005320 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00005321 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005322 << DestType
John McCall086a4642010-11-24 05:12:34 +00005323 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00005324 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005325 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00005326 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5327 S.Diag(Kind.getLocation(), PDiag);
Douglas Gregor33823722011-06-11 01:09:30 +00005328 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5329 Args[0]->getType()->isObjCObjectPointerType())
5330 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00005331 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00005332 }
John Wiegley01296292011-04-08 18:41:53 +00005333
5334 case FK_ConversionFromPropertyFailed:
5335 // No-op. This error has already been reported.
5336 break;
5337
Douglas Gregor51e77d52009-12-10 17:56:55 +00005338 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00005339 SourceRange R;
5340
5341 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00005342 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00005343 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005344 else
Douglas Gregor8ec51732010-09-08 21:40:08 +00005345 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00005346
Douglas Gregor8ec51732010-09-08 21:40:08 +00005347 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5348 if (Kind.isCStyleOrFunctionalCast())
5349 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5350 << R;
5351 else
5352 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5353 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00005354 break;
5355 }
5356
5357 case FK_ReferenceBindingToInitList:
5358 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5359 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5360 break;
5361
5362 case FK_InitListBadDestinationType:
5363 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5364 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5365 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005366
Sebastian Redl6901c0d2011-12-22 18:58:38 +00005367 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005368 case FK_ConstructorOverloadFailed: {
5369 SourceRange ArgsRange;
5370 if (NumArgs)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005371 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005372 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005373
Sebastian Redl6901c0d2011-12-22 18:58:38 +00005374 if (Failure == FK_ListConstructorOverloadFailed) {
5375 assert(NumArgs == 1 && "List construction from other than 1 argument.");
5376 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5377 Args = InitList->getInits();
5378 NumArgs = InitList->getNumInits();
5379 }
5380
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005381 // FIXME: Using "DestType" for the entity we're printing is probably
5382 // bad.
5383 switch (FailedOverloadResult) {
5384 case OR_Ambiguous:
5385 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5386 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00005387 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5388 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005389 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005390
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005391 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005392 if (Kind.getKind() == InitializationKind::IK_Default &&
5393 (Entity.getKind() == InitializedEntity::EK_Base ||
5394 Entity.getKind() == InitializedEntity::EK_Member) &&
5395 isa<CXXConstructorDecl>(S.CurContext)) {
5396 // This is implicit default initialization of a member or
5397 // base within a constructor. If no viable function was
5398 // found, notify the user that she needs to explicitly
5399 // initialize this base/member.
5400 CXXConstructorDecl *Constructor
5401 = cast<CXXConstructorDecl>(S.CurContext);
5402 if (Entity.getKind() == InitializedEntity::EK_Base) {
5403 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5404 << Constructor->isImplicit()
5405 << S.Context.getTypeDeclType(Constructor->getParent())
5406 << /*base=*/0
5407 << Entity.getType();
5408
5409 RecordDecl *BaseDecl
5410 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5411 ->getDecl();
5412 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5413 << S.Context.getTagDeclType(BaseDecl);
5414 } else {
5415 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5416 << Constructor->isImplicit()
5417 << S.Context.getTypeDeclType(Constructor->getParent())
5418 << /*member=*/1
5419 << Entity.getName();
5420 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5421
5422 if (const RecordType *Record
5423 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005424 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005425 diag::note_previous_decl)
5426 << S.Context.getTagDeclType(Record->getDecl());
5427 }
5428 break;
5429 }
5430
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005431 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5432 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00005433 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005434 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005435
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005436 case OR_Deleted: {
5437 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5438 << true << DestType << ArgsRange;
5439 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00005440 OverloadingResult Ovl
5441 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005442 if (Ovl == OR_Deleted) {
5443 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00005444 << 1 << Best->Function->isDeleted();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005445 } else {
5446 llvm_unreachable("Inconsistent overload resolution?");
5447 }
5448 break;
5449 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005450
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005451 case OR_Success:
5452 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005453 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005454 }
David Blaikie60deeee2012-01-17 08:24:58 +00005455 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005456
Douglas Gregor85dabae2009-12-16 01:38:02 +00005457 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005458 if (Entity.getKind() == InitializedEntity::EK_Member &&
5459 isa<CXXConstructorDecl>(S.CurContext)) {
5460 // This is implicit default-initialization of a const member in
5461 // a constructor. Complain that it needs to be explicitly
5462 // initialized.
5463 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5464 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5465 << Constructor->isImplicit()
5466 << S.Context.getTypeDeclType(Constructor->getParent())
5467 << /*const=*/1
5468 << Entity.getName();
5469 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5470 << Entity.getName();
5471 } else {
5472 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5473 << DestType << (bool)DestType->getAs<RecordType>();
5474 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00005475 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005476
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005477 case FK_Incomplete:
5478 S.RequireCompleteType(Kind.getLocation(), DestType,
5479 diag::err_init_incomplete_type);
5480 break;
5481
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005482 case FK_ListInitializationFailed: {
5483 // Run the init list checker again to emit diagnostics.
5484 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5485 QualType DestType = Entity.getType();
5486 InitListChecker DiagnoseInitList(S, Entity, InitList,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00005487 DestType, /*VerifyOnly=*/false,
5488 Kind.getKind() != InitializationKind::IK_Direct ||
5489 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005490 assert(DiagnoseInitList.HadError() &&
5491 "Inconsistent init list check result.");
5492 break;
5493 }
John McCall4124c492011-10-17 18:40:02 +00005494
5495 case FK_PlaceholderType: {
5496 // FIXME: Already diagnosed!
5497 break;
5498 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00005499
5500 case FK_InitListElementCopyFailure: {
5501 // Try to perform all copies again.
5502 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5503 unsigned NumInits = InitList->getNumInits();
5504 QualType DestType = Entity.getType();
5505 QualType E;
5506 bool Success = S.isStdInitializerList(DestType, &E);
5507 (void)Success;
5508 assert(Success && "Where did the std::initializer_list go?");
5509 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5510 S.Context.getConstantArrayType(E,
5511 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5512 NumInits),
5513 ArrayType::Normal, 0));
5514 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
5515 0, HiddenArray);
5516 // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
5517 // where the init list type is wrong, e.g.
5518 // std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
5519 // FIXME: Emit a note if we hit the limit?
5520 int ErrorCount = 0;
5521 for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
5522 Element.setElementIndex(i);
5523 ExprResult Init = S.Owned(InitList->getInit(i));
5524 if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
5525 .isInvalid())
5526 ++ErrorCount;
5527 }
5528 break;
5529 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005530 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005531
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005532 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005533 return true;
5534}
Douglas Gregore1314a62009-12-18 05:02:21 +00005535
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005536void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005537 switch (SequenceKind) {
5538 case FailedSequence: {
5539 OS << "Failed sequence: ";
5540 switch (Failure) {
5541 case FK_TooManyInitsForReference:
5542 OS << "too many initializers for reference";
5543 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005544
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005545 case FK_ArrayNeedsInitList:
5546 OS << "array requires initializer list";
5547 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005548
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005549 case FK_ArrayNeedsInitListOrStringLiteral:
5550 OS << "array requires initializer list or string literal";
5551 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005552
Douglas Gregore2f943b2011-02-22 18:29:51 +00005553 case FK_ArrayTypeMismatch:
5554 OS << "array type mismatch";
5555 break;
5556
5557 case FK_NonConstantArrayInit:
5558 OS << "non-constant array initializer";
5559 break;
5560
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005561 case FK_AddressOfOverloadFailed:
5562 OS << "address of overloaded function failed";
5563 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005564
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005565 case FK_ReferenceInitOverloadFailed:
5566 OS << "overload resolution for reference initialization failed";
5567 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005568
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005569 case FK_NonConstLValueReferenceBindingToTemporary:
5570 OS << "non-const lvalue reference bound to temporary";
5571 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005572
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005573 case FK_NonConstLValueReferenceBindingToUnrelated:
5574 OS << "non-const lvalue reference bound to unrelated type";
5575 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005576
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005577 case FK_RValueReferenceBindingToLValue:
5578 OS << "rvalue reference bound to an lvalue";
5579 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005580
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005581 case FK_ReferenceInitDropsQualifiers:
5582 OS << "reference initialization drops qualifiers";
5583 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005584
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005585 case FK_ReferenceInitFailed:
5586 OS << "reference initialization failed";
5587 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005588
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005589 case FK_ConversionFailed:
5590 OS << "conversion failed";
5591 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005592
John Wiegley01296292011-04-08 18:41:53 +00005593 case FK_ConversionFromPropertyFailed:
5594 OS << "conversion from property failed";
5595 break;
5596
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005597 case FK_TooManyInitsForScalar:
5598 OS << "too many initializers for scalar";
5599 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005600
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005601 case FK_ReferenceBindingToInitList:
5602 OS << "referencing binding to initializer list";
5603 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005604
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005605 case FK_InitListBadDestinationType:
5606 OS << "initializer list for non-aggregate, non-scalar type";
5607 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005608
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005609 case FK_UserConversionOverloadFailed:
5610 OS << "overloading failed for user-defined conversion";
5611 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005612
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005613 case FK_ConstructorOverloadFailed:
5614 OS << "constructor overloading failed";
5615 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005616
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005617 case FK_DefaultInitOfConst:
5618 OS << "default initialization of a const variable";
5619 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005620
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00005621 case FK_Incomplete:
5622 OS << "initialization of incomplete type";
5623 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005624
5625 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005626 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00005627 break;
5628
John McCalla59dc2f2012-01-05 00:13:19 +00005629 case FK_VariableLengthArrayHasInitializer:
5630 OS << "variable length array has an initializer";
5631 break;
5632
John McCall4124c492011-10-17 18:40:02 +00005633 case FK_PlaceholderType:
5634 OS << "initializer expression isn't contextually valid";
5635 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00005636
5637 case FK_ListConstructorOverloadFailed:
5638 OS << "list constructor overloading failed";
5639 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00005640
5641 case FK_InitListElementCopyFailure:
5642 OS << "copy construction of initializer list element failed";
5643 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005644 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005645 OS << '\n';
5646 return;
5647 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005648
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005649 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00005650 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005651 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005652
Sebastian Redld201edf2011-06-05 13:59:11 +00005653 case NormalSequence:
5654 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005655 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005656 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005657
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005658 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5659 if (S != step_begin()) {
5660 OS << " -> ";
5661 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005662
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005663 switch (S->Kind) {
5664 case SK_ResolveAddressOfOverloadedFunction:
5665 OS << "resolve address of overloaded function";
5666 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005667
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005668 case SK_CastDerivedToBaseRValue:
5669 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5670 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005671
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005672 case SK_CastDerivedToBaseXValue:
5673 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5674 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005675
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005676 case SK_CastDerivedToBaseLValue:
5677 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5678 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005679
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005680 case SK_BindReference:
5681 OS << "bind reference to lvalue";
5682 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005683
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005684 case SK_BindReferenceToTemporary:
5685 OS << "bind reference to a temporary";
5686 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005687
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005688 case SK_ExtraneousCopyToTemporary:
5689 OS << "extraneous C++03 copy to temporary";
5690 break;
5691
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005692 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00005693 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005694 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005695
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005696 case SK_QualificationConversionRValue:
5697 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00005698 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005699
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005700 case SK_QualificationConversionXValue:
5701 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00005702 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005703
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005704 case SK_QualificationConversionLValue:
5705 OS << "qualification conversion (lvalue)";
5706 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005707
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005708 case SK_ConversionSequence:
5709 OS << "implicit conversion sequence (";
5710 S->ICS->DebugPrint(); // FIXME: use OS
5711 OS << ")";
5712 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005713
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005714 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005715 OS << "list aggregate initialization";
5716 break;
5717
5718 case SK_ListConstructorCall:
5719 OS << "list initialization via constructor";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005720 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005721
Sebastian Redl29526f02011-11-27 16:50:07 +00005722 case SK_UnwrapInitList:
5723 OS << "unwrap reference initializer list";
5724 break;
5725
5726 case SK_RewrapInitList:
5727 OS << "rewrap reference initializer list";
5728 break;
5729
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005730 case SK_ConstructorInitialization:
5731 OS << "constructor initialization";
5732 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005733
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005734 case SK_ZeroInitialization:
5735 OS << "zero initialization";
5736 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005737
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005738 case SK_CAssignment:
5739 OS << "C assignment";
5740 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005741
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005742 case SK_StringInit:
5743 OS << "string initialization";
5744 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005745
5746 case SK_ObjCObjectConversion:
5747 OS << "Objective-C object conversion";
5748 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005749
5750 case SK_ArrayInit:
5751 OS << "array initialization";
5752 break;
John McCall31168b02011-06-15 23:02:42 +00005753
5754 case SK_PassByIndirectCopyRestore:
5755 OS << "pass by indirect copy and restore";
5756 break;
5757
5758 case SK_PassByIndirectRestore:
5759 OS << "pass by indirect restore";
5760 break;
5761
5762 case SK_ProduceObjCObject:
5763 OS << "Objective-C object retension";
5764 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00005765
5766 case SK_StdInitializerList:
5767 OS << "std::initializer_list from initializer list";
5768 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005769 }
5770 }
5771}
5772
5773void InitializationSequence::dump() const {
5774 dump(llvm::errs());
5775}
5776
Richard Smith66e05fe2012-01-18 05:21:49 +00005777static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
5778 QualType EntityType,
5779 const Expr *PreInit,
5780 const Expr *PostInit) {
5781 if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
5782 return;
5783
5784 // A narrowing conversion can only appear as the final implicit conversion in
5785 // an initialization sequence.
5786 const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
5787 if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
5788 return;
5789
5790 const ImplicitConversionSequence &ICS = *LastStep.ICS;
5791 const StandardConversionSequence *SCS = 0;
5792 switch (ICS.getKind()) {
5793 case ImplicitConversionSequence::StandardConversion:
5794 SCS = &ICS.Standard;
5795 break;
5796 case ImplicitConversionSequence::UserDefinedConversion:
5797 SCS = &ICS.UserDefined.After;
5798 break;
5799 case ImplicitConversionSequence::AmbiguousConversion:
5800 case ImplicitConversionSequence::EllipsisConversion:
5801 case ImplicitConversionSequence::BadConversion:
5802 return;
5803 }
5804
5805 // Determine the type prior to the narrowing conversion. If a conversion
5806 // operator was used, this may be different from both the type of the entity
5807 // and of the pre-initialization expression.
5808 QualType PreNarrowingType = PreInit->getType();
5809 if (Seq.step_begin() + 1 != Seq.step_end())
5810 PreNarrowingType = Seq.step_end()[-2].Type;
5811
5812 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
5813 APValue ConstantValue;
Richard Smithf8379a02012-01-18 23:55:52 +00005814 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00005815 case NK_Not_Narrowing:
5816 // No narrowing occurred.
5817 return;
5818
5819 case NK_Type_Narrowing:
5820 // This was a floating-to-integer conversion, which is always considered a
5821 // narrowing conversion even if the value is a constant and can be
5822 // represented exactly as an integer.
5823 S.Diag(PostInit->getLocStart(),
Douglas Gregor84585ab2012-01-23 15:29:33 +00005824 S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
5825 diag::warn_init_list_type_narrowing
5826 : S.isSFINAEContext()?
5827 diag::err_init_list_type_narrowing_sfinae
5828 : diag::err_init_list_type_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00005829 << PostInit->getSourceRange()
5830 << PreNarrowingType.getLocalUnqualifiedType()
5831 << EntityType.getLocalUnqualifiedType();
5832 break;
5833
5834 case NK_Constant_Narrowing:
5835 // A constant value was narrowed.
5836 S.Diag(PostInit->getLocStart(),
Douglas Gregor84585ab2012-01-23 15:29:33 +00005837 S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
5838 diag::warn_init_list_constant_narrowing
5839 : S.isSFINAEContext()?
5840 diag::err_init_list_constant_narrowing_sfinae
5841 : diag::err_init_list_constant_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00005842 << PostInit->getSourceRange()
Richard Smithf6f003a2011-12-16 19:06:07 +00005843 << ConstantValue.getAsString(S.getASTContext(), EntityType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005844 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00005845 break;
5846
5847 case NK_Variable_Narrowing:
5848 // A variable's value may have been narrowed.
5849 S.Diag(PostInit->getLocStart(),
Douglas Gregor84585ab2012-01-23 15:29:33 +00005850 S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
5851 diag::warn_init_list_variable_narrowing
5852 : S.isSFINAEContext()?
5853 diag::err_init_list_variable_narrowing_sfinae
5854 : diag::err_init_list_variable_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00005855 << PostInit->getSourceRange()
5856 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005857 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00005858 break;
5859 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005860
5861 llvm::SmallString<128> StaticCast;
5862 llvm::raw_svector_ostream OS(StaticCast);
5863 OS << "static_cast<";
5864 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5865 // It's important to use the typedef's name if there is one so that the
5866 // fixit doesn't break code using types like int64_t.
5867 //
5868 // FIXME: This will break if the typedef requires qualification. But
5869 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00005870 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005871 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5872 OS << BT->getName(S.getLangOptions());
5873 else {
5874 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5875 // with a broken cast.
5876 return;
5877 }
5878 OS << ">(";
Richard Smith66e05fe2012-01-18 05:21:49 +00005879 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
5880 << PostInit->getSourceRange()
5881 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005882 << FixItHint::CreateInsertion(
Richard Smith66e05fe2012-01-18 05:21:49 +00005883 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005884}
5885
Douglas Gregore1314a62009-12-18 05:02:21 +00005886//===----------------------------------------------------------------------===//
5887// Initialization helper functions
5888//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00005889bool
5890Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5891 ExprResult Init) {
5892 if (Init.isInvalid())
5893 return false;
5894
5895 Expr *InitE = Init.get();
5896 assert(InitE && "No initialization expression");
5897
5898 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5899 SourceLocation());
5900 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005901 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00005902}
5903
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005904ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00005905Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5906 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005907 ExprResult Init,
5908 bool TopLevelOfInitList) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005909 if (Init.isInvalid())
5910 return ExprError();
5911
John McCall1f425642010-11-11 03:21:53 +00005912 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00005913 assert(InitE && "No initialization expression?");
5914
5915 if (EqualLoc.isInvalid())
5916 EqualLoc = InitE->getLocStart();
5917
5918 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5919 EqualLoc);
5920 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5921 Init.release();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005922
Richard Smith66e05fe2012-01-18 05:21:49 +00005923 ExprResult Result = Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
5924
5925 if (!Result.isInvalid() && TopLevelOfInitList)
5926 DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
5927 InitE, Result.get());
5928
5929 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00005930}