blob: a2e45530d2c22ca9e7a952175457826cc26cabcc [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//
Chris Lattner0cb78032009-02-24 22:27:37 +000010// This file implements semantic analysis for initializers. The main entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
13//
Chris Lattner9ececce2009-02-24 22:48:58 +000014// This file also implements Sema::CheckInitializerTypes.
Steve Narofff8ecff22008-05-01 22:18:59 +000015//
16//===----------------------------------------------------------------------===//
17
Douglas Gregor3e1e5272009-12-09 23:02:17 +000018#include "SemaInit.h"
Douglas Gregor4e0299b2010-01-01 00:03:05 +000019#include "Lookup.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000020#include "Sema.h"
Douglas Gregore4a0bb72009-01-22 00:58:24 +000021#include "clang/Parse/Designator.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000022#include "clang/AST/ASTContext.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000023#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000025#include "clang/AST/TypeLoc.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.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
Chris Lattnerd8b741c82009-02-24 23:10:27 +000034static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattnera9196812009-02-26 23:26:43 +000035 const ArrayType *AT = Context.getAsArrayType(DeclType);
36 if (!AT) return 0;
37
Eli Friedman893abe42009-05-29 18:22:49 +000038 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
39 return 0;
40
Chris Lattnera9196812009-02-26 23:26:43 +000041 // See if this is a string literal or @encode.
42 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000043
Chris Lattnera9196812009-02-26 23:26:43 +000044 // Handle @encode, which is a narrow string.
45 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
46 return Init;
47
48 // Otherwise we can only handle string literals.
49 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000050 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000051
52 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattnera9196812009-02-26 23:26:43 +000053 // char array can be initialized with a narrow string.
54 // Only allow char x[] = "foo"; not char x[] = L"foo";
55 if (!SL->isWide())
Eli Friedman42a84652009-05-31 10:54:53 +000056 return ElemTy->isCharType() ? Init : 0;
Chris Lattnera9196812009-02-26 23:26:43 +000057
Eli Friedman42a84652009-05-31 10:54:53 +000058 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
59 // correction from DR343): "An array with element type compatible with a
60 // qualified or unqualified version of wchar_t may be initialized by a wide
61 // string literal, optionally enclosed in braces."
62 if (Context.typesAreCompatible(Context.getWCharType(),
63 ElemTy.getUnqualifiedType()))
Chris Lattnera9196812009-02-26 23:26:43 +000064 return Init;
Mike Stump11289f42009-09-09 15:08:12 +000065
Chris Lattner0cb78032009-02-24 22:27:37 +000066 return 0;
67}
68
Anders Carlsson26d05642010-01-23 18:35:41 +000069static Sema::OwningExprResult
70CheckSingleInitializer(const InitializedEntity *Entity,
71 Sema::OwningExprResult Init, QualType DeclType, Sema &S){
72 Expr *InitExpr = Init.takeAs<Expr>();
73
Chris Lattner0cb78032009-02-24 22:27:37 +000074 // Get the type before calling CheckSingleAssignmentConstraints(), since
75 // it can promote the expression.
Anders Carlsson26d05642010-01-23 18:35:41 +000076 QualType InitType = InitExpr->getType();
Mike Stump11289f42009-09-09 15:08:12 +000077
Chris Lattner94d2f682009-02-24 22:46:58 +000078 if (S.getLangOptions().CPlusPlus) {
Anders Carlsson3cc795a2010-01-23 19:22:30 +000079 if (Entity) {
80 assert(Entity->getType() == DeclType);
81
82 // C++ [dcl.init.aggr]p2:
83 // Each member is copy-initialized from the corresponding
84 // initializer-clause
85 Sema::OwningExprResult Result =
86 S.PerformCopyInitialization(*Entity, InitExpr->getLocStart(),
87 S.Owned(InitExpr));
88
89 return move(Result);
90 } else {
91 // FIXME: I dislike this error message. A lot.
92 if (S.PerformImplicitConversion(InitExpr, DeclType,
93 Sema::AA_Initializing,
94 /*DirectInit=*/false)) {
95 ImplicitConversionSequence ICS;
96 OverloadCandidateSet CandidateSet;
97 if (S.IsUserDefinedConversion(InitExpr, DeclType, ICS.UserDefined,
98 CandidateSet,
99 true, false, false) != OR_Ambiguous) {
100 S.Diag(InitExpr->getSourceRange().getBegin(),
101 diag::err_typecheck_convert_incompatible)
102 << DeclType << InitExpr->getType()
103 << Sema::AA_Initializing
104 << InitExpr->getSourceRange();
105 return S.ExprError();
106 }
Anders Carlsson26d05642010-01-23 18:35:41 +0000107 S.Diag(InitExpr->getSourceRange().getBegin(),
Anders Carlsson3cc795a2010-01-23 19:22:30 +0000108 diag::err_typecheck_convert_ambiguous)
109 << DeclType << InitExpr->getType() << InitExpr->getSourceRange();
110 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
111 &InitExpr, 1);
112
Anders Carlsson26d05642010-01-23 18:35:41 +0000113 return S.ExprError();
114 }
Anders Carlsson26d05642010-01-23 18:35:41 +0000115
Anders Carlsson3cc795a2010-01-23 19:22:30 +0000116 Init.release();
117 return S.Owned(InitExpr);
118 }
Chris Lattner0cb78032009-02-24 22:27:37 +0000119 }
Mike Stump11289f42009-09-09 15:08:12 +0000120
Chris Lattner94d2f682009-02-24 22:46:58 +0000121 Sema::AssignConvertType ConvTy =
Anders Carlsson26d05642010-01-23 18:35:41 +0000122 S.CheckSingleAssignmentConstraints(DeclType, InitExpr);
123 if (S.DiagnoseAssignmentResult(ConvTy, InitExpr->getLocStart(), DeclType,
124 InitType, InitExpr, Sema::AA_Initializing))
125 return S.ExprError();
126
127 Init.release();
128 return S.Owned(InitExpr);
Chris Lattner0cb78032009-02-24 22:27:37 +0000129}
130
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000131static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
132 // Get the length of the string as parsed.
133 uint64_t StrLength =
134 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
135
Mike Stump11289f42009-09-09 15:08:12 +0000136
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000137 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000138 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +0000139 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +0000140 // being initialized to a string literal.
141 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000142 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +0000143 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +0000144 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
145 ConstVal,
146 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000147 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000148 }
Mike Stump11289f42009-09-09 15:08:12 +0000149
Eli Friedman893abe42009-05-29 18:22:49 +0000150 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000151
Eli Friedman893abe42009-05-29 18:22:49 +0000152 // C99 6.7.8p14. We have an array of character type with known size. However,
153 // the size may be smaller or larger than the string we are initializing.
154 // FIXME: Avoid truncation for 64-bit length strings.
155 if (StrLength-1 > CAT->getSize().getZExtValue())
156 S.Diag(Str->getSourceRange().getBegin(),
157 diag::warn_initializer_string_for_char_array_too_long)
158 << Str->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +0000159
Eli Friedman893abe42009-05-29 18:22:49 +0000160 // Set the type to the actual size that we are initializing. If we have
161 // something like:
162 // char x[1] = "foo";
163 // then this will set the string literal's type to char[1].
164 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000165}
166
Chris Lattner0cb78032009-02-24 22:27:37 +0000167//===----------------------------------------------------------------------===//
168// Semantic checking for initializer lists.
169//===----------------------------------------------------------------------===//
170
Douglas Gregorcde232f2009-01-29 01:05:33 +0000171/// @brief Semantic checking for initializer lists.
172///
173/// The InitListChecker class contains a set of routines that each
174/// handle the initialization of a certain kind of entity, e.g.,
175/// arrays, vectors, struct/union types, scalars, etc. The
176/// InitListChecker itself performs a recursive walk of the subobject
177/// structure of the type to be initialized, while stepping through
178/// the initializer list one element at a time. The IList and Index
179/// parameters to each of the Check* routines contain the active
180/// (syntactic) initializer list and the index into that initializer
181/// list that represents the current initializer. Each routine is
182/// responsible for moving that Index forward as it consumes elements.
183///
184/// Each Check* routine also has a StructuredList/StructuredIndex
185/// arguments, which contains the current the "structured" (semantic)
186/// initializer list and the index into that initializer list where we
187/// are copying initializers as we map them over to the semantic
188/// list. Once we have completed our recursive walk of the subobject
189/// structure, we will have constructed a full semantic initializer
190/// list.
191///
192/// C99 designators cause changes in the initializer list traversal,
193/// because they make the initialization "jump" into a specific
194/// subobject and then continue the initialization from that
195/// point. CheckDesignatedInitializer() recursively steps into the
196/// designated subobject and manages backing out the recursion to
197/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000198namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000199class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000200 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000201 bool hadError;
202 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
203 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000204
205 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000206 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000207 unsigned &StructuredIndex,
208 bool TopLevelObject = false);
Anders Carlssond0849252010-01-23 19:55:29 +0000209 void CheckExplicitInitList(const InitializedEntity *Entity,
210 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000211 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000212 unsigned &StructuredIndex,
213 bool TopLevelObject = false);
Anders Carlssond0849252010-01-23 19:55:29 +0000214 void CheckListElementTypes(const InitializedEntity *Entity,
215 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000216 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000217 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000218 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000219 unsigned &StructuredIndex,
220 bool TopLevelObject = false);
Anders Carlssond0849252010-01-23 19:55:29 +0000221 void CheckSubElementType(const InitializedEntity *Entity,
222 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000223 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000224 InitListExpr *StructuredList,
225 unsigned &StructuredIndex);
Anders Carlssond0849252010-01-23 19:55:29 +0000226 void CheckScalarType(const InitializedEntity *Entity,
227 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000228 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000229 InitListExpr *StructuredList,
230 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000231 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000232 unsigned &Index,
233 InitListExpr *StructuredList,
234 unsigned &StructuredIndex);
Anders Carlssond0849252010-01-23 19:55:29 +0000235 void CheckVectorType(const InitializedEntity *Entity,
236 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000237 InitListExpr *StructuredList,
238 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000239 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
240 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000241 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000242 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000243 unsigned &StructuredIndex,
244 bool TopLevelObject = false);
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000245 void CheckArrayType(const InitializedEntity *Entity,
246 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000247 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000248 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000249 InitListExpr *StructuredList,
250 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000251 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000252 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000253 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000254 RecordDecl::field_iterator *NextField,
255 llvm::APSInt *NextElementIndex,
256 unsigned &Index,
257 InitListExpr *StructuredList,
258 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000259 bool FinishSubobjectInit,
260 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000261 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
262 QualType CurrentObjectType,
263 InitListExpr *StructuredList,
264 unsigned StructuredIndex,
265 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000266 void UpdateStructuredListElement(InitListExpr *StructuredList,
267 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000268 Expr *expr);
269 int numArrayElements(QualType DeclType);
270 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000271
Douglas Gregor2bb07652009-12-22 00:05:34 +0000272 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
273 const InitializedEntity &ParentEntity,
274 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000275 void FillInValueInitializations(const InitializedEntity &Entity,
276 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000277public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000278 InitListChecker(Sema &S, const InitializedEntity &Entity,
279 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000280 bool HadError() { return hadError; }
281
282 // @brief Retrieves the fully-structured initializer list used for
283 // semantic analysis and code generation.
284 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
285};
Chris Lattner9ececce2009-02-24 22:48:58 +0000286} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000287
Douglas Gregor2bb07652009-12-22 00:05:34 +0000288void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
289 const InitializedEntity &ParentEntity,
290 InitListExpr *ILE,
291 bool &RequiresSecondPass) {
292 SourceLocation Loc = ILE->getSourceRange().getBegin();
293 unsigned NumInits = ILE->getNumInits();
294 InitializedEntity MemberEntity
295 = InitializedEntity::InitializeMember(Field, &ParentEntity);
296 if (Init >= NumInits || !ILE->getInit(Init)) {
297 // FIXME: We probably don't need to handle references
298 // specially here, since value-initialization of references is
299 // handled in InitializationSequence.
300 if (Field->getType()->isReferenceType()) {
301 // C++ [dcl.init.aggr]p9:
302 // If an incomplete or empty initializer-list leaves a
303 // member of reference type uninitialized, the program is
304 // ill-formed.
305 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
306 << Field->getType()
307 << ILE->getSyntacticForm()->getSourceRange();
308 SemaRef.Diag(Field->getLocation(),
309 diag::note_uninit_reference_member);
310 hadError = true;
311 return;
312 }
313
314 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
315 true);
316 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
317 if (!InitSeq) {
318 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
319 hadError = true;
320 return;
321 }
322
323 Sema::OwningExprResult MemberInit
324 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
325 Sema::MultiExprArg(SemaRef, 0, 0));
326 if (MemberInit.isInvalid()) {
327 hadError = true;
328 return;
329 }
330
331 if (hadError) {
332 // Do nothing
333 } else if (Init < NumInits) {
334 ILE->setInit(Init, MemberInit.takeAs<Expr>());
335 } else if (InitSeq.getKind()
336 == InitializationSequence::ConstructorInitialization) {
337 // Value-initialization requires a constructor call, so
338 // extend the initializer list to include the constructor
339 // call and make a note that we'll need to take another pass
340 // through the initializer list.
341 ILE->updateInit(Init, MemberInit.takeAs<Expr>());
342 RequiresSecondPass = true;
343 }
344 } else if (InitListExpr *InnerILE
345 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
346 FillInValueInitializations(MemberEntity, InnerILE,
347 RequiresSecondPass);
348}
349
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000350/// Recursively replaces NULL values within the given initializer list
351/// with expressions that perform value-initialization of the
352/// appropriate type.
Douglas Gregor723796a2009-12-16 06:35:08 +0000353void
354InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
355 InitListExpr *ILE,
356 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000357 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000358 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000359 SourceLocation Loc = ILE->getSourceRange().getBegin();
360 if (ILE->getSyntacticForm())
361 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000362
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000363 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000364 if (RType->getDecl()->isUnion() &&
365 ILE->getInitializedFieldInUnion())
366 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
367 Entity, ILE, RequiresSecondPass);
368 else {
369 unsigned Init = 0;
370 for (RecordDecl::field_iterator
371 Field = RType->getDecl()->field_begin(),
372 FieldEnd = RType->getDecl()->field_end();
373 Field != FieldEnd; ++Field) {
374 if (Field->isUnnamedBitfield())
375 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000376
Douglas Gregor2bb07652009-12-22 00:05:34 +0000377 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000378 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000379
380 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
381 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000382 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000383
Douglas Gregor2bb07652009-12-22 00:05:34 +0000384 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000385
Douglas Gregor2bb07652009-12-22 00:05:34 +0000386 // Only look at the first initialization of a union.
387 if (RType->getDecl()->isUnion())
388 break;
389 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000390 }
391
392 return;
Mike Stump11289f42009-09-09 15:08:12 +0000393 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000394
395 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000396
Douglas Gregor723796a2009-12-16 06:35:08 +0000397 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000398 unsigned NumInits = ILE->getNumInits();
399 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000400 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000401 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000402 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
403 NumElements = CAType->getSize().getZExtValue();
Douglas Gregor723796a2009-12-16 06:35:08 +0000404 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
405 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000406 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000407 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000408 NumElements = VType->getNumElements();
Douglas Gregor723796a2009-12-16 06:35:08 +0000409 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
410 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000411 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000412 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000413
Douglas Gregor723796a2009-12-16 06:35:08 +0000414
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000415 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000416 if (hadError)
417 return;
418
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000419 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
420 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000421 ElementEntity.setElementIndex(Init);
422
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000423 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000424 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
425 true);
426 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
427 if (!InitSeq) {
428 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000429 hadError = true;
430 return;
431 }
432
Douglas Gregor723796a2009-12-16 06:35:08 +0000433 Sema::OwningExprResult ElementInit
434 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
435 Sema::MultiExprArg(SemaRef, 0, 0));
436 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000437 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000438 return;
439 }
440
441 if (hadError) {
442 // Do nothing
443 } else if (Init < NumInits) {
444 ILE->setInit(Init, ElementInit.takeAs<Expr>());
445 } else if (InitSeq.getKind()
446 == InitializationSequence::ConstructorInitialization) {
447 // Value-initialization requires a constructor call, so
448 // extend the initializer list to include the constructor
449 // call and make a note that we'll need to take another pass
450 // through the initializer list.
451 ILE->updateInit(Init, ElementInit.takeAs<Expr>());
452 RequiresSecondPass = true;
453 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000454 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000455 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
456 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000457 }
458}
459
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000460
Douglas Gregor723796a2009-12-16 06:35:08 +0000461InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
462 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000463 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000464 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000465
Eli Friedman23a9e312008-05-19 19:16:24 +0000466 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000467 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000468 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000469 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000470 CheckExplicitInitList(&Entity, IL, T, newIndex,
471 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000472 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000473
Douglas Gregor723796a2009-12-16 06:35:08 +0000474 if (!hadError) {
475 bool RequiresSecondPass = false;
476 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000477 if (RequiresSecondPass && !hadError)
Douglas Gregor723796a2009-12-16 06:35:08 +0000478 FillInValueInitializations(Entity, FullyStructuredList,
479 RequiresSecondPass);
480 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000481}
482
483int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000484 // FIXME: use a proper constant
485 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000486 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000487 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000488 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
489 }
490 return maxElements;
491}
492
493int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000494 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000495 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000496 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000497 Field = structDecl->field_begin(),
498 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000499 Field != FieldEnd; ++Field) {
500 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
501 ++InitializableMembers;
502 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000503 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000504 return std::min(InitializableMembers, 1);
505 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000506}
507
Mike Stump11289f42009-09-09 15:08:12 +0000508void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000509 QualType T, unsigned &Index,
510 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000511 unsigned &StructuredIndex,
512 bool TopLevelObject) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000513 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000514
Steve Narofff8ecff22008-05-01 22:18:59 +0000515 if (T->isArrayType())
516 maxElements = numArrayElements(T);
517 else if (T->isStructureType() || T->isUnionType())
518 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000519 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000520 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000521 else
522 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000523
Eli Friedmane0f832b2008-05-25 13:49:22 +0000524 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000525 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000526 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000527 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000528 hadError = true;
529 return;
530 }
531
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000532 // Build a structured initializer list corresponding to this subobject.
533 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000534 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
535 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000536 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
537 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000538 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000539
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000540 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000541 unsigned StartIndex = Index;
Anders Carlssond0849252010-01-23 19:55:29 +0000542 CheckListElementTypes(0, ParentIList, T, false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000543 StructuredSubobjectInitList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000544 StructuredSubobjectInitIndex,
545 TopLevelObject);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000546 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000547 StructuredSubobjectInitList->setType(T);
548
Douglas Gregor5741efb2009-03-01 17:12:46 +0000549 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000550 // range corresponds with the end of the last initializer it used.
551 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000552 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000553 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
554 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
555 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000556}
557
Anders Carlssond0849252010-01-23 19:55:29 +0000558void InitListChecker::CheckExplicitInitList(const InitializedEntity *Entity,
559 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000560 unsigned &Index,
561 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000562 unsigned &StructuredIndex,
563 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000564 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000565 SyntacticToSemantic[IList] = StructuredList;
566 StructuredList->setSyntacticForm(IList);
Anders Carlssond0849252010-01-23 19:55:29 +0000567 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
568 Index, StructuredList, StructuredIndex, TopLevelObject);
Steve Naroff125d73d2008-05-06 00:23:44 +0000569 IList->setType(T);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000570 StructuredList->setType(T);
Eli Friedman85f54972008-05-25 13:22:35 +0000571 if (hadError)
572 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000573
Eli Friedman85f54972008-05-25 13:22:35 +0000574 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000575 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000576 if (StructuredIndex == 1 &&
577 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000578 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000579 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000580 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000581 hadError = true;
582 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000583 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000584 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000585 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000586 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000587 // Don't complain for incomplete types, since we'll get an error
588 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000589 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000590 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000591 CurrentObjectType->isArrayType()? 0 :
592 CurrentObjectType->isVectorType()? 1 :
593 CurrentObjectType->isScalarType()? 2 :
594 CurrentObjectType->isUnionType()? 3 :
595 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000596
597 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000598 if (SemaRef.getLangOptions().CPlusPlus) {
599 DK = diag::err_excess_initializers;
600 hadError = true;
601 }
Nate Begeman425038c2009-07-07 21:53:06 +0000602 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
603 DK = diag::err_excess_initializers;
604 hadError = true;
605 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000606
Chris Lattnerb0912a52009-02-24 22:50:46 +0000607 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000608 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000609 }
610 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000611
Eli Friedman0b4af8f2009-05-16 11:45:48 +0000612 if (T->isScalarType() && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000613 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000614 << IList->getSourceRange()
Chris Lattner3c7b86f2009-12-06 17:36:05 +0000615 << CodeModificationHint::CreateRemoval(IList->getLocStart())
616 << CodeModificationHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000617}
618
Anders Carlssond0849252010-01-23 19:55:29 +0000619void InitListChecker::CheckListElementTypes(const InitializedEntity *Entity,
620 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000621 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000622 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000623 unsigned &Index,
624 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000625 unsigned &StructuredIndex,
626 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000627 if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000628 CheckScalarType(Entity, IList, DeclType, Index,
629 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000630 } else if (DeclType->isVectorType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000631 CheckVectorType(Entity, IList, DeclType, Index,
632 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000633 } else if (DeclType->isAggregateType()) {
634 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000635 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000636 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000637 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000638 StructuredList, StructuredIndex,
639 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000640 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000641 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000642 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000643 false);
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000644 CheckArrayType(Entity, IList, DeclType, Zero,
645 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000646 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000647 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000648 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000649 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
650 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000651 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000652 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000653 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000654 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000655 } else if (DeclType->isRecordType()) {
656 // C++ [dcl.init]p14:
657 // [...] If the class is an aggregate (8.5.1), and the initializer
658 // is a brace-enclosed list, see 8.5.1.
659 //
660 // Note: 8.5.1 is handled below; here, we diagnose the case where
661 // we have an initializer list and a destination type that is not
662 // an aggregate.
663 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000664 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000665 << DeclType << IList->getSourceRange();
666 hadError = true;
667 } else if (DeclType->isReferenceType()) {
668 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000669 } else {
670 // In C, all types are either scalars or aggregates, but
Mike Stump11289f42009-09-09 15:08:12 +0000671 // additional handling is needed here for C++ (and possibly others?).
Steve Narofff8ecff22008-05-01 22:18:59 +0000672 assert(0 && "Unsupported initializer type");
673 }
674}
675
Anders Carlssond0849252010-01-23 19:55:29 +0000676void InitListChecker::CheckSubElementType(const InitializedEntity *Entity,
677 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000678 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000679 unsigned &Index,
680 InitListExpr *StructuredList,
681 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000682 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000683 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
684 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000685 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000686 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000687 = getStructuredSubobjectInit(IList, Index, ElemType,
688 StructuredList, StructuredIndex,
689 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000690 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000691 newStructuredList, newStructuredIndex);
692 ++StructuredIndex;
693 ++Index;
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000694 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
695 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000696 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000697 ++Index;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000698 } else if (ElemType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000699 CheckScalarType(Entity, IList, ElemType, Index,
700 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000701 } else if (ElemType->isReferenceType()) {
702 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedman23a9e312008-05-19 19:16:24 +0000703 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000704 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000705 // C++ [dcl.init.aggr]p12:
706 // All implicit type conversions (clause 4) are considered when
707 // initializing the aggregate member with an ini- tializer from
708 // an initializer-list. If the initializer can initialize a
709 // member, the member is initialized. [...]
Mike Stump11289f42009-09-09 15:08:12 +0000710 ImplicitConversionSequence ICS
Anders Carlsson03068aa2009-08-27 17:18:13 +0000711 = SemaRef.TryCopyInitialization(expr, ElemType,
712 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +0000713 /*ForceRValue=*/false,
714 /*InOverloadResolution=*/false);
Anders Carlsson03068aa2009-08-27 17:18:13 +0000715
John McCall0d1da222010-01-12 00:44:57 +0000716 if (!ICS.isBad()) {
Mike Stump11289f42009-09-09 15:08:12 +0000717 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000718 Sema::AA_Initializing))
Douglas Gregord14247a2009-01-30 22:09:00 +0000719 hadError = true;
720 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
721 ++Index;
722 return;
723 }
724
725 // Fall through for subaggregate initialization
726 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000727 // C99 6.7.8p13:
Douglas Gregord14247a2009-01-30 22:09:00 +0000728 //
729 // The initializer for a structure or union object that has
730 // automatic storage duration shall be either an initializer
731 // list as described below, or a single expression that has
732 // compatible structure or union type. In the latter case, the
733 // initial value of the object, including unnamed members, is
734 // that of the expression.
Eli Friedman9782caa2009-06-13 10:38:46 +0000735 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman893abe42009-05-29 18:22:49 +0000736 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000737 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
738 ++Index;
739 return;
740 }
741
742 // Fall through for subaggregate initialization
743 }
744
745 // C++ [dcl.init.aggr]p12:
Mike Stump11289f42009-09-09 15:08:12 +0000746 //
Douglas Gregord14247a2009-01-30 22:09:00 +0000747 // [...] Otherwise, if the member is itself a non-empty
748 // subaggregate, brace elision is assumed and the initializer is
749 // considered for the initialization of the first member of
750 // the subaggregate.
751 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000752 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
Douglas Gregord14247a2009-01-30 22:09:00 +0000753 StructuredIndex);
754 ++StructuredIndex;
755 } else {
756 // We cannot initialize this element, so let
757 // PerformCopyInitialization produce the appropriate diagnostic.
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000758 SemaRef.PerformCopyInitialization(expr, ElemType, Sema::AA_Initializing);
Douglas Gregord14247a2009-01-30 22:09:00 +0000759 hadError = true;
760 ++Index;
761 ++StructuredIndex;
762 }
763 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000764}
765
Anders Carlssond0849252010-01-23 19:55:29 +0000766void InitListChecker::CheckScalarType(const InitializedEntity *Entity,
767 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000768 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000769 InitListExpr *StructuredList,
770 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000771 if (Index < IList->getNumInits()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000772 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000773 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000774 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000775 diag::err_many_braces_around_scalar_init)
776 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000777 hadError = true;
778 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000779 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000780 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000781 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump11289f42009-09-09 15:08:12 +0000782 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000783 diag::err_designator_for_scalar_init)
784 << DeclType << expr->getSourceRange();
785 hadError = true;
786 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000787 ++StructuredIndex;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000788 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000789 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000790
Anders Carlsson26d05642010-01-23 18:35:41 +0000791 Sema::OwningExprResult Result =
Anders Carlssond0849252010-01-23 19:55:29 +0000792 CheckSingleInitializer(Entity, SemaRef.Owned(expr), DeclType, SemaRef);
Anders Carlsson26d05642010-01-23 18:35:41 +0000793
794 Expr *ResultExpr;
795
796 if (Result.isInvalid())
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000797 hadError = true; // types weren't compatible.
Anders Carlsson26d05642010-01-23 18:35:41 +0000798 else {
799 ResultExpr = Result.takeAs<Expr>();
800
801 if (ResultExpr != expr) {
802 // The type was promoted, update initializer list.
803 IList->setInit(Index, ResultExpr);
804 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000805 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000806 if (hadError)
807 ++StructuredIndex;
808 else
Anders Carlsson26d05642010-01-23 18:35:41 +0000809 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
Steve Narofff8ecff22008-05-01 22:18:59 +0000810 ++Index;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000811 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000812 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000813 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000814 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000815 ++Index;
816 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000817 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000818 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000819}
820
Douglas Gregord14247a2009-01-30 22:09:00 +0000821void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
822 unsigned &Index,
823 InitListExpr *StructuredList,
824 unsigned &StructuredIndex) {
825 if (Index < IList->getNumInits()) {
826 Expr *expr = IList->getInit(Index);
827 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000828 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000829 << DeclType << IList->getSourceRange();
830 hadError = true;
831 ++Index;
832 ++StructuredIndex;
833 return;
Mike Stump11289f42009-09-09 15:08:12 +0000834 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000835
836 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Anders Carlsson271e3a42009-08-27 17:30:43 +0000837 if (SemaRef.CheckReferenceInit(expr, DeclType,
Douglas Gregorc809cc22009-09-23 23:04:10 +0000838 /*FIXME:*/expr->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +0000839 /*SuppressUserConversions=*/false,
840 /*AllowExplicit=*/false,
Mike Stump11289f42009-09-09 15:08:12 +0000841 /*ForceRValue=*/false))
Douglas Gregord14247a2009-01-30 22:09:00 +0000842 hadError = true;
843 else if (savExpr != expr) {
844 // The type was promoted, update initializer list.
845 IList->setInit(Index, expr);
846 }
847 if (hadError)
848 ++StructuredIndex;
849 else
850 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
851 ++Index;
852 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000853 // FIXME: It would be wonderful if we could point at the actual member. In
854 // general, it would be useful to pass location information down the stack,
855 // so that we know the location (or decl) of the "current object" being
856 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000857 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000858 diag::err_init_reference_member_uninitialized)
859 << DeclType
860 << IList->getSourceRange();
861 hadError = true;
862 ++Index;
863 ++StructuredIndex;
864 return;
865 }
866}
867
Anders Carlssond0849252010-01-23 19:55:29 +0000868void InitListChecker::CheckVectorType(const InitializedEntity *Entity,
869 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000870 unsigned &Index,
871 InitListExpr *StructuredList,
872 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000873 if (Index < IList->getNumInits()) {
John McCall9dd450b2009-09-21 23:43:11 +0000874 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000875 unsigned maxElements = VT->getNumElements();
876 unsigned numEltsInit = 0;
Steve Narofff8ecff22008-05-01 22:18:59 +0000877 QualType elementType = VT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +0000878
Nate Begeman5ec4b312009-08-10 23:49:36 +0000879 if (!SemaRef.getLangOptions().OpenCL) {
Anders Carlssond0849252010-01-23 19:55:29 +0000880 // FIXME: Once we know Entity is never null we can remove this check,
881 // as well as the else block.
882 if (Entity) {
883 InitializedEntity ElementEntity =
884 InitializedEntity::InitializeElement(SemaRef.Context, 0, *Entity);
885
886 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
887 // Don't attempt to go past the end of the init list
888 if (Index >= IList->getNumInits())
889 break;
890
891 ElementEntity.setElementIndex(Index);
892 CheckSubElementType(&ElementEntity, IList, elementType, Index,
893 StructuredList, StructuredIndex);
894 }
895 } else {
896 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
897 // Don't attempt to go past the end of the init list
898 if (Index >= IList->getNumInits())
899 break;
900
901 CheckSubElementType(0, IList, elementType, Index,
902 StructuredList, StructuredIndex);
903 }
904 }
Nate Begeman5ec4b312009-08-10 23:49:36 +0000905 } else {
906 // OpenCL initializers allows vectors to be constructed from vectors.
907 for (unsigned i = 0; i < maxElements; ++i) {
908 // Don't attempt to go past the end of the init list
909 if (Index >= IList->getNumInits())
910 break;
911 QualType IType = IList->getInit(Index)->getType();
912 if (!IType->isVectorType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000913 CheckSubElementType(0, IList, elementType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000914 StructuredList, StructuredIndex);
915 ++numEltsInit;
916 } else {
John McCall9dd450b2009-09-21 23:43:11 +0000917 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000918 unsigned numIElts = IVT->getNumElements();
919 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
920 numIElts);
Anders Carlssond0849252010-01-23 19:55:29 +0000921 CheckSubElementType(0, IList, VecType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000922 StructuredList, StructuredIndex);
923 numEltsInit += numIElts;
924 }
925 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000926 }
Mike Stump11289f42009-09-09 15:08:12 +0000927
Nate Begeman5ec4b312009-08-10 23:49:36 +0000928 // OpenCL & AltiVec require all elements to be initialized.
929 if (numEltsInit != maxElements)
930 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
931 SemaRef.Diag(IList->getSourceRange().getBegin(),
932 diag::err_vector_incorrect_num_initializers)
933 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000934 }
935}
936
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000937void InitListChecker::CheckArrayType(const InitializedEntity *Entity,
938 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000939 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000940 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000941 unsigned &Index,
942 InitListExpr *StructuredList,
943 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000944 // Check for the special-case of initializing an array with a string.
945 if (Index < IList->getNumInits()) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000946 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
947 SemaRef.Context)) {
948 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000949 // We place the string literal directly into the resulting
950 // initializer list. This is the only place where the structure
951 // of the structured initializer list doesn't match exactly,
952 // because doing so would involve allocating one character
953 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000954 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +0000955 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000956 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000957 return;
958 }
959 }
Chris Lattner7adf0762008-08-04 07:31:14 +0000960 if (const VariableArrayType *VAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000961 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman85f54972008-05-25 13:22:35 +0000962 // Check for VLAs; in standard C it would be possible to check this
963 // earlier, but I don't know where clang accepts VLAs (gcc accepts
964 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +0000965 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000966 diag::err_variable_object_no_init)
967 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +0000968 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000969 ++Index;
970 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +0000971 return;
972 }
973
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000974 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000975 llvm::APSInt maxElements(elementIndex.getBitWidth(),
976 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000977 bool maxElementsKnown = false;
978 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000979 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000980 maxElements = CAT->getSize();
Douglas Gregor033d1252009-01-23 16:54:12 +0000981 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000982 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000983 maxElementsKnown = true;
984 }
985
Chris Lattnerb0912a52009-02-24 22:50:46 +0000986 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattner7adf0762008-08-04 07:31:14 +0000987 ->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000988 while (Index < IList->getNumInits()) {
989 Expr *Init = IList->getInit(Index);
990 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000991 // If we're not the subobject that matches up with the '{' for
992 // the designator, we shouldn't be handling the
993 // designator. Return immediately.
994 if (!SubobjectIsDesignatorContext)
995 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000996
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000997 // Handle this designated initializer. elementIndex will be
998 // updated to be the next array element we'll initialize.
Mike Stump11289f42009-09-09 15:08:12 +0000999 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001000 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001001 StructuredList, StructuredIndex, true,
1002 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001003 hadError = true;
1004 continue;
1005 }
1006
Douglas Gregor033d1252009-01-23 16:54:12 +00001007 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1008 maxElements.extend(elementIndex.getBitWidth());
1009 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1010 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001011 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001012
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001013 // If the array is of incomplete type, keep track of the number of
1014 // elements in the initializer.
1015 if (!maxElementsKnown && elementIndex > maxElements)
1016 maxElements = elementIndex;
1017
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001018 continue;
1019 }
1020
1021 // If we know the maximum number of elements, and we've already
1022 // hit it, stop consuming elements in the initializer list.
1023 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001024 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001025
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001026 // FIXME: Once we know that Entity is not null, we can remove this check,
1027 // and the else block.
1028 if (Entity) {
1029 InitializedEntity ElementEntity =
1030 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1031 *Entity);
1032 // Check this element.
1033 CheckSubElementType(&ElementEntity, IList, elementType, Index,
1034 StructuredList, StructuredIndex);
1035 } else {
1036 // Check this element.
1037 CheckSubElementType(0, IList, elementType, Index,
1038 StructuredList, StructuredIndex);
1039 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001040 ++elementIndex;
1041
1042 // If the array is of incomplete type, keep track of the number of
1043 // elements in the initializer.
1044 if (!maxElementsKnown && elementIndex > maxElements)
1045 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001046 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001047 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001048 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001049 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001050 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001051 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001052 // Sizing an array implicitly to zero is not allowed by ISO C,
1053 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001054 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001055 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001056 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001057
Mike Stump11289f42009-09-09 15:08:12 +00001058 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001059 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001060 }
1061}
1062
Mike Stump11289f42009-09-09 15:08:12 +00001063void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
1064 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001065 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001066 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001067 unsigned &Index,
1068 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001069 unsigned &StructuredIndex,
1070 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001071 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001072
Eli Friedman23a9e312008-05-19 19:16:24 +00001073 // If the record is invalid, some of it's members are invalid. To avoid
1074 // confusion, we forgo checking the intializer for the entire record.
1075 if (structDecl->isInvalidDecl()) {
1076 hadError = true;
1077 return;
Mike Stump11289f42009-09-09 15:08:12 +00001078 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001079
1080 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1081 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001082 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001083 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001084 Field != FieldEnd; ++Field) {
1085 if (Field->getDeclName()) {
1086 StructuredList->setInitializedFieldInUnion(*Field);
1087 break;
1088 }
1089 }
1090 return;
1091 }
1092
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001093 // If structDecl is a forward declaration, this loop won't do
1094 // anything except look at designated initializers; That's okay,
1095 // because an error should get printed out elsewhere. It might be
1096 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001097 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001098 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001099 bool InitializedSomething = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001100 while (Index < IList->getNumInits()) {
1101 Expr *Init = IList->getInit(Index);
1102
1103 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001104 // If we're not the subobject that matches up with the '{' for
1105 // the designator, we shouldn't be handling the
1106 // designator. Return immediately.
1107 if (!SubobjectIsDesignatorContext)
1108 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001109
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001110 // Handle this designated initializer. Field will be updated to
1111 // the next field that we'll be initializing.
Mike Stump11289f42009-09-09 15:08:12 +00001112 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001113 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001114 StructuredList, StructuredIndex,
1115 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001116 hadError = true;
1117
Douglas Gregora9add4e2009-02-12 19:00:39 +00001118 InitializedSomething = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001119 continue;
1120 }
1121
1122 if (Field == FieldEnd) {
1123 // We've run out of fields. We're done.
1124 break;
1125 }
1126
Douglas Gregora9add4e2009-02-12 19:00:39 +00001127 // We've already initialized a member of a union. We're done.
1128 if (InitializedSomething && DeclType->isUnionType())
1129 break;
1130
Douglas Gregor91f84212008-12-11 16:49:14 +00001131 // If we've hit the flexible array member at the end, we're done.
1132 if (Field->getType()->isIncompleteArrayType())
1133 break;
1134
Douglas Gregor51695702009-01-29 16:53:55 +00001135 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001136 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001137 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001138 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001139 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001140
Anders Carlssond0849252010-01-23 19:55:29 +00001141 CheckSubElementType(0, IList, Field->getType(), Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001142 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001143 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001144
1145 if (DeclType->isUnionType()) {
1146 // Initialize the first field within the union.
1147 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001148 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001149
1150 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001151 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001152
Mike Stump11289f42009-09-09 15:08:12 +00001153 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001154 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001155 return;
1156
1157 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001158 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001159 (!isa<InitListExpr>(IList->getInit(Index)) ||
1160 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001161 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001162 diag::err_flexible_array_init_nonempty)
1163 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001164 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001165 << *Field;
1166 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001167 ++Index;
1168 return;
1169 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001170 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001171 diag::ext_flexible_array_init)
1172 << IList->getInit(Index)->getSourceRange().getBegin();
1173 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1174 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001175 }
1176
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001177 if (isa<InitListExpr>(IList->getInit(Index)))
Anders Carlssond0849252010-01-23 19:55:29 +00001178 CheckSubElementType(0, IList, Field->getType(), Index, StructuredList,
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001179 StructuredIndex);
1180 else
1181 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1182 StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001183}
Steve Narofff8ecff22008-05-01 22:18:59 +00001184
Douglas Gregord5846a12009-04-15 06:41:24 +00001185/// \brief Expand a field designator that refers to a member of an
1186/// anonymous struct or union into a series of field designators that
1187/// refers to the field within the appropriate subobject.
1188///
1189/// Field/FieldIndex will be updated to point to the (new)
1190/// currently-designated field.
1191static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001192 DesignatedInitExpr *DIE,
1193 unsigned DesigIdx,
Douglas Gregord5846a12009-04-15 06:41:24 +00001194 FieldDecl *Field,
1195 RecordDecl::field_iterator &FieldIter,
1196 unsigned &FieldIndex) {
1197 typedef DesignatedInitExpr::Designator Designator;
1198
1199 // Build the path from the current object to the member of the
1200 // anonymous struct/union (backwards).
1201 llvm::SmallVector<FieldDecl *, 4> Path;
1202 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump11289f42009-09-09 15:08:12 +00001203
Douglas Gregord5846a12009-04-15 06:41:24 +00001204 // Build the replacement designators.
1205 llvm::SmallVector<Designator, 4> Replacements;
1206 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1207 FI = Path.rbegin(), FIEnd = Path.rend();
1208 FI != FIEnd; ++FI) {
1209 if (FI + 1 == FIEnd)
Mike Stump11289f42009-09-09 15:08:12 +00001210 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001211 DIE->getDesignator(DesigIdx)->getDotLoc(),
1212 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1213 else
1214 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1215 SourceLocation()));
1216 Replacements.back().setField(*FI);
1217 }
1218
1219 // Expand the current designator into the set of replacement
1220 // designators, so we have a full subobject path down to where the
1221 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001222 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001223 &Replacements[0] + Replacements.size());
Mike Stump11289f42009-09-09 15:08:12 +00001224
Douglas Gregord5846a12009-04-15 06:41:24 +00001225 // Update FieldIter/FieldIndex;
1226 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001227 FieldIter = Record->field_begin();
Douglas Gregord5846a12009-04-15 06:41:24 +00001228 FieldIndex = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001229 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregord5846a12009-04-15 06:41:24 +00001230 FieldIter != FEnd; ++FieldIter) {
1231 if (FieldIter->isUnnamedBitfield())
1232 continue;
1233
1234 if (*FieldIter == Path.back())
1235 return;
1236
1237 ++FieldIndex;
1238 }
1239
1240 assert(false && "Unable to find anonymous struct/union field");
1241}
1242
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001243/// @brief Check the well-formedness of a C99 designated initializer.
1244///
1245/// Determines whether the designated initializer @p DIE, which
1246/// resides at the given @p Index within the initializer list @p
1247/// IList, is well-formed for a current object of type @p DeclType
1248/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001249/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001250/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001251///
1252/// @param IList The initializer list in which this designated
1253/// initializer occurs.
1254///
Douglas Gregora5324162009-04-15 04:56:10 +00001255/// @param DIE The designated initializer expression.
1256///
1257/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001258///
1259/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1260/// into which the designation in @p DIE should refer.
1261///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001262/// @param NextField If non-NULL and the first designator in @p DIE is
1263/// a field, this will be set to the field declaration corresponding
1264/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001265///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001266/// @param NextElementIndex If non-NULL and the first designator in @p
1267/// DIE is an array designator or GNU array-range designator, this
1268/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001269///
1270/// @param Index Index into @p IList where the designated initializer
1271/// @p DIE occurs.
1272///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001273/// @param StructuredList The initializer list expression that
1274/// describes all of the subobject initializers in the order they'll
1275/// actually be initialized.
1276///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001277/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001278bool
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001279InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001280 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001281 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001282 QualType &CurrentObjectType,
1283 RecordDecl::field_iterator *NextField,
1284 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001285 unsigned &Index,
1286 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001287 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001288 bool FinishSubobjectInit,
1289 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001290 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001291 // Check the actual initialization for the designated object type.
1292 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001293
1294 // Temporarily remove the designator expression from the
1295 // initializer list that the child calls see, so that we don't try
1296 // to re-process the designator.
1297 unsigned OldIndex = Index;
1298 IList->setInit(OldIndex, DIE->getInit());
1299
Anders Carlssond0849252010-01-23 19:55:29 +00001300 CheckSubElementType(0, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001301 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001302
1303 // Restore the designated initializer expression in the syntactic
1304 // form of the initializer list.
1305 if (IList->getInit(OldIndex) != DIE->getInit())
1306 DIE->setInit(IList->getInit(OldIndex));
1307 IList->setInit(OldIndex, DIE);
1308
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001309 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001310 }
1311
Douglas Gregora5324162009-04-15 04:56:10 +00001312 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001313 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001314 "Need a non-designated initializer list to start from");
1315
Douglas Gregora5324162009-04-15 04:56:10 +00001316 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001317 // Determine the structural initializer list that corresponds to the
1318 // current subobject.
1319 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001320 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001321 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001322 SourceRange(D->getStartLocation(),
1323 DIE->getSourceRange().getEnd()));
1324 assert(StructuredList && "Expected a structured initializer list");
1325
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001326 if (D->isFieldDesignator()) {
1327 // C99 6.7.8p7:
1328 //
1329 // If a designator has the form
1330 //
1331 // . identifier
1332 //
1333 // then the current object (defined below) shall have
1334 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001335 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001336 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001337 if (!RT) {
1338 SourceLocation Loc = D->getDotLoc();
1339 if (Loc.isInvalid())
1340 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001341 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1342 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001343 ++Index;
1344 return true;
1345 }
1346
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001347 // Note: we perform a linear search of the fields here, despite
1348 // the fact that we have a faster lookup method, because we always
1349 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001350 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001351 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001352 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001353 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001354 Field = RT->getDecl()->field_begin(),
1355 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001356 for (; Field != FieldEnd; ++Field) {
1357 if (Field->isUnnamedBitfield())
1358 continue;
1359
Douglas Gregord5846a12009-04-15 06:41:24 +00001360 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001361 break;
1362
1363 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001364 }
1365
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001366 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001367 // There was no normal field in the struct with the designated
1368 // name. Perform another lookup for this name, which may find
1369 // something that we can't designate (e.g., a member function),
1370 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001371 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001372 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001373 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001374 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001375 // Name lookup didn't find anything. Determine whether this
1376 // was a typo for another field name.
1377 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1378 Sema::LookupMemberName);
1379 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl()) &&
1380 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
1381 ReplacementField->getDeclContext()->getLookupContext()
1382 ->Equals(RT->getDecl())) {
1383 SemaRef.Diag(D->getFieldLoc(),
1384 diag::err_field_designator_unknown_suggest)
1385 << FieldName << CurrentObjectType << R.getLookupName()
1386 << CodeModificationHint::CreateReplacement(D->getFieldLoc(),
1387 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001388 SemaRef.Diag(ReplacementField->getLocation(),
1389 diag::note_previous_decl)
1390 << ReplacementField->getDeclName();
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001391 } else {
1392 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1393 << FieldName << CurrentObjectType;
1394 ++Index;
1395 return true;
1396 }
1397 } else if (!KnownField) {
1398 // Determine whether we found a field at all.
1399 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1400 }
1401
1402 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001403 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001404 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001405 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001406 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001407 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001408 ++Index;
1409 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001410 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001411
1412 if (!KnownField &&
1413 cast<RecordDecl>((ReplacementField)->getDeclContext())
1414 ->isAnonymousStructOrUnion()) {
1415 // Handle an field designator that refers to a member of an
1416 // anonymous struct or union.
1417 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1418 ReplacementField,
1419 Field, FieldIndex);
1420 D = DIE->getDesignator(DesigIdx);
1421 } else if (!KnownField) {
1422 // The replacement field comes from typo correction; find it
1423 // in the list of fields.
1424 FieldIndex = 0;
1425 Field = RT->getDecl()->field_begin();
1426 for (; Field != FieldEnd; ++Field) {
1427 if (Field->isUnnamedBitfield())
1428 continue;
1429
1430 if (ReplacementField == *Field ||
1431 Field->getIdentifier() == ReplacementField->getIdentifier())
1432 break;
1433
1434 ++FieldIndex;
1435 }
1436 }
Douglas Gregord5846a12009-04-15 06:41:24 +00001437 } else if (!KnownField &&
1438 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001439 ->isAnonymousStructOrUnion()) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001440 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1441 Field, FieldIndex);
1442 D = DIE->getDesignator(DesigIdx);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001443 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001444
1445 // All of the fields of a union are located at the same place in
1446 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001447 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001448 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001449 StructuredList->setInitializedFieldInUnion(*Field);
1450 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001451
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001452 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001453 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001454
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001455 // Make sure that our non-designated initializer list has space
1456 // for a subobject corresponding to this field.
1457 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001458 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001459
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001460 // This designator names a flexible array member.
1461 if (Field->getType()->isIncompleteArrayType()) {
1462 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001463 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001464 // We can't designate an object within the flexible array
1465 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001466 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001467 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001468 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001469 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001470 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001471 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001472 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001473 << *Field;
1474 Invalid = true;
1475 }
1476
1477 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1478 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001479 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001480 diag::err_flexible_array_init_needs_braces)
1481 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001482 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001483 << *Field;
1484 Invalid = true;
1485 }
1486
1487 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001488 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001489 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001490 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001491 diag::err_flexible_array_init_nonempty)
1492 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001493 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001494 << *Field;
1495 Invalid = true;
1496 }
1497
1498 if (Invalid) {
1499 ++Index;
1500 return true;
1501 }
1502
1503 // Initialize the array.
1504 bool prevHadError = hadError;
1505 unsigned newStructuredIndex = FieldIndex;
1506 unsigned OldIndex = Index;
1507 IList->setInit(Index, DIE->getInit());
Anders Carlssond0849252010-01-23 19:55:29 +00001508 CheckSubElementType(0, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001509 StructuredList, newStructuredIndex);
1510 IList->setInit(OldIndex, DIE);
1511 if (hadError && !prevHadError) {
1512 ++Field;
1513 ++FieldIndex;
1514 if (NextField)
1515 *NextField = Field;
1516 StructuredIndex = FieldIndex;
1517 return true;
1518 }
1519 } else {
1520 // Recurse to check later designated subobjects.
1521 QualType FieldType = (*Field)->getType();
1522 unsigned newStructuredIndex = FieldIndex;
Douglas Gregora5324162009-04-15 04:56:10 +00001523 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1524 Index, StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001525 true, false))
1526 return true;
1527 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001528
1529 // Find the position of the next field to be initialized in this
1530 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001531 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001532 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001533
1534 // If this the first designator, our caller will continue checking
1535 // the rest of this struct/class/union subobject.
1536 if (IsFirstDesignator) {
1537 if (NextField)
1538 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001539 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001540 return false;
1541 }
1542
Douglas Gregor17bd0942009-01-28 23:36:17 +00001543 if (!FinishSubobjectInit)
1544 return false;
1545
Douglas Gregord5846a12009-04-15 06:41:24 +00001546 // We've already initialized something in the union; we're done.
1547 if (RT->getDecl()->isUnion())
1548 return hadError;
1549
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001550 // Check the remaining fields within this class/struct/union subobject.
1551 bool prevHadError = hadError;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001552 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1553 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001554 return hadError && !prevHadError;
1555 }
1556
1557 // C99 6.7.8p6:
1558 //
1559 // If a designator has the form
1560 //
1561 // [ constant-expression ]
1562 //
1563 // then the current object (defined below) shall have array
1564 // type and the expression shall be an integer constant
1565 // expression. If the array is of unknown size, any
1566 // nonnegative value is valid.
1567 //
1568 // Additionally, cope with the GNU extension that permits
1569 // designators of the form
1570 //
1571 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001572 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001573 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001574 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001575 << CurrentObjectType;
1576 ++Index;
1577 return true;
1578 }
1579
1580 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001581 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1582 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001583 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001584 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001585 DesignatedEndIndex = DesignatedStartIndex;
1586 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001587 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001588
Mike Stump11289f42009-09-09 15:08:12 +00001589
1590 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001591 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001592 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001593 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001594 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001595
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001596 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001597 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001598 }
1599
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001600 if (isa<ConstantArrayType>(AT)) {
1601 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001602 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1603 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1604 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1605 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1606 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001607 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001608 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001609 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001610 << IndexExpr->getSourceRange();
1611 ++Index;
1612 return true;
1613 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001614 } else {
1615 // Make sure the bit-widths and signedness match.
1616 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1617 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001618 else if (DesignatedStartIndex.getBitWidth() <
1619 DesignatedEndIndex.getBitWidth())
Douglas Gregor17bd0942009-01-28 23:36:17 +00001620 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1621 DesignatedStartIndex.setIsUnsigned(true);
1622 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001623 }
Mike Stump11289f42009-09-09 15:08:12 +00001624
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001625 // Make sure that our non-designated initializer list has space
1626 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001627 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001628 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001629 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001630
Douglas Gregor17bd0942009-01-28 23:36:17 +00001631 // Repeatedly perform subobject initializations in the range
1632 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001633
Douglas Gregor17bd0942009-01-28 23:36:17 +00001634 // Move to the next designator
1635 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1636 unsigned OldIndex = Index;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001637 while (DesignatedStartIndex <= DesignatedEndIndex) {
1638 // Recurse to check later designated subobjects.
1639 QualType ElementType = AT->getElementType();
1640 Index = OldIndex;
Douglas Gregora5324162009-04-15 04:56:10 +00001641 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1642 Index, StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001643 (DesignatedStartIndex == DesignatedEndIndex),
1644 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001645 return true;
1646
1647 // Move to the next index in the array that we'll be initializing.
1648 ++DesignatedStartIndex;
1649 ElementIndex = DesignatedStartIndex.getZExtValue();
1650 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001651
1652 // If this the first designator, our caller will continue checking
1653 // the rest of this array subobject.
1654 if (IsFirstDesignator) {
1655 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001656 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001657 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001658 return false;
1659 }
Mike Stump11289f42009-09-09 15:08:12 +00001660
Douglas Gregor17bd0942009-01-28 23:36:17 +00001661 if (!FinishSubobjectInit)
1662 return false;
1663
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001664 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001665 bool prevHadError = hadError;
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001666 CheckArrayType(0, IList, CurrentObjectType, DesignatedStartIndex,
1667 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001668 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001669 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001670}
1671
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001672// Get the structured initializer list for a subobject of type
1673// @p CurrentObjectType.
1674InitListExpr *
1675InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1676 QualType CurrentObjectType,
1677 InitListExpr *StructuredList,
1678 unsigned StructuredIndex,
1679 SourceRange InitRange) {
1680 Expr *ExistingInit = 0;
1681 if (!StructuredList)
1682 ExistingInit = SyntacticToSemantic[IList];
1683 else if (StructuredIndex < StructuredList->getNumInits())
1684 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001685
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001686 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1687 return Result;
1688
1689 if (ExistingInit) {
1690 // We are creating an initializer list that initializes the
1691 // subobjects of the current object, but there was already an
1692 // initialization that completely initialized the current
1693 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001694 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001695 // struct X { int a, b; };
1696 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001697 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001698 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1699 // designated initializer re-initializes the whole
1700 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001701 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001702 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001703 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001704 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001705 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001706 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001707 << ExistingInit->getSourceRange();
1708 }
1709
Mike Stump11289f42009-09-09 15:08:12 +00001710 InitListExpr *Result
1711 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001712 InitRange.getEnd());
1713
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001714 Result->setType(CurrentObjectType);
1715
Douglas Gregor6d00c992009-03-20 23:58:33 +00001716 // Pre-allocate storage for the structured initializer list.
1717 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001718 unsigned NumInits = 0;
1719 if (!StructuredList)
1720 NumInits = IList->getNumInits();
1721 else if (Index < IList->getNumInits()) {
1722 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1723 NumInits = SubList->getNumInits();
1724 }
1725
Mike Stump11289f42009-09-09 15:08:12 +00001726 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001727 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1728 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1729 NumElements = CAType->getSize().getZExtValue();
1730 // Simple heuristic so that we don't allocate a very large
1731 // initializer with many empty entries at the end.
Douglas Gregor221c9a52009-03-21 18:13:52 +00001732 if (NumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001733 NumElements = 0;
1734 }
John McCall9dd450b2009-09-21 23:43:11 +00001735 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001736 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001737 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001738 RecordDecl *RDecl = RType->getDecl();
1739 if (RDecl->isUnion())
1740 NumElements = 1;
1741 else
Mike Stump11289f42009-09-09 15:08:12 +00001742 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001743 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001744 }
1745
Douglas Gregor221c9a52009-03-21 18:13:52 +00001746 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001747 NumElements = IList->getNumInits();
1748
1749 Result->reserveInits(NumElements);
1750
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001751 // Link this new initializer list into the structured initializer
1752 // lists.
1753 if (StructuredList)
1754 StructuredList->updateInit(StructuredIndex, Result);
1755 else {
1756 Result->setSyntacticForm(IList);
1757 SyntacticToSemantic[IList] = Result;
1758 }
1759
1760 return Result;
1761}
1762
1763/// Update the initializer at index @p StructuredIndex within the
1764/// structured initializer list to the value @p expr.
1765void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1766 unsigned &StructuredIndex,
1767 Expr *expr) {
1768 // No structured initializer list to update
1769 if (!StructuredList)
1770 return;
1771
1772 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1773 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001774 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001775 diag::warn_initializer_overrides)
1776 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001777 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001778 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001779 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001780 << PrevInit->getSourceRange();
1781 }
Mike Stump11289f42009-09-09 15:08:12 +00001782
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001783 ++StructuredIndex;
1784}
1785
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001786/// Check that the given Index expression is a valid array designator
1787/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001788/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001789/// and produces a reasonable diagnostic if there is a
1790/// failure. Returns true if there was an error, false otherwise. If
1791/// everything went okay, Value will receive the value of the constant
1792/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001793static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001794CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001795 SourceLocation Loc = Index->getSourceRange().getBegin();
1796
1797 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001798 if (S.VerifyIntegerConstantExpression(Index, &Value))
1799 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001800
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001801 if (Value.isSigned() && Value.isNegative())
1802 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001803 << Value.toString(10) << Index->getSourceRange();
1804
Douglas Gregor51650d32009-01-23 21:04:18 +00001805 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001806 return false;
1807}
1808
1809Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1810 SourceLocation Loc,
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00001811 bool GNUSyntax,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001812 OwningExprResult Init) {
1813 typedef DesignatedInitExpr::Designator ASTDesignator;
1814
1815 bool Invalid = false;
1816 llvm::SmallVector<ASTDesignator, 32> Designators;
1817 llvm::SmallVector<Expr *, 32> InitExpressions;
1818
1819 // Build designators and check array designator expressions.
1820 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1821 const Designator &D = Desig.getDesignator(Idx);
1822 switch (D.getKind()) {
1823 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001824 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001825 D.getFieldLoc()));
1826 break;
1827
1828 case Designator::ArrayDesignator: {
1829 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1830 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001831 if (!Index->isTypeDependent() &&
1832 !Index->isValueDependent() &&
1833 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001834 Invalid = true;
1835 else {
1836 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001837 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001838 D.getRBracketLoc()));
1839 InitExpressions.push_back(Index);
1840 }
1841 break;
1842 }
1843
1844 case Designator::ArrayRangeDesignator: {
1845 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1846 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1847 llvm::APSInt StartValue;
1848 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001849 bool StartDependent = StartIndex->isTypeDependent() ||
1850 StartIndex->isValueDependent();
1851 bool EndDependent = EndIndex->isTypeDependent() ||
1852 EndIndex->isValueDependent();
1853 if ((!StartDependent &&
1854 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1855 (!EndDependent &&
1856 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001857 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001858 else {
1859 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001860 if (StartDependent || EndDependent) {
1861 // Nothing to compute.
1862 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregor7a95b082009-01-23 22:22:29 +00001863 EndValue.extend(StartValue.getBitWidth());
1864 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1865 StartValue.extend(EndValue.getBitWidth());
1866
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001867 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001868 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001869 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001870 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1871 Invalid = true;
1872 } else {
1873 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001874 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001875 D.getEllipsisLoc(),
1876 D.getRBracketLoc()));
1877 InitExpressions.push_back(StartIndex);
1878 InitExpressions.push_back(EndIndex);
1879 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001880 }
1881 break;
1882 }
1883 }
1884 }
1885
1886 if (Invalid || Init.isInvalid())
1887 return ExprError();
1888
1889 // Clear out the expressions within the designation.
1890 Desig.ClearExprs(*this);
1891
1892 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001893 = DesignatedInitExpr::Create(Context,
1894 Designators.data(), Designators.size(),
1895 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001896 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001897 return Owned(DIE);
1898}
Douglas Gregor85df8d82009-01-29 00:45:39 +00001899
Douglas Gregor723796a2009-12-16 06:35:08 +00001900bool Sema::CheckInitList(const InitializedEntity &Entity,
1901 InitListExpr *&InitList, QualType &DeclType) {
1902 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00001903 if (!CheckInitList.HadError())
1904 InitList = CheckInitList.getFullyStructuredList();
1905
1906 return CheckInitList.HadError();
1907}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00001908
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001909//===----------------------------------------------------------------------===//
1910// Initialization entity
1911//===----------------------------------------------------------------------===//
1912
Douglas Gregor723796a2009-12-16 06:35:08 +00001913InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1914 const InitializedEntity &Parent)
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001915 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00001916{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001917 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1918 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001919 Type = AT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001920 } else {
1921 Kind = EK_VectorElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001922 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001923 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001924}
1925
1926InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1927 CXXBaseSpecifier *Base)
1928{
1929 InitializedEntity Result;
1930 Result.Kind = EK_Base;
1931 Result.Base = Base;
Douglas Gregor1b303932009-12-22 15:35:07 +00001932 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001933 return Result;
1934}
1935
Douglas Gregor85dabae2009-12-16 01:38:02 +00001936DeclarationName InitializedEntity::getName() const {
1937 switch (getKind()) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00001938 case EK_Parameter:
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00001939 if (!VariableOrMember)
1940 return DeclarationName();
1941 // Fall through
1942
1943 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001944 case EK_Member:
1945 return VariableOrMember->getDeclName();
1946
1947 case EK_Result:
1948 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00001949 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001950 case EK_Temporary:
1951 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001952 case EK_ArrayElement:
1953 case EK_VectorElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001954 return DeclarationName();
1955 }
1956
1957 // Silence GCC warning
1958 return DeclarationName();
1959}
1960
Douglas Gregora4b592a2009-12-19 03:01:41 +00001961DeclaratorDecl *InitializedEntity::getDecl() const {
1962 switch (getKind()) {
1963 case EK_Variable:
1964 case EK_Parameter:
1965 case EK_Member:
1966 return VariableOrMember;
1967
1968 case EK_Result:
1969 case EK_Exception:
1970 case EK_New:
1971 case EK_Temporary:
1972 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001973 case EK_ArrayElement:
1974 case EK_VectorElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00001975 return 0;
1976 }
1977
1978 // Silence GCC warning
1979 return 0;
1980}
1981
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001982//===----------------------------------------------------------------------===//
1983// Initialization sequence
1984//===----------------------------------------------------------------------===//
1985
1986void InitializationSequence::Step::Destroy() {
1987 switch (Kind) {
1988 case SK_ResolveAddressOfOverloadedFunction:
1989 case SK_CastDerivedToBaseRValue:
1990 case SK_CastDerivedToBaseLValue:
1991 case SK_BindReference:
1992 case SK_BindReferenceToTemporary:
1993 case SK_UserConversion:
1994 case SK_QualificationConversionRValue:
1995 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00001996 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00001997 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00001998 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00001999 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002000 case SK_StringInit:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002001 break;
2002
2003 case SK_ConversionSequence:
2004 delete ICS;
2005 }
2006}
2007
2008void InitializationSequence::AddAddressOverloadResolutionStep(
2009 FunctionDecl *Function) {
2010 Step S;
2011 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2012 S.Type = Function->getType();
2013 S.Function = Function;
2014 Steps.push_back(S);
2015}
2016
2017void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2018 bool IsLValue) {
2019 Step S;
2020 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
2021 S.Type = BaseType;
2022 Steps.push_back(S);
2023}
2024
2025void InitializationSequence::AddReferenceBindingStep(QualType T,
2026 bool BindingTemporary) {
2027 Step S;
2028 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2029 S.Type = T;
2030 Steps.push_back(S);
2031}
2032
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002033void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2034 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002035 Step S;
2036 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002037 S.Type = T;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002038 S.Function = Function;
2039 Steps.push_back(S);
2040}
2041
2042void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2043 bool IsLValue) {
2044 Step S;
2045 S.Kind = IsLValue? SK_QualificationConversionLValue
2046 : SK_QualificationConversionRValue;
2047 S.Type = Ty;
2048 Steps.push_back(S);
2049}
2050
2051void InitializationSequence::AddConversionSequenceStep(
2052 const ImplicitConversionSequence &ICS,
2053 QualType T) {
2054 Step S;
2055 S.Kind = SK_ConversionSequence;
2056 S.Type = T;
2057 S.ICS = new ImplicitConversionSequence(ICS);
2058 Steps.push_back(S);
2059}
2060
Douglas Gregor51e77d52009-12-10 17:56:55 +00002061void InitializationSequence::AddListInitializationStep(QualType T) {
2062 Step S;
2063 S.Kind = SK_ListInitialization;
2064 S.Type = T;
2065 Steps.push_back(S);
2066}
2067
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002068void
2069InitializationSequence::AddConstructorInitializationStep(
2070 CXXConstructorDecl *Constructor,
2071 QualType T) {
2072 Step S;
2073 S.Kind = SK_ConstructorInitialization;
2074 S.Type = T;
2075 S.Function = Constructor;
2076 Steps.push_back(S);
2077}
2078
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002079void InitializationSequence::AddZeroInitializationStep(QualType T) {
2080 Step S;
2081 S.Kind = SK_ZeroInitialization;
2082 S.Type = T;
2083 Steps.push_back(S);
2084}
2085
Douglas Gregore1314a62009-12-18 05:02:21 +00002086void InitializationSequence::AddCAssignmentStep(QualType T) {
2087 Step S;
2088 S.Kind = SK_CAssignment;
2089 S.Type = T;
2090 Steps.push_back(S);
2091}
2092
Eli Friedman78275202009-12-19 08:11:05 +00002093void InitializationSequence::AddStringInitStep(QualType T) {
2094 Step S;
2095 S.Kind = SK_StringInit;
2096 S.Type = T;
2097 Steps.push_back(S);
2098}
2099
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002100void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2101 OverloadingResult Result) {
2102 SequenceKind = FailedSequence;
2103 this->Failure = Failure;
2104 this->FailedOverloadResult = Result;
2105}
2106
2107//===----------------------------------------------------------------------===//
2108// Attempt initialization
2109//===----------------------------------------------------------------------===//
2110
2111/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregor51e77d52009-12-10 17:56:55 +00002112static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002113 const InitializedEntity &Entity,
2114 const InitializationKind &Kind,
2115 InitListExpr *InitList,
2116 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00002117 // FIXME: We only perform rudimentary checking of list
2118 // initializations at this point, then assume that any list
2119 // initialization of an array, aggregate, or scalar will be
2120 // well-formed. We we actually "perform" list initialization, we'll
2121 // do all of the necessary checking. C++0x initializer lists will
2122 // force us to perform more checking here.
2123 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2124
Douglas Gregor1b303932009-12-22 15:35:07 +00002125 QualType DestType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00002126
2127 // C++ [dcl.init]p13:
2128 // If T is a scalar type, then a declaration of the form
2129 //
2130 // T x = { a };
2131 //
2132 // is equivalent to
2133 //
2134 // T x = a;
2135 if (DestType->isScalarType()) {
2136 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2137 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2138 return;
2139 }
2140
2141 // Assume scalar initialization from a single value works.
2142 } else if (DestType->isAggregateType()) {
2143 // Assume aggregate initialization works.
2144 } else if (DestType->isVectorType()) {
2145 // Assume vector initialization works.
2146 } else if (DestType->isReferenceType()) {
2147 // FIXME: C++0x defines behavior for this.
2148 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2149 return;
2150 } else if (DestType->isRecordType()) {
2151 // FIXME: C++0x defines behavior for this
2152 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2153 }
2154
2155 // Add a general "list initialization" step.
2156 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002157}
2158
2159/// \brief Try a reference initialization that involves calling a conversion
2160/// function.
2161///
2162/// FIXME: look intos DRs 656, 896
2163static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2164 const InitializedEntity &Entity,
2165 const InitializationKind &Kind,
2166 Expr *Initializer,
2167 bool AllowRValues,
2168 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002169 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002170 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2171 QualType T1 = cv1T1.getUnqualifiedType();
2172 QualType cv2T2 = Initializer->getType();
2173 QualType T2 = cv2T2.getUnqualifiedType();
2174
2175 bool DerivedToBase;
2176 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2177 T1, T2, DerivedToBase) &&
2178 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002179 (void)DerivedToBase;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002180
2181 // Build the candidate set directly in the initialization sequence
2182 // structure, so that it will persist if we fail.
2183 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2184 CandidateSet.clear();
2185
2186 // Determine whether we are allowed to call explicit constructors or
2187 // explicit conversion operators.
2188 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2189
2190 const RecordType *T1RecordType = 0;
2191 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2192 // The type we're converting to is a class type. Enumerate its constructors
2193 // to see if there is a suitable conversion.
2194 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2195
2196 DeclarationName ConstructorName
2197 = S.Context.DeclarationNames.getCXXConstructorName(
2198 S.Context.getCanonicalType(T1).getUnqualifiedType());
2199 DeclContext::lookup_iterator Con, ConEnd;
2200 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2201 Con != ConEnd; ++Con) {
2202 // Find the constructor (which may be a template).
2203 CXXConstructorDecl *Constructor = 0;
2204 FunctionTemplateDecl *ConstructorTmpl
2205 = dyn_cast<FunctionTemplateDecl>(*Con);
2206 if (ConstructorTmpl)
2207 Constructor = cast<CXXConstructorDecl>(
2208 ConstructorTmpl->getTemplatedDecl());
2209 else
2210 Constructor = cast<CXXConstructorDecl>(*Con);
2211
2212 if (!Constructor->isInvalidDecl() &&
2213 Constructor->isConvertingConstructor(AllowExplicit)) {
2214 if (ConstructorTmpl)
2215 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2216 &Initializer, 1, CandidateSet);
2217 else
2218 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2219 }
2220 }
2221 }
2222
2223 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2224 // The type we're converting from is a class type, enumerate its conversion
2225 // functions.
2226 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2227
2228 // Determine the type we are converting to. If we are allowed to
2229 // convert to an rvalue, take the type that the destination type
2230 // refers to.
2231 QualType ToType = AllowRValues? cv1T1 : DestType;
2232
John McCallad371252010-01-20 00:46:10 +00002233 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002234 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002235 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2236 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002237 NamedDecl *D = *I;
2238 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2239 if (isa<UsingShadowDecl>(D))
2240 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2241
2242 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2243 CXXConversionDecl *Conv;
2244 if (ConvTemplate)
2245 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2246 else
2247 Conv = cast<CXXConversionDecl>(*I);
2248
2249 // If the conversion function doesn't return a reference type,
2250 // it can't be considered for this conversion unless we're allowed to
2251 // consider rvalues.
2252 // FIXME: Do we need to make sure that we only consider conversion
2253 // candidates with reference-compatible results? That might be needed to
2254 // break recursion.
2255 if ((AllowExplicit || !Conv->isExplicit()) &&
2256 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2257 if (ConvTemplate)
2258 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2259 ToType, CandidateSet);
2260 else
2261 S.AddConversionCandidate(Conv, ActingDC, Initializer, cv1T1,
2262 CandidateSet);
2263 }
2264 }
2265 }
2266
2267 SourceLocation DeclLoc = Initializer->getLocStart();
2268
2269 // Perform overload resolution. If it fails, return the failed result.
2270 OverloadCandidateSet::iterator Best;
2271 if (OverloadingResult Result
2272 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2273 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002274
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002275 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002276
2277 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002278 if (isa<CXXConversionDecl>(Function))
2279 T2 = Function->getResultType();
2280 else
2281 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002282
2283 // Add the user-defined conversion step.
2284 Sequence.AddUserConversionStep(Function, T2.getNonReferenceType());
2285
2286 // Determine whether we need to perform derived-to-base or
2287 // cv-qualification adjustments.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002288 bool NewDerivedToBase = false;
2289 Sema::ReferenceCompareResult NewRefRelationship
2290 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2291 NewDerivedToBase);
2292 assert(NewRefRelationship != Sema::Ref_Incompatible &&
2293 "Overload resolution picked a bad conversion function");
2294 (void)NewRefRelationship;
2295 if (NewDerivedToBase)
2296 Sequence.AddDerivedToBaseCastStep(
2297 S.Context.getQualifiedType(T1,
2298 T2.getNonReferenceType().getQualifiers()),
2299 /*isLValue=*/true);
2300
2301 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2302 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2303
2304 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2305 return OR_Success;
2306}
2307
2308/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2309static void TryReferenceInitialization(Sema &S,
2310 const InitializedEntity &Entity,
2311 const InitializationKind &Kind,
2312 Expr *Initializer,
2313 InitializationSequence &Sequence) {
2314 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2315
Douglas Gregor1b303932009-12-22 15:35:07 +00002316 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002317 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002318 Qualifiers T1Quals;
2319 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002320 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002321 Qualifiers T2Quals;
2322 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002323 SourceLocation DeclLoc = Initializer->getLocStart();
2324
2325 // If the initializer is the address of an overloaded function, try
2326 // to resolve the overloaded function. If all goes well, T2 is the
2327 // type of the resulting function.
2328 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2329 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2330 T1,
2331 false);
2332 if (!Fn) {
2333 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2334 return;
2335 }
2336
2337 Sequence.AddAddressOverloadResolutionStep(Fn);
2338 cv2T2 = Fn->getType();
2339 T2 = cv2T2.getUnqualifiedType();
2340 }
2341
2342 // FIXME: Rvalue references
2343 bool ForceRValue = false;
2344
2345 // Compute some basic properties of the types and the initializer.
2346 bool isLValueRef = DestType->isLValueReferenceType();
2347 bool isRValueRef = !isLValueRef;
2348 bool DerivedToBase = false;
2349 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2350 Initializer->isLvalue(S.Context);
2351 Sema::ReferenceCompareResult RefRelationship
2352 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2353
2354 // C++0x [dcl.init.ref]p5:
2355 // A reference to type "cv1 T1" is initialized by an expression of type
2356 // "cv2 T2" as follows:
2357 //
2358 // - If the reference is an lvalue reference and the initializer
2359 // expression
2360 OverloadingResult ConvOvlResult = OR_Success;
2361 if (isLValueRef) {
2362 if (InitLvalue == Expr::LV_Valid &&
2363 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2364 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2365 // reference-compatible with "cv2 T2," or
2366 //
2367 // Per C++ [over.best.ics]p2, we ignore whether the lvalue is a
2368 // bit-field when we're determining whether the reference initialization
2369 // can occur. This property will be checked by PerformInitialization.
2370 if (DerivedToBase)
2371 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002372 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002373 /*isLValue=*/true);
Chandler Carruth04bdce62010-01-12 20:32:25 +00002374 if (T1Quals != T2Quals)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002375 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
2376 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/false);
2377 return;
2378 }
2379
2380 // - has a class type (i.e., T2 is a class type), where T1 is not
2381 // reference-related to T2, and can be implicitly converted to an
2382 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2383 // with "cv3 T3" (this conversion is selected by enumerating the
2384 // applicable conversion functions (13.3.1.6) and choosing the best
2385 // one through overload resolution (13.3)),
2386 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2387 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2388 Initializer,
2389 /*AllowRValues=*/false,
2390 Sequence);
2391 if (ConvOvlResult == OR_Success)
2392 return;
John McCall0d1da222010-01-12 00:44:57 +00002393 if (ConvOvlResult != OR_No_Viable_Function) {
2394 Sequence.SetOverloadFailure(
2395 InitializationSequence::FK_ReferenceInitOverloadFailed,
2396 ConvOvlResult);
2397 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002398 }
2399 }
2400
2401 // - Otherwise, the reference shall be an lvalue reference to a
2402 // non-volatile const type (i.e., cv1 shall be const), or the reference
2403 // shall be an rvalue reference and the initializer expression shall
2404 // be an rvalue.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002405 if (!((isLValueRef && T1Quals.hasConst()) ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002406 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2407 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2408 Sequence.SetOverloadFailure(
2409 InitializationSequence::FK_ReferenceInitOverloadFailed,
2410 ConvOvlResult);
2411 else if (isLValueRef)
2412 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2413 ? (RefRelationship == Sema::Ref_Related
2414 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2415 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2416 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2417 else
2418 Sequence.SetFailed(
2419 InitializationSequence::FK_RValueReferenceBindingToLValue);
2420
2421 return;
2422 }
2423
2424 // - If T1 and T2 are class types and
2425 if (T1->isRecordType() && T2->isRecordType()) {
2426 // - the initializer expression is an rvalue and "cv1 T1" is
2427 // reference-compatible with "cv2 T2", or
2428 if (InitLvalue != Expr::LV_Valid &&
2429 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2430 if (DerivedToBase)
2431 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002432 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002433 /*isLValue=*/false);
Chandler Carruth04bdce62010-01-12 20:32:25 +00002434 if (T1Quals != T2Quals)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002435 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2436 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2437 return;
2438 }
2439
2440 // - T1 is not reference-related to T2 and the initializer expression
2441 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2442 // conversion is selected by enumerating the applicable conversion
2443 // functions (13.3.1.6) and choosing the best one through overload
2444 // resolution (13.3)),
2445 if (RefRelationship == Sema::Ref_Incompatible) {
2446 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2447 Kind, Initializer,
2448 /*AllowRValues=*/true,
2449 Sequence);
2450 if (ConvOvlResult)
2451 Sequence.SetOverloadFailure(
2452 InitializationSequence::FK_ReferenceInitOverloadFailed,
2453 ConvOvlResult);
2454
2455 return;
2456 }
2457
2458 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2459 return;
2460 }
2461
2462 // - If the initializer expression is an rvalue, with T2 an array type,
2463 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2464 // is bound to the object represented by the rvalue (see 3.10).
2465 // FIXME: How can an array type be reference-compatible with anything?
2466 // Don't we mean the element types of T1 and T2?
2467
2468 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2469 // from the initializer expression using the rules for a non-reference
2470 // copy initialization (8.5). The reference is then bound to the
2471 // temporary. [...]
2472 // Determine whether we are allowed to call explicit constructors or
2473 // explicit conversion operators.
2474 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2475 ImplicitConversionSequence ICS
2476 = S.TryImplicitConversion(Initializer, cv1T1,
2477 /*SuppressUserConversions=*/false, AllowExplicit,
2478 /*ForceRValue=*/false,
2479 /*FIXME:InOverloadResolution=*/false,
2480 /*UserCast=*/Kind.isExplicitCast());
2481
John McCall0d1da222010-01-12 00:44:57 +00002482 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002483 // FIXME: Use the conversion function set stored in ICS to turn
2484 // this into an overloading ambiguity diagnostic. However, we need
2485 // to keep that set as an OverloadCandidateSet rather than as some
2486 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002487 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2488 Sequence.SetOverloadFailure(
2489 InitializationSequence::FK_ReferenceInitOverloadFailed,
2490 ConvOvlResult);
2491 else
2492 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002493 return;
2494 }
2495
2496 // [...] If T1 is reference-related to T2, cv1 must be the
2497 // same cv-qualification as, or greater cv-qualification
2498 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002499 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2500 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002501 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00002502 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002503 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2504 return;
2505 }
2506
2507 // Perform the actual conversion.
2508 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2509 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2510 return;
2511}
2512
2513/// \brief Attempt character array initialization from a string literal
2514/// (C++ [dcl.init.string], C99 6.7.8).
2515static void TryStringLiteralInitialization(Sema &S,
2516 const InitializedEntity &Entity,
2517 const InitializationKind &Kind,
2518 Expr *Initializer,
2519 InitializationSequence &Sequence) {
Eli Friedman78275202009-12-19 08:11:05 +00002520 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregor1b303932009-12-22 15:35:07 +00002521 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002522}
2523
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002524/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2525/// enumerates the constructors of the initialized entity and performs overload
2526/// resolution to select the best.
2527static void TryConstructorInitialization(Sema &S,
2528 const InitializedEntity &Entity,
2529 const InitializationKind &Kind,
2530 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002531 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002532 InitializationSequence &Sequence) {
Douglas Gregore1314a62009-12-18 05:02:21 +00002533 if (Kind.getKind() == InitializationKind::IK_Copy)
2534 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2535 else
2536 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002537
2538 // Build the candidate set directly in the initialization sequence
2539 // structure, so that it will persist if we fail.
2540 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2541 CandidateSet.clear();
2542
2543 // Determine whether we are allowed to call explicit constructors or
2544 // explicit conversion operators.
2545 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2546 Kind.getKind() == InitializationKind::IK_Value ||
2547 Kind.getKind() == InitializationKind::IK_Default);
2548
2549 // The type we're converting to is a class type. Enumerate its constructors
2550 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002551 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2552 assert(DestRecordType && "Constructor initialization requires record type");
2553 CXXRecordDecl *DestRecordDecl
2554 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2555
2556 DeclarationName ConstructorName
2557 = S.Context.DeclarationNames.getCXXConstructorName(
2558 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2559 DeclContext::lookup_iterator Con, ConEnd;
2560 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2561 Con != ConEnd; ++Con) {
2562 // Find the constructor (which may be a template).
2563 CXXConstructorDecl *Constructor = 0;
2564 FunctionTemplateDecl *ConstructorTmpl
2565 = dyn_cast<FunctionTemplateDecl>(*Con);
2566 if (ConstructorTmpl)
2567 Constructor = cast<CXXConstructorDecl>(
2568 ConstructorTmpl->getTemplatedDecl());
2569 else
2570 Constructor = cast<CXXConstructorDecl>(*Con);
2571
2572 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002573 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002574 if (ConstructorTmpl)
2575 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2576 Args, NumArgs, CandidateSet);
2577 else
2578 S.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2579 }
2580 }
2581
2582 SourceLocation DeclLoc = Kind.getLocation();
2583
2584 // Perform overload resolution. If it fails, return the failed result.
2585 OverloadCandidateSet::iterator Best;
2586 if (OverloadingResult Result
2587 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2588 Sequence.SetOverloadFailure(
2589 InitializationSequence::FK_ConstructorOverloadFailed,
2590 Result);
2591 return;
2592 }
2593
2594 // Add the constructor initialization step. Any cv-qualification conversion is
2595 // subsumed by the initialization.
Douglas Gregore1314a62009-12-18 05:02:21 +00002596 if (Kind.getKind() == InitializationKind::IK_Copy) {
2597 Sequence.AddUserConversionStep(Best->Function, DestType);
2598 } else {
2599 Sequence.AddConstructorInitializationStep(
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002600 cast<CXXConstructorDecl>(Best->Function),
Douglas Gregore1314a62009-12-18 05:02:21 +00002601 DestType);
2602 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002603}
2604
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002605/// \brief Attempt value initialization (C++ [dcl.init]p7).
2606static void TryValueInitialization(Sema &S,
2607 const InitializedEntity &Entity,
2608 const InitializationKind &Kind,
2609 InitializationSequence &Sequence) {
2610 // C++ [dcl.init]p5:
2611 //
2612 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00002613 QualType T = Entity.getType();
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002614
2615 // -- if T is an array type, then each element is value-initialized;
2616 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2617 T = AT->getElementType();
2618
2619 if (const RecordType *RT = T->getAs<RecordType>()) {
2620 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2621 // -- if T is a class type (clause 9) with a user-declared
2622 // constructor (12.1), then the default constructor for T is
2623 // called (and the initialization is ill-formed if T has no
2624 // accessible default constructor);
2625 //
2626 // FIXME: we really want to refer to a single subobject of the array,
2627 // but Entity doesn't have a way to capture that (yet).
2628 if (ClassDecl->hasUserDeclaredConstructor())
2629 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2630
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002631 // -- if T is a (possibly cv-qualified) non-union class type
2632 // without a user-provided constructor, then the object is
2633 // zero-initialized and, if T’s implicitly-declared default
2634 // constructor is non-trivial, that constructor is called.
2635 if ((ClassDecl->getTagKind() == TagDecl::TK_class ||
2636 ClassDecl->getTagKind() == TagDecl::TK_struct) &&
2637 !ClassDecl->hasTrivialConstructor()) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002638 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002639 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2640 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002641 }
2642 }
2643
Douglas Gregor1b303932009-12-22 15:35:07 +00002644 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002645 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2646}
2647
Douglas Gregor85dabae2009-12-16 01:38:02 +00002648/// \brief Attempt default initialization (C++ [dcl.init]p6).
2649static void TryDefaultInitialization(Sema &S,
2650 const InitializedEntity &Entity,
2651 const InitializationKind &Kind,
2652 InitializationSequence &Sequence) {
2653 assert(Kind.getKind() == InitializationKind::IK_Default);
2654
2655 // C++ [dcl.init]p6:
2656 // To default-initialize an object of type T means:
2657 // - if T is an array type, each element is default-initialized;
Douglas Gregor1b303932009-12-22 15:35:07 +00002658 QualType DestType = Entity.getType();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002659 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2660 DestType = Array->getElementType();
2661
2662 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2663 // constructor for T is called (and the initialization is ill-formed if
2664 // T has no accessible default constructor);
2665 if (DestType->isRecordType()) {
2666 // FIXME: If a program calls for the default initialization of an object of
2667 // a const-qualified type T, T shall be a class type with a user-provided
2668 // default constructor.
2669 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2670 Sequence);
2671 }
2672
2673 // - otherwise, no initialization is performed.
2674 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2675
2676 // If a program calls for the default initialization of an object of
2677 // a const-qualified type T, T shall be a class type with a user-provided
2678 // default constructor.
2679 if (DestType.isConstQualified())
2680 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2681}
2682
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002683/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2684/// which enumerates all conversion functions and performs overload resolution
2685/// to select the best.
2686static void TryUserDefinedConversion(Sema &S,
2687 const InitializedEntity &Entity,
2688 const InitializationKind &Kind,
2689 Expr *Initializer,
2690 InitializationSequence &Sequence) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002691 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2692
Douglas Gregor1b303932009-12-22 15:35:07 +00002693 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002694 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2695 QualType SourceType = Initializer->getType();
2696 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2697 "Must have a class type to perform a user-defined conversion");
2698
2699 // Build the candidate set directly in the initialization sequence
2700 // structure, so that it will persist if we fail.
2701 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2702 CandidateSet.clear();
2703
2704 // Determine whether we are allowed to call explicit constructors or
2705 // explicit conversion operators.
2706 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2707
2708 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2709 // The type we're converting to is a class type. Enumerate its constructors
2710 // to see if there is a suitable conversion.
2711 CXXRecordDecl *DestRecordDecl
2712 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2713
2714 DeclarationName ConstructorName
2715 = S.Context.DeclarationNames.getCXXConstructorName(
2716 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2717 DeclContext::lookup_iterator Con, ConEnd;
2718 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2719 Con != ConEnd; ++Con) {
2720 // Find the constructor (which may be a template).
2721 CXXConstructorDecl *Constructor = 0;
2722 FunctionTemplateDecl *ConstructorTmpl
2723 = dyn_cast<FunctionTemplateDecl>(*Con);
2724 if (ConstructorTmpl)
2725 Constructor = cast<CXXConstructorDecl>(
2726 ConstructorTmpl->getTemplatedDecl());
2727 else
2728 Constructor = cast<CXXConstructorDecl>(*Con);
2729
2730 if (!Constructor->isInvalidDecl() &&
2731 Constructor->isConvertingConstructor(AllowExplicit)) {
2732 if (ConstructorTmpl)
2733 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2734 &Initializer, 1, CandidateSet);
2735 else
2736 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2737 }
2738 }
2739 }
Eli Friedman78275202009-12-19 08:11:05 +00002740
2741 SourceLocation DeclLoc = Initializer->getLocStart();
2742
Douglas Gregor540c3b02009-12-14 17:27:33 +00002743 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2744 // The type we're converting from is a class type, enumerate its conversion
2745 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00002746
Eli Friedman4afe9a32009-12-20 22:12:03 +00002747 // We can only enumerate the conversion functions for a complete type; if
2748 // the type isn't complete, simply skip this step.
2749 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2750 CXXRecordDecl *SourceRecordDecl
2751 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002752
John McCallad371252010-01-20 00:46:10 +00002753 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00002754 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002755 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman4afe9a32009-12-20 22:12:03 +00002756 E = Conversions->end();
2757 I != E; ++I) {
2758 NamedDecl *D = *I;
2759 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2760 if (isa<UsingShadowDecl>(D))
2761 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2762
2763 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2764 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00002765 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00002766 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002767 else
Eli Friedman4afe9a32009-12-20 22:12:03 +00002768 Conv = cast<CXXConversionDecl>(*I);
2769
2770 if (AllowExplicit || !Conv->isExplicit()) {
2771 if (ConvTemplate)
2772 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC,
2773 Initializer, DestType,
2774 CandidateSet);
2775 else
2776 S.AddConversionCandidate(Conv, ActingDC, Initializer, DestType,
2777 CandidateSet);
2778 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002779 }
2780 }
2781 }
2782
Douglas Gregor540c3b02009-12-14 17:27:33 +00002783 // Perform overload resolution. If it fails, return the failed result.
2784 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00002785 if (OverloadingResult Result
Douglas Gregor540c3b02009-12-14 17:27:33 +00002786 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2787 Sequence.SetOverloadFailure(
2788 InitializationSequence::FK_UserConversionOverloadFailed,
2789 Result);
2790 return;
2791 }
John McCall0d1da222010-01-12 00:44:57 +00002792
Douglas Gregor540c3b02009-12-14 17:27:33 +00002793 FunctionDecl *Function = Best->Function;
2794
2795 if (isa<CXXConstructorDecl>(Function)) {
2796 // Add the user-defined conversion step. Any cv-qualification conversion is
2797 // subsumed by the initialization.
2798 Sequence.AddUserConversionStep(Function, DestType);
2799 return;
2800 }
2801
2802 // Add the user-defined conversion step that calls the conversion function.
2803 QualType ConvType = Function->getResultType().getNonReferenceType();
2804 Sequence.AddUserConversionStep(Function, ConvType);
2805
2806 // If the conversion following the call to the conversion function is
2807 // interesting, add it as a separate step.
2808 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2809 Best->FinalConversion.Third) {
2810 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00002811 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002812 ICS.Standard = Best->FinalConversion;
2813 Sequence.AddConversionSequenceStep(ICS, DestType);
2814 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002815}
2816
2817/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2818/// non-class type to another.
2819static void TryImplicitConversion(Sema &S,
2820 const InitializedEntity &Entity,
2821 const InitializationKind &Kind,
2822 Expr *Initializer,
2823 InitializationSequence &Sequence) {
2824 ImplicitConversionSequence ICS
Douglas Gregor1b303932009-12-22 15:35:07 +00002825 = S.TryImplicitConversion(Initializer, Entity.getType(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002826 /*SuppressUserConversions=*/true,
2827 /*AllowExplicit=*/false,
2828 /*ForceRValue=*/false,
2829 /*FIXME:InOverloadResolution=*/false,
2830 /*UserCast=*/Kind.isExplicitCast());
2831
John McCall0d1da222010-01-12 00:44:57 +00002832 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002833 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2834 return;
2835 }
2836
Douglas Gregor1b303932009-12-22 15:35:07 +00002837 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002838}
2839
2840InitializationSequence::InitializationSequence(Sema &S,
2841 const InitializedEntity &Entity,
2842 const InitializationKind &Kind,
2843 Expr **Args,
2844 unsigned NumArgs) {
2845 ASTContext &Context = S.Context;
2846
2847 // C++0x [dcl.init]p16:
2848 // The semantics of initializers are as follows. The destination type is
2849 // the type of the object or reference being initialized and the source
2850 // type is the type of the initializer expression. The source type is not
2851 // defined when the initializer is a braced-init-list or when it is a
2852 // parenthesized list of expressions.
Douglas Gregor1b303932009-12-22 15:35:07 +00002853 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002854
2855 if (DestType->isDependentType() ||
2856 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2857 SequenceKind = DependentSequence;
2858 return;
2859 }
2860
2861 QualType SourceType;
2862 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00002863 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002864 Initializer = Args[0];
2865 if (!isa<InitListExpr>(Initializer))
2866 SourceType = Initializer->getType();
2867 }
2868
2869 // - If the initializer is a braced-init-list, the object is
2870 // list-initialized (8.5.4).
2871 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2872 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00002873 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002874 }
2875
2876 // - If the destination type is a reference type, see 8.5.3.
2877 if (DestType->isReferenceType()) {
2878 // C++0x [dcl.init.ref]p1:
2879 // A variable declared to be a T& or T&&, that is, "reference to type T"
2880 // (8.3.2), shall be initialized by an object, or function, of type T or
2881 // by an object that can be converted into a T.
2882 // (Therefore, multiple arguments are not permitted.)
2883 if (NumArgs != 1)
2884 SetFailed(FK_TooManyInitsForReference);
2885 else
2886 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2887 return;
2888 }
2889
2890 // - If the destination type is an array of characters, an array of
2891 // char16_t, an array of char32_t, or an array of wchar_t, and the
2892 // initializer is a string literal, see 8.5.2.
2893 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2894 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2895 return;
2896 }
2897
2898 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002899 if (Kind.getKind() == InitializationKind::IK_Value ||
2900 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002901 TryValueInitialization(S, Entity, Kind, *this);
2902 return;
2903 }
2904
Douglas Gregor85dabae2009-12-16 01:38:02 +00002905 // Handle default initialization.
2906 if (Kind.getKind() == InitializationKind::IK_Default){
2907 TryDefaultInitialization(S, Entity, Kind, *this);
2908 return;
2909 }
Douglas Gregore1314a62009-12-18 05:02:21 +00002910
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002911 // - Otherwise, if the destination type is an array, the program is
2912 // ill-formed.
2913 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2914 if (AT->getElementType()->isAnyCharacterType())
2915 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2916 else
2917 SetFailed(FK_ArrayNeedsInitList);
2918
2919 return;
2920 }
Eli Friedman78275202009-12-19 08:11:05 +00002921
2922 // Handle initialization in C
2923 if (!S.getLangOptions().CPlusPlus) {
2924 setSequenceKind(CAssignment);
2925 AddCAssignmentStep(DestType);
2926 return;
2927 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002928
2929 // - If the destination type is a (possibly cv-qualified) class type:
2930 if (DestType->isRecordType()) {
2931 // - If the initialization is direct-initialization, or if it is
2932 // copy-initialization where the cv-unqualified version of the
2933 // source type is the same class as, or a derived class of, the
2934 // class of the destination, constructors are considered. [...]
2935 if (Kind.getKind() == InitializationKind::IK_Direct ||
2936 (Kind.getKind() == InitializationKind::IK_Copy &&
2937 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2938 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002939 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregor1b303932009-12-22 15:35:07 +00002940 Entity.getType(), *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002941 // - Otherwise (i.e., for the remaining copy-initialization cases),
2942 // user-defined conversion sequences that can convert from the source
2943 // type to the destination type or (when a conversion function is
2944 // used) to a derived class thereof are enumerated as described in
2945 // 13.3.1.4, and the best one is chosen through overload resolution
2946 // (13.3).
2947 else
2948 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2949 return;
2950 }
2951
Douglas Gregor85dabae2009-12-16 01:38:02 +00002952 if (NumArgs > 1) {
2953 SetFailed(FK_TooManyInitsForScalar);
2954 return;
2955 }
2956 assert(NumArgs == 1 && "Zero-argument case handled above");
2957
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002958 // - Otherwise, if the source type is a (possibly cv-qualified) class
2959 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002960 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002961 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2962 return;
2963 }
2964
2965 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00002966 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002967 // conversions (Clause 4) will be used, if necessary, to convert the
2968 // initializer expression to the cv-unqualified version of the
2969 // destination type; no user-defined conversions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002970 setSequenceKind(StandardConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002971 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
2972}
2973
2974InitializationSequence::~InitializationSequence() {
2975 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
2976 StepEnd = Steps.end();
2977 Step != StepEnd; ++Step)
2978 Step->Destroy();
2979}
2980
2981//===----------------------------------------------------------------------===//
2982// Perform initialization
2983//===----------------------------------------------------------------------===//
Douglas Gregore1314a62009-12-18 05:02:21 +00002984static Sema::AssignmentAction
2985getAssignmentAction(const InitializedEntity &Entity) {
2986 switch(Entity.getKind()) {
2987 case InitializedEntity::EK_Variable:
2988 case InitializedEntity::EK_New:
2989 return Sema::AA_Initializing;
2990
2991 case InitializedEntity::EK_Parameter:
2992 // FIXME: Can we tell when we're sending vs. passing?
2993 return Sema::AA_Passing;
2994
2995 case InitializedEntity::EK_Result:
2996 return Sema::AA_Returning;
2997
2998 case InitializedEntity::EK_Exception:
2999 case InitializedEntity::EK_Base:
3000 llvm_unreachable("No assignment action for C++-specific initialization");
3001 break;
3002
3003 case InitializedEntity::EK_Temporary:
3004 // FIXME: Can we tell apart casting vs. converting?
3005 return Sema::AA_Casting;
3006
3007 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003008 case InitializedEntity::EK_ArrayElement:
3009 case InitializedEntity::EK_VectorElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003010 return Sema::AA_Initializing;
3011 }
3012
3013 return Sema::AA_Converting;
3014}
3015
3016static bool shouldBindAsTemporary(const InitializedEntity &Entity,
3017 bool IsCopy) {
3018 switch (Entity.getKind()) {
3019 case InitializedEntity::EK_Result:
3020 case InitializedEntity::EK_Exception:
3021 return !IsCopy;
3022
3023 case InitializedEntity::EK_New:
3024 case InitializedEntity::EK_Variable:
3025 case InitializedEntity::EK_Base:
3026 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003027 case InitializedEntity::EK_ArrayElement:
3028 case InitializedEntity::EK_VectorElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003029 return false;
3030
3031 case InitializedEntity::EK_Parameter:
3032 case InitializedEntity::EK_Temporary:
3033 return true;
3034 }
3035
3036 llvm_unreachable("missed an InitializedEntity kind?");
3037}
3038
3039/// \brief If we need to perform an additional copy of the initialized object
3040/// for this kind of entity (e.g., the result of a function or an object being
3041/// thrown), make the copy.
3042static Sema::OwningExprResult CopyIfRequiredForEntity(Sema &S,
3043 const InitializedEntity &Entity,
Douglas Gregora4b592a2009-12-19 03:01:41 +00003044 const InitializationKind &Kind,
Douglas Gregore1314a62009-12-18 05:02:21 +00003045 Sema::OwningExprResult CurInit) {
3046 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003047
3048 switch (Entity.getKind()) {
3049 case InitializedEntity::EK_Result:
Douglas Gregor1b303932009-12-22 15:35:07 +00003050 if (Entity.getType()->isReferenceType())
Douglas Gregore1314a62009-12-18 05:02:21 +00003051 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003052 Loc = Entity.getReturnLoc();
3053 break;
3054
3055 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003056 Loc = Entity.getThrowLoc();
3057 break;
3058
3059 case InitializedEntity::EK_Variable:
Douglas Gregor1b303932009-12-22 15:35:07 +00003060 if (Entity.getType()->isReferenceType() ||
Douglas Gregora4b592a2009-12-19 03:01:41 +00003061 Kind.getKind() != InitializationKind::IK_Copy)
3062 return move(CurInit);
3063 Loc = Entity.getDecl()->getLocation();
3064 break;
3065
Douglas Gregore1314a62009-12-18 05:02:21 +00003066 case InitializedEntity::EK_Parameter:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003067 // FIXME: Do we need this initialization for a parameter?
3068 return move(CurInit);
3069
Douglas Gregore1314a62009-12-18 05:02:21 +00003070 case InitializedEntity::EK_New:
3071 case InitializedEntity::EK_Temporary:
3072 case InitializedEntity::EK_Base:
3073 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003074 case InitializedEntity::EK_ArrayElement:
3075 case InitializedEntity::EK_VectorElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003076 // We don't need to copy for any of these initialized entities.
3077 return move(CurInit);
3078 }
3079
3080 Expr *CurInitExpr = (Expr *)CurInit.get();
3081 CXXRecordDecl *Class = 0;
3082 if (const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>())
3083 Class = cast<CXXRecordDecl>(Record->getDecl());
3084 if (!Class)
3085 return move(CurInit);
3086
3087 // Perform overload resolution using the class's copy constructors.
3088 DeclarationName ConstructorName
3089 = S.Context.DeclarationNames.getCXXConstructorName(
3090 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
3091 DeclContext::lookup_iterator Con, ConEnd;
3092 OverloadCandidateSet CandidateSet;
3093 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
3094 Con != ConEnd; ++Con) {
3095 // Find the constructor (which may be a template).
3096 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3097 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor507eb872009-12-22 00:34:07 +00003098 !Constructor->isCopyConstructor())
Douglas Gregore1314a62009-12-18 05:02:21 +00003099 continue;
3100
3101 S.AddOverloadCandidate(Constructor, &CurInitExpr, 1, CandidateSet);
3102 }
3103
3104 OverloadCandidateSet::iterator Best;
3105 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3106 case OR_Success:
3107 break;
3108
3109 case OR_No_Viable_Function:
3110 S.Diag(Loc, diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003111 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003112 << CurInitExpr->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003113 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
3114 &CurInitExpr, 1);
Douglas Gregore1314a62009-12-18 05:02:21 +00003115 return S.ExprError();
3116
3117 case OR_Ambiguous:
3118 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003119 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003120 << CurInitExpr->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003121 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_ViableCandidates,
3122 &CurInitExpr, 1);
Douglas Gregore1314a62009-12-18 05:02:21 +00003123 return S.ExprError();
3124
3125 case OR_Deleted:
3126 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003127 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003128 << CurInitExpr->getSourceRange();
3129 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3130 << Best->Function->isDeleted();
3131 return S.ExprError();
3132 }
3133
3134 CurInit.release();
3135 return S.BuildCXXConstructExpr(Loc, CurInitExpr->getType(),
3136 cast<CXXConstructorDecl>(Best->Function),
3137 /*Elidable=*/true,
3138 Sema::MultiExprArg(S,
3139 (void**)&CurInitExpr, 1));
3140}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003141
3142Action::OwningExprResult
3143InitializationSequence::Perform(Sema &S,
3144 const InitializedEntity &Entity,
3145 const InitializationKind &Kind,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003146 Action::MultiExprArg Args,
3147 QualType *ResultType) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003148 if (SequenceKind == FailedSequence) {
3149 unsigned NumArgs = Args.size();
3150 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3151 return S.ExprError();
3152 }
3153
3154 if (SequenceKind == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003155 // If the declaration is a non-dependent, incomplete array type
3156 // that has an initializer, then its type will be completed once
3157 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00003158 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00003159 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003160 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003161 if (const IncompleteArrayType *ArrayT
3162 = S.Context.getAsIncompleteArrayType(DeclType)) {
3163 // FIXME: We don't currently have the ability to accurately
3164 // compute the length of an initializer list without
3165 // performing full type-checking of the initializer list
3166 // (since we have to determine where braces are implicitly
3167 // introduced and such). So, we fall back to making the array
3168 // type a dependently-sized array type with no specified
3169 // bound.
3170 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3171 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00003172
Douglas Gregor51e77d52009-12-10 17:56:55 +00003173 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00003174 if (DeclaratorDecl *DD = Entity.getDecl()) {
3175 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3176 TypeLoc TL = TInfo->getTypeLoc();
3177 if (IncompleteArrayTypeLoc *ArrayLoc
3178 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3179 Brackets = ArrayLoc->getBracketsRange();
3180 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00003181 }
3182
3183 *ResultType
3184 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3185 /*NumElts=*/0,
3186 ArrayT->getSizeModifier(),
3187 ArrayT->getIndexTypeCVRQualifiers(),
3188 Brackets);
3189 }
3190
3191 }
3192 }
3193
Eli Friedmana553d4a2009-12-22 02:35:53 +00003194 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003195 return Sema::OwningExprResult(S, Args.release()[0]);
3196
3197 unsigned NumArgs = Args.size();
3198 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3199 SourceLocation(),
3200 (Expr **)Args.release(),
3201 NumArgs,
3202 SourceLocation()));
3203 }
3204
Douglas Gregor85dabae2009-12-16 01:38:02 +00003205 if (SequenceKind == NoInitialization)
3206 return S.Owned((Expr *)0);
3207
Douglas Gregor1b303932009-12-22 15:35:07 +00003208 QualType DestType = Entity.getType().getNonReferenceType();
3209 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00003210 // the same as Entity.getDecl()->getType() in cases involving type merging,
3211 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003212 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003213 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00003214 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003215
Douglas Gregor85dabae2009-12-16 01:38:02 +00003216 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3217
3218 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3219
3220 // For initialization steps that start with a single initializer,
3221 // grab the only argument out the Args and place it into the "current"
3222 // initializer.
3223 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003224 case SK_ResolveAddressOfOverloadedFunction:
3225 case SK_CastDerivedToBaseRValue:
3226 case SK_CastDerivedToBaseLValue:
3227 case SK_BindReference:
3228 case SK_BindReferenceToTemporary:
3229 case SK_UserConversion:
3230 case SK_QualificationConversionLValue:
3231 case SK_QualificationConversionRValue:
3232 case SK_ConversionSequence:
3233 case SK_ListInitialization:
3234 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003235 case SK_StringInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00003236 assert(Args.size() == 1);
3237 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3238 if (CurInit.isInvalid())
3239 return S.ExprError();
3240 break;
3241
3242 case SK_ConstructorInitialization:
3243 case SK_ZeroInitialization:
3244 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003245 }
3246
3247 // Walk through the computed steps for the initialization sequence,
3248 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003249 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003250 for (step_iterator Step = step_begin(), StepEnd = step_end();
3251 Step != StepEnd; ++Step) {
3252 if (CurInit.isInvalid())
3253 return S.ExprError();
3254
3255 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003256 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003257
3258 switch (Step->Kind) {
3259 case SK_ResolveAddressOfOverloadedFunction:
3260 // Overload resolution determined which function invoke; update the
3261 // initializer to reflect that choice.
3262 CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function);
3263 break;
3264
3265 case SK_CastDerivedToBaseRValue:
3266 case SK_CastDerivedToBaseLValue: {
3267 // We have a derived-to-base cast that produces either an rvalue or an
3268 // lvalue. Perform that cast.
3269
3270 // Casts to inaccessible base classes are allowed with C-style casts.
3271 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3272 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3273 CurInitExpr->getLocStart(),
3274 CurInitExpr->getSourceRange(),
3275 IgnoreBaseAccess))
3276 return S.ExprError();
3277
3278 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3279 CastExpr::CK_DerivedToBase,
3280 (Expr*)CurInit.release(),
3281 Step->Kind == SK_CastDerivedToBaseLValue));
3282 break;
3283 }
3284
3285 case SK_BindReference:
3286 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3287 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3288 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00003289 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003290 << BitField->getDeclName()
3291 << CurInitExpr->getSourceRange();
3292 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3293 return S.ExprError();
3294 }
3295
3296 // Reference binding does not have any corresponding ASTs.
3297
3298 // Check exception specifications
3299 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3300 return S.ExprError();
3301 break;
3302
3303 case SK_BindReferenceToTemporary:
3304 // Check exception specifications
3305 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3306 return S.ExprError();
3307
3308 // FIXME: At present, we have no AST to describe when we need to make a
3309 // temporary to bind a reference to. We should.
3310 break;
3311
3312 case SK_UserConversion: {
3313 // We have a user-defined conversion that invokes either a constructor
3314 // or a conversion function.
3315 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregore1314a62009-12-18 05:02:21 +00003316 bool IsCopy = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003317 if (CXXConstructorDecl *Constructor
3318 = dyn_cast<CXXConstructorDecl>(Step->Function)) {
3319 // Build a call to the selected constructor.
3320 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3321 SourceLocation Loc = CurInitExpr->getLocStart();
3322 CurInit.release(); // Ownership transferred into MultiExprArg, below.
3323
3324 // Determine the arguments required to actually perform the constructor
3325 // call.
3326 if (S.CompleteConstructorCall(Constructor,
3327 Sema::MultiExprArg(S,
3328 (void **)&CurInitExpr,
3329 1),
3330 Loc, ConstructorArgs))
3331 return S.ExprError();
3332
3333 // Build the an expression that constructs a temporary.
3334 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3335 move_arg(ConstructorArgs));
3336 if (CurInit.isInvalid())
3337 return S.ExprError();
3338
3339 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00003340 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3341 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3342 S.IsDerivedFrom(SourceType, Class))
3343 IsCopy = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003344 } else {
3345 // Build a call to the conversion function.
3346 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function);
Douglas Gregore1314a62009-12-18 05:02:21 +00003347
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003348 // FIXME: Should we move this initialization into a separate
3349 // derived-to-base conversion? I believe the answer is "no", because
3350 // we don't want to turn off access control here for c-style casts.
3351 if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion))
3352 return S.ExprError();
3353
3354 // Do a little dance to make sure that CurInit has the proper
3355 // pointer.
3356 CurInit.release();
3357
3358 // Build the actual call to the conversion function.
3359 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3360 if (CurInit.isInvalid() || !CurInit.get())
3361 return S.ExprError();
3362
3363 CastKind = CastExpr::CK_UserDefinedConversion;
3364 }
3365
Douglas Gregore1314a62009-12-18 05:02:21 +00003366 if (shouldBindAsTemporary(Entity, IsCopy))
3367 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3368
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003369 CurInitExpr = CurInit.takeAs<Expr>();
3370 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3371 CastKind,
3372 CurInitExpr,
Douglas Gregore1314a62009-12-18 05:02:21 +00003373 false));
3374
3375 if (!IsCopy)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003376 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003377 break;
3378 }
3379
3380 case SK_QualificationConversionLValue:
3381 case SK_QualificationConversionRValue:
3382 // Perform a qualification conversion; these can never go wrong.
3383 S.ImpCastExprToType(CurInitExpr, Step->Type,
3384 CastExpr::CK_NoOp,
3385 Step->Kind == SK_QualificationConversionLValue);
3386 CurInit.release();
3387 CurInit = S.Owned(CurInitExpr);
3388 break;
3389
3390 case SK_ConversionSequence:
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003391 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003392 false, false, *Step->ICS))
3393 return S.ExprError();
3394
3395 CurInit.release();
3396 CurInit = S.Owned(CurInitExpr);
3397 break;
Douglas Gregor51e77d52009-12-10 17:56:55 +00003398
3399 case SK_ListInitialization: {
3400 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3401 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00003402 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregor51e77d52009-12-10 17:56:55 +00003403 return S.ExprError();
3404
3405 CurInit.release();
3406 CurInit = S.Owned(InitList);
3407 break;
3408 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003409
3410 case SK_ConstructorInitialization: {
3411 CXXConstructorDecl *Constructor
3412 = cast<CXXConstructorDecl>(Step->Function);
3413
3414 // Build a call to the selected constructor.
3415 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3416 SourceLocation Loc = Kind.getLocation();
3417
3418 // Determine the arguments required to actually perform the constructor
3419 // call.
3420 if (S.CompleteConstructorCall(Constructor, move(Args),
3421 Loc, ConstructorArgs))
3422 return S.ExprError();
3423
3424 // Build the an expression that constructs a temporary.
Douglas Gregor1b303932009-12-22 15:35:07 +00003425 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
Douglas Gregor39c778b2009-12-20 22:01:25 +00003426 Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003427 move_arg(ConstructorArgs),
3428 ConstructorInitRequiresZeroInit);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003429 if (CurInit.isInvalid())
3430 return S.ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003431
3432 bool Elidable
3433 = cast<CXXConstructExpr>((Expr *)CurInit.get())->isElidable();
3434 if (shouldBindAsTemporary(Entity, Elidable))
3435 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3436
3437 if (!Elidable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003438 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003439 break;
3440 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003441
3442 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003443 step_iterator NextStep = Step;
3444 ++NextStep;
3445 if (NextStep != StepEnd &&
3446 NextStep->Kind == SK_ConstructorInitialization) {
3447 // The need for zero-initialization is recorded directly into
3448 // the call to the object's constructor within the next step.
3449 ConstructorInitRequiresZeroInit = true;
3450 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3451 S.getLangOptions().CPlusPlus &&
3452 !Kind.isImplicitValueInit()) {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003453 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3454 Kind.getRange().getBegin(),
3455 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003456 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003457 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003458 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003459 break;
3460 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003461
3462 case SK_CAssignment: {
3463 QualType SourceType = CurInitExpr->getType();
3464 Sema::AssignConvertType ConvTy =
3465 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregor96596c92009-12-22 07:24:36 +00003466
3467 // If this is a call, allow conversion to a transparent union.
3468 if (ConvTy != Sema::Compatible &&
3469 Entity.getKind() == InitializedEntity::EK_Parameter &&
3470 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3471 == Sema::Compatible)
3472 ConvTy = Sema::Compatible;
3473
Douglas Gregore1314a62009-12-18 05:02:21 +00003474 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3475 Step->Type, SourceType,
3476 CurInitExpr, getAssignmentAction(Entity)))
3477 return S.ExprError();
3478
3479 CurInit.release();
3480 CurInit = S.Owned(CurInitExpr);
3481 break;
3482 }
Eli Friedman78275202009-12-19 08:11:05 +00003483
3484 case SK_StringInit: {
3485 QualType Ty = Step->Type;
3486 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3487 break;
3488 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003489 }
3490 }
3491
3492 return move(CurInit);
3493}
3494
3495//===----------------------------------------------------------------------===//
3496// Diagnose initialization failures
3497//===----------------------------------------------------------------------===//
3498bool InitializationSequence::Diagnose(Sema &S,
3499 const InitializedEntity &Entity,
3500 const InitializationKind &Kind,
3501 Expr **Args, unsigned NumArgs) {
3502 if (SequenceKind != FailedSequence)
3503 return false;
3504
Douglas Gregor1b303932009-12-22 15:35:07 +00003505 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003506 switch (Failure) {
3507 case FK_TooManyInitsForReference:
3508 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3509 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
3510 break;
3511
3512 case FK_ArrayNeedsInitList:
3513 case FK_ArrayNeedsInitListOrStringLiteral:
3514 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3515 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3516 break;
3517
3518 case FK_AddressOfOverloadFailed:
3519 S.ResolveAddressOfOverloadedFunction(Args[0],
3520 DestType.getNonReferenceType(),
3521 true);
3522 break;
3523
3524 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00003525 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003526 switch (FailedOverloadResult) {
3527 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00003528 if (Failure == FK_UserConversionOverloadFailed)
3529 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3530 << Args[0]->getType() << DestType
3531 << Args[0]->getSourceRange();
3532 else
3533 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3534 << DestType << Args[0]->getType()
3535 << Args[0]->getSourceRange();
3536
John McCallad907772010-01-12 07:18:19 +00003537 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_ViableCandidates,
3538 Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003539 break;
3540
3541 case OR_No_Viable_Function:
3542 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3543 << Args[0]->getType() << DestType.getNonReferenceType()
3544 << Args[0]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003545 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3546 Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003547 break;
3548
3549 case OR_Deleted: {
3550 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3551 << Args[0]->getType() << DestType.getNonReferenceType()
3552 << Args[0]->getSourceRange();
3553 OverloadCandidateSet::iterator Best;
3554 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3555 Kind.getLocation(),
3556 Best);
3557 if (Ovl == OR_Deleted) {
3558 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3559 << Best->Function->isDeleted();
3560 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003561 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003562 }
3563 break;
3564 }
3565
3566 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003567 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003568 break;
3569 }
3570 break;
3571
3572 case FK_NonConstLValueReferenceBindingToTemporary:
3573 case FK_NonConstLValueReferenceBindingToUnrelated:
3574 S.Diag(Kind.getLocation(),
3575 Failure == FK_NonConstLValueReferenceBindingToTemporary
3576 ? diag::err_lvalue_reference_bind_to_temporary
3577 : diag::err_lvalue_reference_bind_to_unrelated)
3578 << DestType.getNonReferenceType()
3579 << Args[0]->getType()
3580 << Args[0]->getSourceRange();
3581 break;
3582
3583 case FK_RValueReferenceBindingToLValue:
3584 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3585 << Args[0]->getSourceRange();
3586 break;
3587
3588 case FK_ReferenceInitDropsQualifiers:
3589 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3590 << DestType.getNonReferenceType()
3591 << Args[0]->getType()
3592 << Args[0]->getSourceRange();
3593 break;
3594
3595 case FK_ReferenceInitFailed:
3596 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3597 << DestType.getNonReferenceType()
3598 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3599 << Args[0]->getType()
3600 << Args[0]->getSourceRange();
3601 break;
3602
3603 case FK_ConversionFailed:
Douglas Gregore1314a62009-12-18 05:02:21 +00003604 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
3605 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003606 << DestType
3607 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3608 << Args[0]->getType()
3609 << Args[0]->getSourceRange();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003610 break;
3611
3612 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003613 SourceRange R;
3614
3615 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3616 R = SourceRange(InitList->getInit(1)->getLocStart(),
3617 InitList->getLocEnd());
3618 else
3619 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00003620
3621 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor85dabae2009-12-16 01:38:02 +00003622 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00003623 break;
3624 }
3625
3626 case FK_ReferenceBindingToInitList:
3627 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3628 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3629 break;
3630
3631 case FK_InitListBadDestinationType:
3632 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3633 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3634 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003635
3636 case FK_ConstructorOverloadFailed: {
3637 SourceRange ArgsRange;
3638 if (NumArgs)
3639 ArgsRange = SourceRange(Args[0]->getLocStart(),
3640 Args[NumArgs - 1]->getLocEnd());
3641
3642 // FIXME: Using "DestType" for the entity we're printing is probably
3643 // bad.
3644 switch (FailedOverloadResult) {
3645 case OR_Ambiguous:
3646 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3647 << DestType << ArgsRange;
John McCall12f97bc2010-01-08 04:41:39 +00003648 S.PrintOverloadCandidates(FailedCandidateSet,
John McCallad907772010-01-12 07:18:19 +00003649 Sema::OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003650 break;
3651
3652 case OR_No_Viable_Function:
3653 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3654 << DestType << ArgsRange;
John McCallad907772010-01-12 07:18:19 +00003655 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3656 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003657 break;
3658
3659 case OR_Deleted: {
3660 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3661 << true << DestType << ArgsRange;
3662 OverloadCandidateSet::iterator Best;
3663 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3664 Kind.getLocation(),
3665 Best);
3666 if (Ovl == OR_Deleted) {
3667 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3668 << Best->Function->isDeleted();
3669 } else {
3670 llvm_unreachable("Inconsistent overload resolution?");
3671 }
3672 break;
3673 }
3674
3675 case OR_Success:
3676 llvm_unreachable("Conversion did not fail!");
3677 break;
3678 }
3679 break;
3680 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003681
3682 case FK_DefaultInitOfConst:
3683 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3684 << DestType;
3685 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003686 }
3687
3688 return true;
3689}
Douglas Gregore1314a62009-12-18 05:02:21 +00003690
3691//===----------------------------------------------------------------------===//
3692// Initialization helper functions
3693//===----------------------------------------------------------------------===//
3694Sema::OwningExprResult
3695Sema::PerformCopyInitialization(const InitializedEntity &Entity,
3696 SourceLocation EqualLoc,
3697 OwningExprResult Init) {
3698 if (Init.isInvalid())
3699 return ExprError();
3700
3701 Expr *InitE = (Expr *)Init.get();
3702 assert(InitE && "No initialization expression?");
3703
3704 if (EqualLoc.isInvalid())
3705 EqualLoc = InitE->getLocStart();
3706
3707 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
3708 EqualLoc);
3709 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
3710 Init.release();
3711 return Seq.Perform(*this, Entity, Kind,
3712 MultiExprArg(*this, (void**)&InitE, 1));
3713}