blob: b13c4ad29945ae321028a8a2620c537b2dbeab8e [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
Anders Carlssondbb25a32010-01-23 20:47:59 +0000205 void CheckImplicitInitList(const InitializedEntity *Entity,
206 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000207 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000208 unsigned &StructuredIndex,
209 bool TopLevelObject = false);
Anders Carlssond0849252010-01-23 19:55:29 +0000210 void CheckExplicitInitList(const InitializedEntity *Entity,
211 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000212 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000213 unsigned &StructuredIndex,
214 bool TopLevelObject = false);
Anders Carlssond0849252010-01-23 19:55:29 +0000215 void CheckListElementTypes(const InitializedEntity *Entity,
216 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000217 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000218 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000219 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000220 unsigned &StructuredIndex,
221 bool TopLevelObject = false);
Anders Carlssond0849252010-01-23 19:55:29 +0000222 void CheckSubElementType(const InitializedEntity *Entity,
223 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000224 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000225 InitListExpr *StructuredList,
226 unsigned &StructuredIndex);
Anders Carlssond0849252010-01-23 19:55:29 +0000227 void CheckScalarType(const InitializedEntity *Entity,
228 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000229 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000230 InitListExpr *StructuredList,
231 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000232 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000233 unsigned &Index,
234 InitListExpr *StructuredList,
235 unsigned &StructuredIndex);
Anders Carlssond0849252010-01-23 19:55:29 +0000236 void CheckVectorType(const InitializedEntity *Entity,
237 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000238 InitListExpr *StructuredList,
239 unsigned &StructuredIndex);
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000240 void CheckStructUnionTypes(const InitializedEntity *Entity,
241 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000242 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000243 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000244 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000245 unsigned &StructuredIndex,
246 bool TopLevelObject = false);
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000247 void CheckArrayType(const InitializedEntity *Entity,
248 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000249 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000250 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000251 InitListExpr *StructuredList,
252 unsigned &StructuredIndex);
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000253 bool CheckDesignatedInitializer(const InitializedEntity *Entity,
254 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000255 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000256 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000257 RecordDecl::field_iterator *NextField,
258 llvm::APSInt *NextElementIndex,
259 unsigned &Index,
260 InitListExpr *StructuredList,
261 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000262 bool FinishSubobjectInit,
263 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000264 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
265 QualType CurrentObjectType,
266 InitListExpr *StructuredList,
267 unsigned StructuredIndex,
268 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000269 void UpdateStructuredListElement(InitListExpr *StructuredList,
270 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000271 Expr *expr);
272 int numArrayElements(QualType DeclType);
273 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000274
Douglas Gregor2bb07652009-12-22 00:05:34 +0000275 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
276 const InitializedEntity &ParentEntity,
277 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000278 void FillInValueInitializations(const InitializedEntity &Entity,
279 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000280public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000281 InitListChecker(Sema &S, const InitializedEntity &Entity,
282 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000283 bool HadError() { return hadError; }
284
285 // @brief Retrieves the fully-structured initializer list used for
286 // semantic analysis and code generation.
287 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
288};
Chris Lattner9ececce2009-02-24 22:48:58 +0000289} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000290
Douglas Gregor2bb07652009-12-22 00:05:34 +0000291void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
292 const InitializedEntity &ParentEntity,
293 InitListExpr *ILE,
294 bool &RequiresSecondPass) {
295 SourceLocation Loc = ILE->getSourceRange().getBegin();
296 unsigned NumInits = ILE->getNumInits();
297 InitializedEntity MemberEntity
298 = InitializedEntity::InitializeMember(Field, &ParentEntity);
299 if (Init >= NumInits || !ILE->getInit(Init)) {
300 // FIXME: We probably don't need to handle references
301 // specially here, since value-initialization of references is
302 // handled in InitializationSequence.
303 if (Field->getType()->isReferenceType()) {
304 // C++ [dcl.init.aggr]p9:
305 // If an incomplete or empty initializer-list leaves a
306 // member of reference type uninitialized, the program is
307 // ill-formed.
308 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
309 << Field->getType()
310 << ILE->getSyntacticForm()->getSourceRange();
311 SemaRef.Diag(Field->getLocation(),
312 diag::note_uninit_reference_member);
313 hadError = true;
314 return;
315 }
316
317 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
318 true);
319 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
320 if (!InitSeq) {
321 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
322 hadError = true;
323 return;
324 }
325
326 Sema::OwningExprResult MemberInit
327 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
328 Sema::MultiExprArg(SemaRef, 0, 0));
329 if (MemberInit.isInvalid()) {
330 hadError = true;
331 return;
332 }
333
334 if (hadError) {
335 // Do nothing
336 } else if (Init < NumInits) {
337 ILE->setInit(Init, MemberInit.takeAs<Expr>());
338 } else if (InitSeq.getKind()
339 == InitializationSequence::ConstructorInitialization) {
340 // Value-initialization requires a constructor call, so
341 // extend the initializer list to include the constructor
342 // call and make a note that we'll need to take another pass
343 // through the initializer list.
344 ILE->updateInit(Init, MemberInit.takeAs<Expr>());
345 RequiresSecondPass = true;
346 }
347 } else if (InitListExpr *InnerILE
348 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
349 FillInValueInitializations(MemberEntity, InnerILE,
350 RequiresSecondPass);
351}
352
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000353/// Recursively replaces NULL values within the given initializer list
354/// with expressions that perform value-initialization of the
355/// appropriate type.
Douglas Gregor723796a2009-12-16 06:35:08 +0000356void
357InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
358 InitListExpr *ILE,
359 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000360 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000361 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000362 SourceLocation Loc = ILE->getSourceRange().getBegin();
363 if (ILE->getSyntacticForm())
364 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000365
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000366 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000367 if (RType->getDecl()->isUnion() &&
368 ILE->getInitializedFieldInUnion())
369 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
370 Entity, ILE, RequiresSecondPass);
371 else {
372 unsigned Init = 0;
373 for (RecordDecl::field_iterator
374 Field = RType->getDecl()->field_begin(),
375 FieldEnd = RType->getDecl()->field_end();
376 Field != FieldEnd; ++Field) {
377 if (Field->isUnnamedBitfield())
378 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000379
Douglas Gregor2bb07652009-12-22 00:05:34 +0000380 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000381 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000382
383 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
384 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000385 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000386
Douglas Gregor2bb07652009-12-22 00:05:34 +0000387 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000388
Douglas Gregor2bb07652009-12-22 00:05:34 +0000389 // Only look at the first initialization of a union.
390 if (RType->getDecl()->isUnion())
391 break;
392 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000393 }
394
395 return;
Mike Stump11289f42009-09-09 15:08:12 +0000396 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000397
398 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000399
Douglas Gregor723796a2009-12-16 06:35:08 +0000400 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000401 unsigned NumInits = ILE->getNumInits();
402 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000403 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000404 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000405 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
406 NumElements = CAType->getSize().getZExtValue();
Douglas Gregor723796a2009-12-16 06:35:08 +0000407 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
408 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000409 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000410 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000411 NumElements = VType->getNumElements();
Douglas Gregor723796a2009-12-16 06:35:08 +0000412 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
413 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000414 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000415 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000416
Douglas Gregor723796a2009-12-16 06:35:08 +0000417
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000418 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000419 if (hadError)
420 return;
421
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000422 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
423 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000424 ElementEntity.setElementIndex(Init);
425
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000426 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000427 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
428 true);
429 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
430 if (!InitSeq) {
431 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000432 hadError = true;
433 return;
434 }
435
Douglas Gregor723796a2009-12-16 06:35:08 +0000436 Sema::OwningExprResult ElementInit
437 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
438 Sema::MultiExprArg(SemaRef, 0, 0));
439 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000440 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000441 return;
442 }
443
444 if (hadError) {
445 // Do nothing
446 } else if (Init < NumInits) {
447 ILE->setInit(Init, ElementInit.takeAs<Expr>());
448 } else if (InitSeq.getKind()
449 == InitializationSequence::ConstructorInitialization) {
450 // Value-initialization requires a constructor call, so
451 // extend the initializer list to include the constructor
452 // call and make a note that we'll need to take another pass
453 // through the initializer list.
454 ILE->updateInit(Init, ElementInit.takeAs<Expr>());
455 RequiresSecondPass = true;
456 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000457 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000458 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
459 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000460 }
461}
462
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000463
Douglas Gregor723796a2009-12-16 06:35:08 +0000464InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
465 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000466 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000467 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000468
Eli Friedman23a9e312008-05-19 19:16:24 +0000469 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000470 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000471 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000472 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000473 CheckExplicitInitList(&Entity, IL, T, newIndex,
474 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000475 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000476
Douglas Gregor723796a2009-12-16 06:35:08 +0000477 if (!hadError) {
478 bool RequiresSecondPass = false;
479 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000480 if (RequiresSecondPass && !hadError)
Douglas Gregor723796a2009-12-16 06:35:08 +0000481 FillInValueInitializations(Entity, FullyStructuredList,
482 RequiresSecondPass);
483 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000484}
485
486int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000487 // FIXME: use a proper constant
488 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000489 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000490 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000491 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
492 }
493 return maxElements;
494}
495
496int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000497 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000498 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000499 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000500 Field = structDecl->field_begin(),
501 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000502 Field != FieldEnd; ++Field) {
503 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
504 ++InitializableMembers;
505 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000506 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000507 return std::min(InitializableMembers, 1);
508 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000509}
510
Anders Carlssondbb25a32010-01-23 20:47:59 +0000511void InitListChecker::CheckImplicitInitList(const InitializedEntity *Entity,
512 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000513 QualType T, unsigned &Index,
514 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000515 unsigned &StructuredIndex,
516 bool TopLevelObject) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000517 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000518
Steve Narofff8ecff22008-05-01 22:18:59 +0000519 if (T->isArrayType())
520 maxElements = numArrayElements(T);
521 else if (T->isStructureType() || T->isUnionType())
522 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000523 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000524 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000525 else
526 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000527
Eli Friedmane0f832b2008-05-25 13:49:22 +0000528 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000529 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000530 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000531 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000532 hadError = true;
533 return;
534 }
535
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000536 // Build a structured initializer list corresponding to this subobject.
537 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000538 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
539 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000540 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
541 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000542 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000543
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000544 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000545 unsigned StartIndex = Index;
Anders Carlssondbb25a32010-01-23 20:47:59 +0000546 CheckListElementTypes(Entity, ParentIList, T,
547 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000548 StructuredSubobjectInitList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000549 StructuredSubobjectInitIndex,
550 TopLevelObject);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000551 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000552 StructuredSubobjectInitList->setType(T);
553
Douglas Gregor5741efb2009-03-01 17:12:46 +0000554 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000555 // range corresponds with the end of the last initializer it used.
556 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000557 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000558 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
559 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
560 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000561}
562
Anders Carlssond0849252010-01-23 19:55:29 +0000563void InitListChecker::CheckExplicitInitList(const InitializedEntity *Entity,
564 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000565 unsigned &Index,
566 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000567 unsigned &StructuredIndex,
568 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000569 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000570 SyntacticToSemantic[IList] = StructuredList;
571 StructuredList->setSyntacticForm(IList);
Anders Carlssond0849252010-01-23 19:55:29 +0000572 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
573 Index, StructuredList, StructuredIndex, TopLevelObject);
Steve Naroff125d73d2008-05-06 00:23:44 +0000574 IList->setType(T);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000575 StructuredList->setType(T);
Eli Friedman85f54972008-05-25 13:22:35 +0000576 if (hadError)
577 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000578
Eli Friedman85f54972008-05-25 13:22:35 +0000579 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000580 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000581 if (StructuredIndex == 1 &&
582 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000583 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000584 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000585 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000586 hadError = true;
587 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000588 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000589 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000590 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000591 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000592 // Don't complain for incomplete types, since we'll get an error
593 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000594 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000595 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000596 CurrentObjectType->isArrayType()? 0 :
597 CurrentObjectType->isVectorType()? 1 :
598 CurrentObjectType->isScalarType()? 2 :
599 CurrentObjectType->isUnionType()? 3 :
600 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000601
602 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000603 if (SemaRef.getLangOptions().CPlusPlus) {
604 DK = diag::err_excess_initializers;
605 hadError = true;
606 }
Nate Begeman425038c2009-07-07 21:53:06 +0000607 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
608 DK = diag::err_excess_initializers;
609 hadError = true;
610 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000611
Chris Lattnerb0912a52009-02-24 22:50:46 +0000612 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000613 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000614 }
615 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000616
Eli Friedman0b4af8f2009-05-16 11:45:48 +0000617 if (T->isScalarType() && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000618 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000619 << IList->getSourceRange()
Chris Lattner3c7b86f2009-12-06 17:36:05 +0000620 << CodeModificationHint::CreateRemoval(IList->getLocStart())
621 << CodeModificationHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000622}
623
Anders Carlssond0849252010-01-23 19:55:29 +0000624void InitListChecker::CheckListElementTypes(const InitializedEntity *Entity,
625 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000626 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000627 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000628 unsigned &Index,
629 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000630 unsigned &StructuredIndex,
631 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000632 if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000633 CheckScalarType(Entity, IList, DeclType, Index,
634 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000635 } else if (DeclType->isVectorType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000636 CheckVectorType(Entity, IList, DeclType, Index,
637 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000638 } else if (DeclType->isAggregateType()) {
639 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000640 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000641 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000642 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000643 StructuredList, StructuredIndex,
644 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000645 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000646 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000647 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000648 false);
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000649 CheckArrayType(Entity, IList, DeclType, Zero,
650 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000651 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000652 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000653 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000654 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
655 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000656 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000657 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000658 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000659 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000660 } else if (DeclType->isRecordType()) {
661 // C++ [dcl.init]p14:
662 // [...] If the class is an aggregate (8.5.1), and the initializer
663 // is a brace-enclosed list, see 8.5.1.
664 //
665 // Note: 8.5.1 is handled below; here, we diagnose the case where
666 // we have an initializer list and a destination type that is not
667 // an aggregate.
668 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000669 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000670 << DeclType << IList->getSourceRange();
671 hadError = true;
672 } else if (DeclType->isReferenceType()) {
673 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000674 } else {
675 // In C, all types are either scalars or aggregates, but
Mike Stump11289f42009-09-09 15:08:12 +0000676 // additional handling is needed here for C++ (and possibly others?).
Steve Narofff8ecff22008-05-01 22:18:59 +0000677 assert(0 && "Unsupported initializer type");
678 }
679}
680
Anders Carlssond0849252010-01-23 19:55:29 +0000681void InitListChecker::CheckSubElementType(const InitializedEntity *Entity,
682 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000683 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000684 unsigned &Index,
685 InitListExpr *StructuredList,
686 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000687 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000688 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
689 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000690 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000691 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000692 = getStructuredSubobjectInit(IList, Index, ElemType,
693 StructuredList, StructuredIndex,
694 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000695 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000696 newStructuredList, newStructuredIndex);
697 ++StructuredIndex;
698 ++Index;
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000699 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
700 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000701 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000702 ++Index;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000703 } else if (ElemType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000704 CheckScalarType(Entity, IList, ElemType, Index,
705 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000706 } else if (ElemType->isReferenceType()) {
707 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedman23a9e312008-05-19 19:16:24 +0000708 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000709 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000710 // C++ [dcl.init.aggr]p12:
711 // All implicit type conversions (clause 4) are considered when
712 // initializing the aggregate member with an ini- tializer from
713 // an initializer-list. If the initializer can initialize a
714 // member, the member is initialized. [...]
Mike Stump11289f42009-09-09 15:08:12 +0000715 ImplicitConversionSequence ICS
Anders Carlsson03068aa2009-08-27 17:18:13 +0000716 = SemaRef.TryCopyInitialization(expr, ElemType,
717 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +0000718 /*ForceRValue=*/false,
719 /*InOverloadResolution=*/false);
Anders Carlsson03068aa2009-08-27 17:18:13 +0000720
John McCall0d1da222010-01-12 00:44:57 +0000721 if (!ICS.isBad()) {
Mike Stump11289f42009-09-09 15:08:12 +0000722 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000723 Sema::AA_Initializing))
Douglas Gregord14247a2009-01-30 22:09:00 +0000724 hadError = true;
725 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
726 ++Index;
727 return;
728 }
729
730 // Fall through for subaggregate initialization
731 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000732 // C99 6.7.8p13:
Douglas Gregord14247a2009-01-30 22:09:00 +0000733 //
734 // The initializer for a structure or union object that has
735 // automatic storage duration shall be either an initializer
736 // list as described below, or a single expression that has
737 // compatible structure or union type. In the latter case, the
738 // initial value of the object, including unnamed members, is
739 // that of the expression.
Eli Friedman9782caa2009-06-13 10:38:46 +0000740 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman893abe42009-05-29 18:22:49 +0000741 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000742 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
743 ++Index;
744 return;
745 }
746
747 // Fall through for subaggregate initialization
748 }
749
750 // C++ [dcl.init.aggr]p12:
Mike Stump11289f42009-09-09 15:08:12 +0000751 //
Douglas Gregord14247a2009-01-30 22:09:00 +0000752 // [...] Otherwise, if the member is itself a non-empty
753 // subaggregate, brace elision is assumed and the initializer is
754 // considered for the initialization of the first member of
755 // the subaggregate.
756 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Anders Carlssondbb25a32010-01-23 20:47:59 +0000757 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
Douglas Gregord14247a2009-01-30 22:09:00 +0000758 StructuredIndex);
759 ++StructuredIndex;
760 } else {
761 // We cannot initialize this element, so let
762 // PerformCopyInitialization produce the appropriate diagnostic.
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000763 SemaRef.PerformCopyInitialization(expr, ElemType, Sema::AA_Initializing);
Douglas Gregord14247a2009-01-30 22:09:00 +0000764 hadError = true;
765 ++Index;
766 ++StructuredIndex;
767 }
768 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000769}
770
Anders Carlssond0849252010-01-23 19:55:29 +0000771void InitListChecker::CheckScalarType(const InitializedEntity *Entity,
772 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000773 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000774 InitListExpr *StructuredList,
775 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000776 if (Index < IList->getNumInits()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000777 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000778 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000779 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000780 diag::err_many_braces_around_scalar_init)
781 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000782 hadError = true;
783 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000784 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000785 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000786 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump11289f42009-09-09 15:08:12 +0000787 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000788 diag::err_designator_for_scalar_init)
789 << DeclType << expr->getSourceRange();
790 hadError = true;
791 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000792 ++StructuredIndex;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000793 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000794 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000795
Anders Carlsson26d05642010-01-23 18:35:41 +0000796 Sema::OwningExprResult Result =
Anders Carlssond0849252010-01-23 19:55:29 +0000797 CheckSingleInitializer(Entity, SemaRef.Owned(expr), DeclType, SemaRef);
Anders Carlsson26d05642010-01-23 18:35:41 +0000798
799 Expr *ResultExpr;
800
801 if (Result.isInvalid())
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000802 hadError = true; // types weren't compatible.
Anders Carlsson26d05642010-01-23 18:35:41 +0000803 else {
804 ResultExpr = Result.takeAs<Expr>();
805
806 if (ResultExpr != expr) {
807 // The type was promoted, update initializer list.
808 IList->setInit(Index, ResultExpr);
809 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000810 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000811 if (hadError)
812 ++StructuredIndex;
813 else
Anders Carlsson26d05642010-01-23 18:35:41 +0000814 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
Steve Narofff8ecff22008-05-01 22:18:59 +0000815 ++Index;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000816 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000817 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000818 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000819 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000820 ++Index;
821 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000822 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000823 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000824}
825
Douglas Gregord14247a2009-01-30 22:09:00 +0000826void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
827 unsigned &Index,
828 InitListExpr *StructuredList,
829 unsigned &StructuredIndex) {
830 if (Index < IList->getNumInits()) {
831 Expr *expr = IList->getInit(Index);
832 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000833 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000834 << DeclType << IList->getSourceRange();
835 hadError = true;
836 ++Index;
837 ++StructuredIndex;
838 return;
Mike Stump11289f42009-09-09 15:08:12 +0000839 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000840
841 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Anders Carlsson271e3a42009-08-27 17:30:43 +0000842 if (SemaRef.CheckReferenceInit(expr, DeclType,
Douglas Gregorc809cc22009-09-23 23:04:10 +0000843 /*FIXME:*/expr->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +0000844 /*SuppressUserConversions=*/false,
845 /*AllowExplicit=*/false,
Mike Stump11289f42009-09-09 15:08:12 +0000846 /*ForceRValue=*/false))
Douglas Gregord14247a2009-01-30 22:09:00 +0000847 hadError = true;
848 else if (savExpr != expr) {
849 // The type was promoted, update initializer list.
850 IList->setInit(Index, expr);
851 }
852 if (hadError)
853 ++StructuredIndex;
854 else
855 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
856 ++Index;
857 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000858 // FIXME: It would be wonderful if we could point at the actual member. In
859 // general, it would be useful to pass location information down the stack,
860 // so that we know the location (or decl) of the "current object" being
861 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000862 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000863 diag::err_init_reference_member_uninitialized)
864 << DeclType
865 << IList->getSourceRange();
866 hadError = true;
867 ++Index;
868 ++StructuredIndex;
869 return;
870 }
871}
872
Anders Carlssond0849252010-01-23 19:55:29 +0000873void InitListChecker::CheckVectorType(const InitializedEntity *Entity,
874 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000875 unsigned &Index,
876 InitListExpr *StructuredList,
877 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000878 if (Index < IList->getNumInits()) {
John McCall9dd450b2009-09-21 23:43:11 +0000879 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000880 unsigned maxElements = VT->getNumElements();
881 unsigned numEltsInit = 0;
Steve Narofff8ecff22008-05-01 22:18:59 +0000882 QualType elementType = VT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +0000883
Nate Begeman5ec4b312009-08-10 23:49:36 +0000884 if (!SemaRef.getLangOptions().OpenCL) {
Anders Carlssond0849252010-01-23 19:55:29 +0000885 // FIXME: Once we know Entity is never null we can remove this check,
886 // as well as the else block.
887 if (Entity) {
888 InitializedEntity ElementEntity =
889 InitializedEntity::InitializeElement(SemaRef.Context, 0, *Entity);
890
891 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
892 // Don't attempt to go past the end of the init list
893 if (Index >= IList->getNumInits())
894 break;
895
896 ElementEntity.setElementIndex(Index);
897 CheckSubElementType(&ElementEntity, IList, elementType, Index,
898 StructuredList, StructuredIndex);
899 }
900 } else {
901 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
902 // Don't attempt to go past the end of the init list
903 if (Index >= IList->getNumInits())
904 break;
905
906 CheckSubElementType(0, IList, elementType, Index,
907 StructuredList, StructuredIndex);
908 }
909 }
Nate Begeman5ec4b312009-08-10 23:49:36 +0000910 } else {
911 // OpenCL initializers allows vectors to be constructed from vectors.
912 for (unsigned i = 0; i < maxElements; ++i) {
913 // Don't attempt to go past the end of the init list
914 if (Index >= IList->getNumInits())
915 break;
916 QualType IType = IList->getInit(Index)->getType();
917 if (!IType->isVectorType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000918 CheckSubElementType(0, IList, elementType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000919 StructuredList, StructuredIndex);
920 ++numEltsInit;
921 } else {
John McCall9dd450b2009-09-21 23:43:11 +0000922 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000923 unsigned numIElts = IVT->getNumElements();
924 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
925 numIElts);
Anders Carlssond0849252010-01-23 19:55:29 +0000926 CheckSubElementType(0, IList, VecType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000927 StructuredList, StructuredIndex);
928 numEltsInit += numIElts;
929 }
930 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000931 }
Mike Stump11289f42009-09-09 15:08:12 +0000932
Nate Begeman5ec4b312009-08-10 23:49:36 +0000933 // OpenCL & AltiVec require all elements to be initialized.
934 if (numEltsInit != maxElements)
935 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
936 SemaRef.Diag(IList->getSourceRange().getBegin(),
937 diag::err_vector_incorrect_num_initializers)
938 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000939 }
940}
941
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000942void InitListChecker::CheckArrayType(const InitializedEntity *Entity,
943 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000944 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000945 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000946 unsigned &Index,
947 InitListExpr *StructuredList,
948 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000949 // Check for the special-case of initializing an array with a string.
950 if (Index < IList->getNumInits()) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000951 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
952 SemaRef.Context)) {
953 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000954 // We place the string literal directly into the resulting
955 // initializer list. This is the only place where the structure
956 // of the structured initializer list doesn't match exactly,
957 // because doing so would involve allocating one character
958 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000959 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +0000960 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000961 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000962 return;
963 }
964 }
Chris Lattner7adf0762008-08-04 07:31:14 +0000965 if (const VariableArrayType *VAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000966 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman85f54972008-05-25 13:22:35 +0000967 // Check for VLAs; in standard C it would be possible to check this
968 // earlier, but I don't know where clang accepts VLAs (gcc accepts
969 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +0000970 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000971 diag::err_variable_object_no_init)
972 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +0000973 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000974 ++Index;
975 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +0000976 return;
977 }
978
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000979 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000980 llvm::APSInt maxElements(elementIndex.getBitWidth(),
981 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000982 bool maxElementsKnown = false;
983 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000984 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000985 maxElements = CAT->getSize();
Douglas Gregor033d1252009-01-23 16:54:12 +0000986 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000987 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000988 maxElementsKnown = true;
989 }
990
Chris Lattnerb0912a52009-02-24 22:50:46 +0000991 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattner7adf0762008-08-04 07:31:14 +0000992 ->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000993 while (Index < IList->getNumInits()) {
994 Expr *Init = IList->getInit(Index);
995 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000996 // If we're not the subobject that matches up with the '{' for
997 // the designator, we shouldn't be handling the
998 // designator. Return immediately.
999 if (!SubobjectIsDesignatorContext)
1000 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001001
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001002 // Handle this designated initializer. elementIndex will be
1003 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001004 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001005 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001006 StructuredList, StructuredIndex, true,
1007 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001008 hadError = true;
1009 continue;
1010 }
1011
Douglas Gregor033d1252009-01-23 16:54:12 +00001012 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1013 maxElements.extend(elementIndex.getBitWidth());
1014 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1015 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001016 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001017
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001018 // If the array is of incomplete type, keep track of the number of
1019 // elements in the initializer.
1020 if (!maxElementsKnown && elementIndex > maxElements)
1021 maxElements = elementIndex;
1022
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001023 continue;
1024 }
1025
1026 // If we know the maximum number of elements, and we've already
1027 // hit it, stop consuming elements in the initializer list.
1028 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001029 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001030
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001031 // FIXME: Once we know that Entity is not null, we can remove this check,
1032 // and the else block.
1033 if (Entity) {
1034 InitializedEntity ElementEntity =
1035 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1036 *Entity);
1037 // Check this element.
1038 CheckSubElementType(&ElementEntity, IList, elementType, Index,
1039 StructuredList, StructuredIndex);
1040 } else {
1041 // Check this element.
1042 CheckSubElementType(0, IList, elementType, Index,
1043 StructuredList, StructuredIndex);
1044 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001045 ++elementIndex;
1046
1047 // If the array is of incomplete type, keep track of the number of
1048 // elements in the initializer.
1049 if (!maxElementsKnown && elementIndex > maxElements)
1050 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001051 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001052 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001053 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001054 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001055 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001056 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001057 // Sizing an array implicitly to zero is not allowed by ISO C,
1058 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001059 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001060 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001061 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001062
Mike Stump11289f42009-09-09 15:08:12 +00001063 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001064 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001065 }
1066}
1067
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001068void InitListChecker::CheckStructUnionTypes(const InitializedEntity *Entity,
1069 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001070 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001071 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001072 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001073 unsigned &Index,
1074 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001075 unsigned &StructuredIndex,
1076 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001077 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001078
Eli Friedman23a9e312008-05-19 19:16:24 +00001079 // If the record is invalid, some of it's members are invalid. To avoid
1080 // confusion, we forgo checking the intializer for the entire record.
1081 if (structDecl->isInvalidDecl()) {
1082 hadError = true;
1083 return;
Mike Stump11289f42009-09-09 15:08:12 +00001084 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001085
1086 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1087 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001088 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001089 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001090 Field != FieldEnd; ++Field) {
1091 if (Field->getDeclName()) {
1092 StructuredList->setInitializedFieldInUnion(*Field);
1093 break;
1094 }
1095 }
1096 return;
1097 }
1098
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001099 // If structDecl is a forward declaration, this loop won't do
1100 // anything except look at designated initializers; That's okay,
1101 // because an error should get printed out elsewhere. It might be
1102 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001103 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001104 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001105 bool InitializedSomething = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001106 while (Index < IList->getNumInits()) {
1107 Expr *Init = IList->getInit(Index);
1108
1109 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001110 // If we're not the subobject that matches up with the '{' for
1111 // the designator, we shouldn't be handling the
1112 // designator. Return immediately.
1113 if (!SubobjectIsDesignatorContext)
1114 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001115
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001116 // Handle this designated initializer. Field will be updated to
1117 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001118 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001119 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001120 StructuredList, StructuredIndex,
1121 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001122 hadError = true;
1123
Douglas Gregora9add4e2009-02-12 19:00:39 +00001124 InitializedSomething = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001125 continue;
1126 }
1127
1128 if (Field == FieldEnd) {
1129 // We've run out of fields. We're done.
1130 break;
1131 }
1132
Douglas Gregora9add4e2009-02-12 19:00:39 +00001133 // We've already initialized a member of a union. We're done.
1134 if (InitializedSomething && DeclType->isUnionType())
1135 break;
1136
Douglas Gregor91f84212008-12-11 16:49:14 +00001137 // If we've hit the flexible array member at the end, we're done.
1138 if (Field->getType()->isIncompleteArrayType())
1139 break;
1140
Douglas Gregor51695702009-01-29 16:53:55 +00001141 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001142 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001143 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001144 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001145 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001146
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001147 // FIXME: Once we know Entity is not null, we can get rid of the check
1148 // and the else block.
1149 if (Entity) {
1150 InitializedEntity MemberEntity =
1151 InitializedEntity::InitializeMember(*Field, Entity);
1152 CheckSubElementType(&MemberEntity, IList, Field->getType(), Index,
1153 StructuredList, StructuredIndex);
1154 } else {
1155 CheckSubElementType(0, IList, Field->getType(), Index,
1156 StructuredList, StructuredIndex);
1157 }
Douglas Gregora9add4e2009-02-12 19:00:39 +00001158 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001159
1160 if (DeclType->isUnionType()) {
1161 // Initialize the first field within the union.
1162 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001163 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001164
1165 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001166 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001167
Mike Stump11289f42009-09-09 15:08:12 +00001168 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001169 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001170 return;
1171
1172 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001173 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001174 (!isa<InitListExpr>(IList->getInit(Index)) ||
1175 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001176 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001177 diag::err_flexible_array_init_nonempty)
1178 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001179 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001180 << *Field;
1181 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001182 ++Index;
1183 return;
1184 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001185 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001186 diag::ext_flexible_array_init)
1187 << IList->getInit(Index)->getSourceRange().getBegin();
1188 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1189 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001190 }
1191
Anders Carlssondbb25a32010-01-23 20:47:59 +00001192 // FIXME: Once we know Entity is not null, we can get rid of the check
1193 // and the else block.
1194 if (Entity) {
1195 InitializedEntity MemberEntity =
1196 InitializedEntity::InitializeMember(*Field, Entity);
1197
1198 if (isa<InitListExpr>(IList->getInit(Index)))
1199 CheckSubElementType(&MemberEntity, IList, Field->getType(), Index,
1200 StructuredList, StructuredIndex);
1201 else
1202 CheckImplicitInitList(&MemberEntity, IList, Field->getType(), Index,
1203 StructuredList, StructuredIndex);
1204 } else {
1205 if (isa<InitListExpr>(IList->getInit(Index)))
1206 CheckSubElementType(0, IList, Field->getType(), Index,
1207 StructuredList, StructuredIndex);
1208 else
1209 CheckImplicitInitList(0, IList, Field->getType(), Index,
1210 StructuredList, StructuredIndex);
1211 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001212}
Steve Narofff8ecff22008-05-01 22:18:59 +00001213
Douglas Gregord5846a12009-04-15 06:41:24 +00001214/// \brief Expand a field designator that refers to a member of an
1215/// anonymous struct or union into a series of field designators that
1216/// refers to the field within the appropriate subobject.
1217///
1218/// Field/FieldIndex will be updated to point to the (new)
1219/// currently-designated field.
1220static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001221 DesignatedInitExpr *DIE,
1222 unsigned DesigIdx,
Douglas Gregord5846a12009-04-15 06:41:24 +00001223 FieldDecl *Field,
1224 RecordDecl::field_iterator &FieldIter,
1225 unsigned &FieldIndex) {
1226 typedef DesignatedInitExpr::Designator Designator;
1227
1228 // Build the path from the current object to the member of the
1229 // anonymous struct/union (backwards).
1230 llvm::SmallVector<FieldDecl *, 4> Path;
1231 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump11289f42009-09-09 15:08:12 +00001232
Douglas Gregord5846a12009-04-15 06:41:24 +00001233 // Build the replacement designators.
1234 llvm::SmallVector<Designator, 4> Replacements;
1235 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1236 FI = Path.rbegin(), FIEnd = Path.rend();
1237 FI != FIEnd; ++FI) {
1238 if (FI + 1 == FIEnd)
Mike Stump11289f42009-09-09 15:08:12 +00001239 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001240 DIE->getDesignator(DesigIdx)->getDotLoc(),
1241 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1242 else
1243 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1244 SourceLocation()));
1245 Replacements.back().setField(*FI);
1246 }
1247
1248 // Expand the current designator into the set of replacement
1249 // designators, so we have a full subobject path down to where the
1250 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001251 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001252 &Replacements[0] + Replacements.size());
Mike Stump11289f42009-09-09 15:08:12 +00001253
Douglas Gregord5846a12009-04-15 06:41:24 +00001254 // Update FieldIter/FieldIndex;
1255 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001256 FieldIter = Record->field_begin();
Douglas Gregord5846a12009-04-15 06:41:24 +00001257 FieldIndex = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001258 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregord5846a12009-04-15 06:41:24 +00001259 FieldIter != FEnd; ++FieldIter) {
1260 if (FieldIter->isUnnamedBitfield())
1261 continue;
1262
1263 if (*FieldIter == Path.back())
1264 return;
1265
1266 ++FieldIndex;
1267 }
1268
1269 assert(false && "Unable to find anonymous struct/union field");
1270}
1271
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001272/// @brief Check the well-formedness of a C99 designated initializer.
1273///
1274/// Determines whether the designated initializer @p DIE, which
1275/// resides at the given @p Index within the initializer list @p
1276/// IList, is well-formed for a current object of type @p DeclType
1277/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001278/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001279/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001280///
1281/// @param IList The initializer list in which this designated
1282/// initializer occurs.
1283///
Douglas Gregora5324162009-04-15 04:56:10 +00001284/// @param DIE The designated initializer expression.
1285///
1286/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001287///
1288/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1289/// into which the designation in @p DIE should refer.
1290///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001291/// @param NextField If non-NULL and the first designator in @p DIE is
1292/// a field, this will be set to the field declaration corresponding
1293/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001294///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001295/// @param NextElementIndex If non-NULL and the first designator in @p
1296/// DIE is an array designator or GNU array-range designator, this
1297/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001298///
1299/// @param Index Index into @p IList where the designated initializer
1300/// @p DIE occurs.
1301///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001302/// @param StructuredList The initializer list expression that
1303/// describes all of the subobject initializers in the order they'll
1304/// actually be initialized.
1305///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001306/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001307bool
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001308InitListChecker::CheckDesignatedInitializer(const InitializedEntity *Entity,
1309 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001310 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001311 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001312 QualType &CurrentObjectType,
1313 RecordDecl::field_iterator *NextField,
1314 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001315 unsigned &Index,
1316 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001317 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001318 bool FinishSubobjectInit,
1319 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001320 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001321 // Check the actual initialization for the designated object type.
1322 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001323
1324 // Temporarily remove the designator expression from the
1325 // initializer list that the child calls see, so that we don't try
1326 // to re-process the designator.
1327 unsigned OldIndex = Index;
1328 IList->setInit(OldIndex, DIE->getInit());
1329
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001330 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001331 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001332
1333 // Restore the designated initializer expression in the syntactic
1334 // form of the initializer list.
1335 if (IList->getInit(OldIndex) != DIE->getInit())
1336 DIE->setInit(IList->getInit(OldIndex));
1337 IList->setInit(OldIndex, DIE);
1338
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001339 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001340 }
1341
Douglas Gregora5324162009-04-15 04:56:10 +00001342 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001343 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001344 "Need a non-designated initializer list to start from");
1345
Douglas Gregora5324162009-04-15 04:56:10 +00001346 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001347 // Determine the structural initializer list that corresponds to the
1348 // current subobject.
1349 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001350 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001351 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001352 SourceRange(D->getStartLocation(),
1353 DIE->getSourceRange().getEnd()));
1354 assert(StructuredList && "Expected a structured initializer list");
1355
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001356 if (D->isFieldDesignator()) {
1357 // C99 6.7.8p7:
1358 //
1359 // If a designator has the form
1360 //
1361 // . identifier
1362 //
1363 // then the current object (defined below) shall have
1364 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001365 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001366 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001367 if (!RT) {
1368 SourceLocation Loc = D->getDotLoc();
1369 if (Loc.isInvalid())
1370 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001371 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1372 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001373 ++Index;
1374 return true;
1375 }
1376
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001377 // Note: we perform a linear search of the fields here, despite
1378 // the fact that we have a faster lookup method, because we always
1379 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001380 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001381 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001382 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001383 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001384 Field = RT->getDecl()->field_begin(),
1385 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001386 for (; Field != FieldEnd; ++Field) {
1387 if (Field->isUnnamedBitfield())
1388 continue;
1389
Douglas Gregord5846a12009-04-15 06:41:24 +00001390 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001391 break;
1392
1393 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001394 }
1395
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001396 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001397 // There was no normal field in the struct with the designated
1398 // name. Perform another lookup for this name, which may find
1399 // something that we can't designate (e.g., a member function),
1400 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001401 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001402 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001403 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001404 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001405 // Name lookup didn't find anything. Determine whether this
1406 // was a typo for another field name.
1407 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1408 Sema::LookupMemberName);
1409 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl()) &&
1410 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
1411 ReplacementField->getDeclContext()->getLookupContext()
1412 ->Equals(RT->getDecl())) {
1413 SemaRef.Diag(D->getFieldLoc(),
1414 diag::err_field_designator_unknown_suggest)
1415 << FieldName << CurrentObjectType << R.getLookupName()
1416 << CodeModificationHint::CreateReplacement(D->getFieldLoc(),
1417 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001418 SemaRef.Diag(ReplacementField->getLocation(),
1419 diag::note_previous_decl)
1420 << ReplacementField->getDeclName();
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001421 } else {
1422 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1423 << FieldName << CurrentObjectType;
1424 ++Index;
1425 return true;
1426 }
1427 } else if (!KnownField) {
1428 // Determine whether we found a field at all.
1429 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1430 }
1431
1432 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001433 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001434 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001435 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001436 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001437 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001438 ++Index;
1439 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001440 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001441
1442 if (!KnownField &&
1443 cast<RecordDecl>((ReplacementField)->getDeclContext())
1444 ->isAnonymousStructOrUnion()) {
1445 // Handle an field designator that refers to a member of an
1446 // anonymous struct or union.
1447 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1448 ReplacementField,
1449 Field, FieldIndex);
1450 D = DIE->getDesignator(DesigIdx);
1451 } else if (!KnownField) {
1452 // The replacement field comes from typo correction; find it
1453 // in the list of fields.
1454 FieldIndex = 0;
1455 Field = RT->getDecl()->field_begin();
1456 for (; Field != FieldEnd; ++Field) {
1457 if (Field->isUnnamedBitfield())
1458 continue;
1459
1460 if (ReplacementField == *Field ||
1461 Field->getIdentifier() == ReplacementField->getIdentifier())
1462 break;
1463
1464 ++FieldIndex;
1465 }
1466 }
Douglas Gregord5846a12009-04-15 06:41:24 +00001467 } else if (!KnownField &&
1468 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001469 ->isAnonymousStructOrUnion()) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001470 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1471 Field, FieldIndex);
1472 D = DIE->getDesignator(DesigIdx);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001473 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001474
1475 // All of the fields of a union are located at the same place in
1476 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001477 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001478 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001479 StructuredList->setInitializedFieldInUnion(*Field);
1480 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001481
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001482 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001483 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001484
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001485 // Make sure that our non-designated initializer list has space
1486 // for a subobject corresponding to this field.
1487 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001488 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001489
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001490 // This designator names a flexible array member.
1491 if (Field->getType()->isIncompleteArrayType()) {
1492 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001493 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001494 // We can't designate an object within the flexible array
1495 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001496 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001497 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001498 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001499 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001500 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001501 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001502 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001503 << *Field;
1504 Invalid = true;
1505 }
1506
1507 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1508 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001509 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001510 diag::err_flexible_array_init_needs_braces)
1511 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001512 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001513 << *Field;
1514 Invalid = true;
1515 }
1516
1517 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001518 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001519 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001520 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001521 diag::err_flexible_array_init_nonempty)
1522 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001523 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001524 << *Field;
1525 Invalid = true;
1526 }
1527
1528 if (Invalid) {
1529 ++Index;
1530 return true;
1531 }
1532
1533 // Initialize the array.
1534 bool prevHadError = hadError;
1535 unsigned newStructuredIndex = FieldIndex;
1536 unsigned OldIndex = Index;
1537 IList->setInit(Index, DIE->getInit());
Anders Carlssond0849252010-01-23 19:55:29 +00001538 CheckSubElementType(0, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001539 StructuredList, newStructuredIndex);
1540 IList->setInit(OldIndex, DIE);
1541 if (hadError && !prevHadError) {
1542 ++Field;
1543 ++FieldIndex;
1544 if (NextField)
1545 *NextField = Field;
1546 StructuredIndex = FieldIndex;
1547 return true;
1548 }
1549 } else {
1550 // Recurse to check later designated subobjects.
1551 QualType FieldType = (*Field)->getType();
1552 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001553
1554 InitializedEntity MemberEntity =
1555 InitializedEntity::InitializeMember(*Field, Entity);
1556 if (CheckDesignatedInitializer(&MemberEntity, IList, DIE, DesigIdx + 1,
1557 FieldType, 0, 0, Index,
1558 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001559 true, false))
1560 return true;
1561 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001562
1563 // Find the position of the next field to be initialized in this
1564 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001565 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001566 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001567
1568 // If this the first designator, our caller will continue checking
1569 // the rest of this struct/class/union subobject.
1570 if (IsFirstDesignator) {
1571 if (NextField)
1572 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001573 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001574 return false;
1575 }
1576
Douglas Gregor17bd0942009-01-28 23:36:17 +00001577 if (!FinishSubobjectInit)
1578 return false;
1579
Douglas Gregord5846a12009-04-15 06:41:24 +00001580 // We've already initialized something in the union; we're done.
1581 if (RT->getDecl()->isUnion())
1582 return hadError;
1583
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001584 // Check the remaining fields within this class/struct/union subobject.
1585 bool prevHadError = hadError;
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001586
1587 CheckStructUnionTypes(0, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001588 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001589 return hadError && !prevHadError;
1590 }
1591
1592 // C99 6.7.8p6:
1593 //
1594 // If a designator has the form
1595 //
1596 // [ constant-expression ]
1597 //
1598 // then the current object (defined below) shall have array
1599 // type and the expression shall be an integer constant
1600 // expression. If the array is of unknown size, any
1601 // nonnegative value is valid.
1602 //
1603 // Additionally, cope with the GNU extension that permits
1604 // designators of the form
1605 //
1606 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001607 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001608 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001609 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001610 << CurrentObjectType;
1611 ++Index;
1612 return true;
1613 }
1614
1615 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001616 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1617 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001618 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001619 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001620 DesignatedEndIndex = DesignatedStartIndex;
1621 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001622 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001623
Mike Stump11289f42009-09-09 15:08:12 +00001624
1625 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001626 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001627 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001628 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001629 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001630
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001631 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001632 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001633 }
1634
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001635 if (isa<ConstantArrayType>(AT)) {
1636 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001637 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1638 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1639 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1640 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1641 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001642 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001643 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001644 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001645 << IndexExpr->getSourceRange();
1646 ++Index;
1647 return true;
1648 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001649 } else {
1650 // Make sure the bit-widths and signedness match.
1651 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1652 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001653 else if (DesignatedStartIndex.getBitWidth() <
1654 DesignatedEndIndex.getBitWidth())
Douglas Gregor17bd0942009-01-28 23:36:17 +00001655 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1656 DesignatedStartIndex.setIsUnsigned(true);
1657 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001658 }
Mike Stump11289f42009-09-09 15:08:12 +00001659
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001660 // Make sure that our non-designated initializer list has space
1661 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001662 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001663 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001664 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001665
Douglas Gregor17bd0942009-01-28 23:36:17 +00001666 // Repeatedly perform subobject initializations in the range
1667 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001668
Douglas Gregor17bd0942009-01-28 23:36:17 +00001669 // Move to the next designator
1670 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1671 unsigned OldIndex = Index;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001672
1673 InitializedEntity ElementEntity =
1674 InitializedEntity::InitializeElement(SemaRef.Context, 0, *Entity);
1675
Douglas Gregor17bd0942009-01-28 23:36:17 +00001676 while (DesignatedStartIndex <= DesignatedEndIndex) {
1677 // Recurse to check later designated subobjects.
1678 QualType ElementType = AT->getElementType();
1679 Index = OldIndex;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001680
1681 ElementEntity.setElementIndex(ElementIndex);
1682 if (CheckDesignatedInitializer(&ElementEntity, IList, DIE, DesigIdx + 1,
1683 ElementType, 0, 0, Index,
1684 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001685 (DesignatedStartIndex == DesignatedEndIndex),
1686 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001687 return true;
1688
1689 // Move to the next index in the array that we'll be initializing.
1690 ++DesignatedStartIndex;
1691 ElementIndex = DesignatedStartIndex.getZExtValue();
1692 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001693
1694 // If this the first designator, our caller will continue checking
1695 // the rest of this array subobject.
1696 if (IsFirstDesignator) {
1697 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001698 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001699 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001700 return false;
1701 }
Mike Stump11289f42009-09-09 15:08:12 +00001702
Douglas Gregor17bd0942009-01-28 23:36:17 +00001703 if (!FinishSubobjectInit)
1704 return false;
1705
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001706 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001707 bool prevHadError = hadError;
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001708 CheckArrayType(0, IList, CurrentObjectType, DesignatedStartIndex,
1709 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001710 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001711 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001712}
1713
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001714// Get the structured initializer list for a subobject of type
1715// @p CurrentObjectType.
1716InitListExpr *
1717InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1718 QualType CurrentObjectType,
1719 InitListExpr *StructuredList,
1720 unsigned StructuredIndex,
1721 SourceRange InitRange) {
1722 Expr *ExistingInit = 0;
1723 if (!StructuredList)
1724 ExistingInit = SyntacticToSemantic[IList];
1725 else if (StructuredIndex < StructuredList->getNumInits())
1726 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001727
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001728 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1729 return Result;
1730
1731 if (ExistingInit) {
1732 // We are creating an initializer list that initializes the
1733 // subobjects of the current object, but there was already an
1734 // initialization that completely initialized the current
1735 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001736 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001737 // struct X { int a, b; };
1738 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001739 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001740 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1741 // designated initializer re-initializes the whole
1742 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001743 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001744 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001745 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001746 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001747 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001748 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001749 << ExistingInit->getSourceRange();
1750 }
1751
Mike Stump11289f42009-09-09 15:08:12 +00001752 InitListExpr *Result
1753 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001754 InitRange.getEnd());
1755
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001756 Result->setType(CurrentObjectType);
1757
Douglas Gregor6d00c992009-03-20 23:58:33 +00001758 // Pre-allocate storage for the structured initializer list.
1759 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001760 unsigned NumInits = 0;
1761 if (!StructuredList)
1762 NumInits = IList->getNumInits();
1763 else if (Index < IList->getNumInits()) {
1764 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1765 NumInits = SubList->getNumInits();
1766 }
1767
Mike Stump11289f42009-09-09 15:08:12 +00001768 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001769 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1770 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1771 NumElements = CAType->getSize().getZExtValue();
1772 // Simple heuristic so that we don't allocate a very large
1773 // initializer with many empty entries at the end.
Douglas Gregor221c9a52009-03-21 18:13:52 +00001774 if (NumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001775 NumElements = 0;
1776 }
John McCall9dd450b2009-09-21 23:43:11 +00001777 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001778 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001779 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001780 RecordDecl *RDecl = RType->getDecl();
1781 if (RDecl->isUnion())
1782 NumElements = 1;
1783 else
Mike Stump11289f42009-09-09 15:08:12 +00001784 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001785 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001786 }
1787
Douglas Gregor221c9a52009-03-21 18:13:52 +00001788 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001789 NumElements = IList->getNumInits();
1790
1791 Result->reserveInits(NumElements);
1792
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001793 // Link this new initializer list into the structured initializer
1794 // lists.
1795 if (StructuredList)
1796 StructuredList->updateInit(StructuredIndex, Result);
1797 else {
1798 Result->setSyntacticForm(IList);
1799 SyntacticToSemantic[IList] = Result;
1800 }
1801
1802 return Result;
1803}
1804
1805/// Update the initializer at index @p StructuredIndex within the
1806/// structured initializer list to the value @p expr.
1807void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1808 unsigned &StructuredIndex,
1809 Expr *expr) {
1810 // No structured initializer list to update
1811 if (!StructuredList)
1812 return;
1813
1814 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1815 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001816 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001817 diag::warn_initializer_overrides)
1818 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001819 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001820 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001821 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001822 << PrevInit->getSourceRange();
1823 }
Mike Stump11289f42009-09-09 15:08:12 +00001824
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001825 ++StructuredIndex;
1826}
1827
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001828/// Check that the given Index expression is a valid array designator
1829/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001830/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001831/// and produces a reasonable diagnostic if there is a
1832/// failure. Returns true if there was an error, false otherwise. If
1833/// everything went okay, Value will receive the value of the constant
1834/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001835static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001836CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001837 SourceLocation Loc = Index->getSourceRange().getBegin();
1838
1839 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001840 if (S.VerifyIntegerConstantExpression(Index, &Value))
1841 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001842
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001843 if (Value.isSigned() && Value.isNegative())
1844 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001845 << Value.toString(10) << Index->getSourceRange();
1846
Douglas Gregor51650d32009-01-23 21:04:18 +00001847 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001848 return false;
1849}
1850
1851Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1852 SourceLocation Loc,
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00001853 bool GNUSyntax,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001854 OwningExprResult Init) {
1855 typedef DesignatedInitExpr::Designator ASTDesignator;
1856
1857 bool Invalid = false;
1858 llvm::SmallVector<ASTDesignator, 32> Designators;
1859 llvm::SmallVector<Expr *, 32> InitExpressions;
1860
1861 // Build designators and check array designator expressions.
1862 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1863 const Designator &D = Desig.getDesignator(Idx);
1864 switch (D.getKind()) {
1865 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001866 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001867 D.getFieldLoc()));
1868 break;
1869
1870 case Designator::ArrayDesignator: {
1871 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1872 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001873 if (!Index->isTypeDependent() &&
1874 !Index->isValueDependent() &&
1875 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001876 Invalid = true;
1877 else {
1878 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001879 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001880 D.getRBracketLoc()));
1881 InitExpressions.push_back(Index);
1882 }
1883 break;
1884 }
1885
1886 case Designator::ArrayRangeDesignator: {
1887 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1888 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1889 llvm::APSInt StartValue;
1890 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001891 bool StartDependent = StartIndex->isTypeDependent() ||
1892 StartIndex->isValueDependent();
1893 bool EndDependent = EndIndex->isTypeDependent() ||
1894 EndIndex->isValueDependent();
1895 if ((!StartDependent &&
1896 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1897 (!EndDependent &&
1898 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001899 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001900 else {
1901 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001902 if (StartDependent || EndDependent) {
1903 // Nothing to compute.
1904 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregor7a95b082009-01-23 22:22:29 +00001905 EndValue.extend(StartValue.getBitWidth());
1906 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1907 StartValue.extend(EndValue.getBitWidth());
1908
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001909 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001910 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001911 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001912 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1913 Invalid = true;
1914 } else {
1915 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001916 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001917 D.getEllipsisLoc(),
1918 D.getRBracketLoc()));
1919 InitExpressions.push_back(StartIndex);
1920 InitExpressions.push_back(EndIndex);
1921 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001922 }
1923 break;
1924 }
1925 }
1926 }
1927
1928 if (Invalid || Init.isInvalid())
1929 return ExprError();
1930
1931 // Clear out the expressions within the designation.
1932 Desig.ClearExprs(*this);
1933
1934 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001935 = DesignatedInitExpr::Create(Context,
1936 Designators.data(), Designators.size(),
1937 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001938 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001939 return Owned(DIE);
1940}
Douglas Gregor85df8d82009-01-29 00:45:39 +00001941
Douglas Gregor723796a2009-12-16 06:35:08 +00001942bool Sema::CheckInitList(const InitializedEntity &Entity,
1943 InitListExpr *&InitList, QualType &DeclType) {
1944 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00001945 if (!CheckInitList.HadError())
1946 InitList = CheckInitList.getFullyStructuredList();
1947
1948 return CheckInitList.HadError();
1949}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00001950
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001951//===----------------------------------------------------------------------===//
1952// Initialization entity
1953//===----------------------------------------------------------------------===//
1954
Douglas Gregor723796a2009-12-16 06:35:08 +00001955InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1956 const InitializedEntity &Parent)
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001957 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00001958{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001959 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1960 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001961 Type = AT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001962 } else {
1963 Kind = EK_VectorElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001964 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001965 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001966}
1967
1968InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1969 CXXBaseSpecifier *Base)
1970{
1971 InitializedEntity Result;
1972 Result.Kind = EK_Base;
1973 Result.Base = Base;
Douglas Gregor1b303932009-12-22 15:35:07 +00001974 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001975 return Result;
1976}
1977
Douglas Gregor85dabae2009-12-16 01:38:02 +00001978DeclarationName InitializedEntity::getName() const {
1979 switch (getKind()) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00001980 case EK_Parameter:
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00001981 if (!VariableOrMember)
1982 return DeclarationName();
1983 // Fall through
1984
1985 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001986 case EK_Member:
1987 return VariableOrMember->getDeclName();
1988
1989 case EK_Result:
1990 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00001991 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001992 case EK_Temporary:
1993 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001994 case EK_ArrayElement:
1995 case EK_VectorElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001996 return DeclarationName();
1997 }
1998
1999 // Silence GCC warning
2000 return DeclarationName();
2001}
2002
Douglas Gregora4b592a2009-12-19 03:01:41 +00002003DeclaratorDecl *InitializedEntity::getDecl() const {
2004 switch (getKind()) {
2005 case EK_Variable:
2006 case EK_Parameter:
2007 case EK_Member:
2008 return VariableOrMember;
2009
2010 case EK_Result:
2011 case EK_Exception:
2012 case EK_New:
2013 case EK_Temporary:
2014 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002015 case EK_ArrayElement:
2016 case EK_VectorElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002017 return 0;
2018 }
2019
2020 // Silence GCC warning
2021 return 0;
2022}
2023
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002024//===----------------------------------------------------------------------===//
2025// Initialization sequence
2026//===----------------------------------------------------------------------===//
2027
2028void InitializationSequence::Step::Destroy() {
2029 switch (Kind) {
2030 case SK_ResolveAddressOfOverloadedFunction:
2031 case SK_CastDerivedToBaseRValue:
2032 case SK_CastDerivedToBaseLValue:
2033 case SK_BindReference:
2034 case SK_BindReferenceToTemporary:
2035 case SK_UserConversion:
2036 case SK_QualificationConversionRValue:
2037 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002038 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002039 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002040 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002041 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002042 case SK_StringInit:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002043 break;
2044
2045 case SK_ConversionSequence:
2046 delete ICS;
2047 }
2048}
2049
2050void InitializationSequence::AddAddressOverloadResolutionStep(
2051 FunctionDecl *Function) {
2052 Step S;
2053 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2054 S.Type = Function->getType();
2055 S.Function = Function;
2056 Steps.push_back(S);
2057}
2058
2059void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2060 bool IsLValue) {
2061 Step S;
2062 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
2063 S.Type = BaseType;
2064 Steps.push_back(S);
2065}
2066
2067void InitializationSequence::AddReferenceBindingStep(QualType T,
2068 bool BindingTemporary) {
2069 Step S;
2070 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2071 S.Type = T;
2072 Steps.push_back(S);
2073}
2074
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002075void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2076 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002077 Step S;
2078 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002079 S.Type = T;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002080 S.Function = Function;
2081 Steps.push_back(S);
2082}
2083
2084void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2085 bool IsLValue) {
2086 Step S;
2087 S.Kind = IsLValue? SK_QualificationConversionLValue
2088 : SK_QualificationConversionRValue;
2089 S.Type = Ty;
2090 Steps.push_back(S);
2091}
2092
2093void InitializationSequence::AddConversionSequenceStep(
2094 const ImplicitConversionSequence &ICS,
2095 QualType T) {
2096 Step S;
2097 S.Kind = SK_ConversionSequence;
2098 S.Type = T;
2099 S.ICS = new ImplicitConversionSequence(ICS);
2100 Steps.push_back(S);
2101}
2102
Douglas Gregor51e77d52009-12-10 17:56:55 +00002103void InitializationSequence::AddListInitializationStep(QualType T) {
2104 Step S;
2105 S.Kind = SK_ListInitialization;
2106 S.Type = T;
2107 Steps.push_back(S);
2108}
2109
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002110void
2111InitializationSequence::AddConstructorInitializationStep(
2112 CXXConstructorDecl *Constructor,
2113 QualType T) {
2114 Step S;
2115 S.Kind = SK_ConstructorInitialization;
2116 S.Type = T;
2117 S.Function = Constructor;
2118 Steps.push_back(S);
2119}
2120
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002121void InitializationSequence::AddZeroInitializationStep(QualType T) {
2122 Step S;
2123 S.Kind = SK_ZeroInitialization;
2124 S.Type = T;
2125 Steps.push_back(S);
2126}
2127
Douglas Gregore1314a62009-12-18 05:02:21 +00002128void InitializationSequence::AddCAssignmentStep(QualType T) {
2129 Step S;
2130 S.Kind = SK_CAssignment;
2131 S.Type = T;
2132 Steps.push_back(S);
2133}
2134
Eli Friedman78275202009-12-19 08:11:05 +00002135void InitializationSequence::AddStringInitStep(QualType T) {
2136 Step S;
2137 S.Kind = SK_StringInit;
2138 S.Type = T;
2139 Steps.push_back(S);
2140}
2141
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002142void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2143 OverloadingResult Result) {
2144 SequenceKind = FailedSequence;
2145 this->Failure = Failure;
2146 this->FailedOverloadResult = Result;
2147}
2148
2149//===----------------------------------------------------------------------===//
2150// Attempt initialization
2151//===----------------------------------------------------------------------===//
2152
2153/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregor51e77d52009-12-10 17:56:55 +00002154static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002155 const InitializedEntity &Entity,
2156 const InitializationKind &Kind,
2157 InitListExpr *InitList,
2158 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00002159 // FIXME: We only perform rudimentary checking of list
2160 // initializations at this point, then assume that any list
2161 // initialization of an array, aggregate, or scalar will be
2162 // well-formed. We we actually "perform" list initialization, we'll
2163 // do all of the necessary checking. C++0x initializer lists will
2164 // force us to perform more checking here.
2165 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2166
Douglas Gregor1b303932009-12-22 15:35:07 +00002167 QualType DestType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00002168
2169 // C++ [dcl.init]p13:
2170 // If T is a scalar type, then a declaration of the form
2171 //
2172 // T x = { a };
2173 //
2174 // is equivalent to
2175 //
2176 // T x = a;
2177 if (DestType->isScalarType()) {
2178 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2179 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2180 return;
2181 }
2182
2183 // Assume scalar initialization from a single value works.
2184 } else if (DestType->isAggregateType()) {
2185 // Assume aggregate initialization works.
2186 } else if (DestType->isVectorType()) {
2187 // Assume vector initialization works.
2188 } else if (DestType->isReferenceType()) {
2189 // FIXME: C++0x defines behavior for this.
2190 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2191 return;
2192 } else if (DestType->isRecordType()) {
2193 // FIXME: C++0x defines behavior for this
2194 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2195 }
2196
2197 // Add a general "list initialization" step.
2198 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002199}
2200
2201/// \brief Try a reference initialization that involves calling a conversion
2202/// function.
2203///
2204/// FIXME: look intos DRs 656, 896
2205static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2206 const InitializedEntity &Entity,
2207 const InitializationKind &Kind,
2208 Expr *Initializer,
2209 bool AllowRValues,
2210 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002211 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002212 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2213 QualType T1 = cv1T1.getUnqualifiedType();
2214 QualType cv2T2 = Initializer->getType();
2215 QualType T2 = cv2T2.getUnqualifiedType();
2216
2217 bool DerivedToBase;
2218 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2219 T1, T2, DerivedToBase) &&
2220 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002221 (void)DerivedToBase;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002222
2223 // Build the candidate set directly in the initialization sequence
2224 // structure, so that it will persist if we fail.
2225 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2226 CandidateSet.clear();
2227
2228 // Determine whether we are allowed to call explicit constructors or
2229 // explicit conversion operators.
2230 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2231
2232 const RecordType *T1RecordType = 0;
2233 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2234 // The type we're converting to is a class type. Enumerate its constructors
2235 // to see if there is a suitable conversion.
2236 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2237
2238 DeclarationName ConstructorName
2239 = S.Context.DeclarationNames.getCXXConstructorName(
2240 S.Context.getCanonicalType(T1).getUnqualifiedType());
2241 DeclContext::lookup_iterator Con, ConEnd;
2242 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2243 Con != ConEnd; ++Con) {
2244 // Find the constructor (which may be a template).
2245 CXXConstructorDecl *Constructor = 0;
2246 FunctionTemplateDecl *ConstructorTmpl
2247 = dyn_cast<FunctionTemplateDecl>(*Con);
2248 if (ConstructorTmpl)
2249 Constructor = cast<CXXConstructorDecl>(
2250 ConstructorTmpl->getTemplatedDecl());
2251 else
2252 Constructor = cast<CXXConstructorDecl>(*Con);
2253
2254 if (!Constructor->isInvalidDecl() &&
2255 Constructor->isConvertingConstructor(AllowExplicit)) {
2256 if (ConstructorTmpl)
2257 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2258 &Initializer, 1, CandidateSet);
2259 else
2260 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2261 }
2262 }
2263 }
2264
2265 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2266 // The type we're converting from is a class type, enumerate its conversion
2267 // functions.
2268 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2269
2270 // Determine the type we are converting to. If we are allowed to
2271 // convert to an rvalue, take the type that the destination type
2272 // refers to.
2273 QualType ToType = AllowRValues? cv1T1 : DestType;
2274
John McCallad371252010-01-20 00:46:10 +00002275 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002276 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002277 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2278 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002279 NamedDecl *D = *I;
2280 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2281 if (isa<UsingShadowDecl>(D))
2282 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2283
2284 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2285 CXXConversionDecl *Conv;
2286 if (ConvTemplate)
2287 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2288 else
2289 Conv = cast<CXXConversionDecl>(*I);
2290
2291 // If the conversion function doesn't return a reference type,
2292 // it can't be considered for this conversion unless we're allowed to
2293 // consider rvalues.
2294 // FIXME: Do we need to make sure that we only consider conversion
2295 // candidates with reference-compatible results? That might be needed to
2296 // break recursion.
2297 if ((AllowExplicit || !Conv->isExplicit()) &&
2298 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2299 if (ConvTemplate)
2300 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2301 ToType, CandidateSet);
2302 else
2303 S.AddConversionCandidate(Conv, ActingDC, Initializer, cv1T1,
2304 CandidateSet);
2305 }
2306 }
2307 }
2308
2309 SourceLocation DeclLoc = Initializer->getLocStart();
2310
2311 // Perform overload resolution. If it fails, return the failed result.
2312 OverloadCandidateSet::iterator Best;
2313 if (OverloadingResult Result
2314 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2315 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002316
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002317 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002318
2319 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002320 if (isa<CXXConversionDecl>(Function))
2321 T2 = Function->getResultType();
2322 else
2323 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002324
2325 // Add the user-defined conversion step.
2326 Sequence.AddUserConversionStep(Function, T2.getNonReferenceType());
2327
2328 // Determine whether we need to perform derived-to-base or
2329 // cv-qualification adjustments.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002330 bool NewDerivedToBase = false;
2331 Sema::ReferenceCompareResult NewRefRelationship
2332 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2333 NewDerivedToBase);
2334 assert(NewRefRelationship != Sema::Ref_Incompatible &&
2335 "Overload resolution picked a bad conversion function");
2336 (void)NewRefRelationship;
2337 if (NewDerivedToBase)
2338 Sequence.AddDerivedToBaseCastStep(
2339 S.Context.getQualifiedType(T1,
2340 T2.getNonReferenceType().getQualifiers()),
2341 /*isLValue=*/true);
2342
2343 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2344 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2345
2346 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2347 return OR_Success;
2348}
2349
2350/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2351static void TryReferenceInitialization(Sema &S,
2352 const InitializedEntity &Entity,
2353 const InitializationKind &Kind,
2354 Expr *Initializer,
2355 InitializationSequence &Sequence) {
2356 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2357
Douglas Gregor1b303932009-12-22 15:35:07 +00002358 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002359 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002360 Qualifiers T1Quals;
2361 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002362 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002363 Qualifiers T2Quals;
2364 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002365 SourceLocation DeclLoc = Initializer->getLocStart();
2366
2367 // If the initializer is the address of an overloaded function, try
2368 // to resolve the overloaded function. If all goes well, T2 is the
2369 // type of the resulting function.
2370 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2371 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2372 T1,
2373 false);
2374 if (!Fn) {
2375 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2376 return;
2377 }
2378
2379 Sequence.AddAddressOverloadResolutionStep(Fn);
2380 cv2T2 = Fn->getType();
2381 T2 = cv2T2.getUnqualifiedType();
2382 }
2383
2384 // FIXME: Rvalue references
2385 bool ForceRValue = false;
2386
2387 // Compute some basic properties of the types and the initializer.
2388 bool isLValueRef = DestType->isLValueReferenceType();
2389 bool isRValueRef = !isLValueRef;
2390 bool DerivedToBase = false;
2391 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2392 Initializer->isLvalue(S.Context);
2393 Sema::ReferenceCompareResult RefRelationship
2394 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2395
2396 // C++0x [dcl.init.ref]p5:
2397 // A reference to type "cv1 T1" is initialized by an expression of type
2398 // "cv2 T2" as follows:
2399 //
2400 // - If the reference is an lvalue reference and the initializer
2401 // expression
2402 OverloadingResult ConvOvlResult = OR_Success;
2403 if (isLValueRef) {
2404 if (InitLvalue == Expr::LV_Valid &&
2405 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2406 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2407 // reference-compatible with "cv2 T2," or
2408 //
2409 // Per C++ [over.best.ics]p2, we ignore whether the lvalue is a
2410 // bit-field when we're determining whether the reference initialization
2411 // can occur. This property will be checked by PerformInitialization.
2412 if (DerivedToBase)
2413 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002414 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002415 /*isLValue=*/true);
Chandler Carruth04bdce62010-01-12 20:32:25 +00002416 if (T1Quals != T2Quals)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002417 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
2418 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/false);
2419 return;
2420 }
2421
2422 // - has a class type (i.e., T2 is a class type), where T1 is not
2423 // reference-related to T2, and can be implicitly converted to an
2424 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2425 // with "cv3 T3" (this conversion is selected by enumerating the
2426 // applicable conversion functions (13.3.1.6) and choosing the best
2427 // one through overload resolution (13.3)),
2428 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2429 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2430 Initializer,
2431 /*AllowRValues=*/false,
2432 Sequence);
2433 if (ConvOvlResult == OR_Success)
2434 return;
John McCall0d1da222010-01-12 00:44:57 +00002435 if (ConvOvlResult != OR_No_Viable_Function) {
2436 Sequence.SetOverloadFailure(
2437 InitializationSequence::FK_ReferenceInitOverloadFailed,
2438 ConvOvlResult);
2439 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002440 }
2441 }
2442
2443 // - Otherwise, the reference shall be an lvalue reference to a
2444 // non-volatile const type (i.e., cv1 shall be const), or the reference
2445 // shall be an rvalue reference and the initializer expression shall
2446 // be an rvalue.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002447 if (!((isLValueRef && T1Quals.hasConst()) ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002448 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2449 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2450 Sequence.SetOverloadFailure(
2451 InitializationSequence::FK_ReferenceInitOverloadFailed,
2452 ConvOvlResult);
2453 else if (isLValueRef)
2454 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2455 ? (RefRelationship == Sema::Ref_Related
2456 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2457 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2458 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2459 else
2460 Sequence.SetFailed(
2461 InitializationSequence::FK_RValueReferenceBindingToLValue);
2462
2463 return;
2464 }
2465
2466 // - If T1 and T2 are class types and
2467 if (T1->isRecordType() && T2->isRecordType()) {
2468 // - the initializer expression is an rvalue and "cv1 T1" is
2469 // reference-compatible with "cv2 T2", or
2470 if (InitLvalue != Expr::LV_Valid &&
2471 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2472 if (DerivedToBase)
2473 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002474 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002475 /*isLValue=*/false);
Chandler Carruth04bdce62010-01-12 20:32:25 +00002476 if (T1Quals != T2Quals)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002477 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2478 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2479 return;
2480 }
2481
2482 // - T1 is not reference-related to T2 and the initializer expression
2483 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2484 // conversion is selected by enumerating the applicable conversion
2485 // functions (13.3.1.6) and choosing the best one through overload
2486 // resolution (13.3)),
2487 if (RefRelationship == Sema::Ref_Incompatible) {
2488 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2489 Kind, Initializer,
2490 /*AllowRValues=*/true,
2491 Sequence);
2492 if (ConvOvlResult)
2493 Sequence.SetOverloadFailure(
2494 InitializationSequence::FK_ReferenceInitOverloadFailed,
2495 ConvOvlResult);
2496
2497 return;
2498 }
2499
2500 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2501 return;
2502 }
2503
2504 // - If the initializer expression is an rvalue, with T2 an array type,
2505 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2506 // is bound to the object represented by the rvalue (see 3.10).
2507 // FIXME: How can an array type be reference-compatible with anything?
2508 // Don't we mean the element types of T1 and T2?
2509
2510 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2511 // from the initializer expression using the rules for a non-reference
2512 // copy initialization (8.5). The reference is then bound to the
2513 // temporary. [...]
2514 // Determine whether we are allowed to call explicit constructors or
2515 // explicit conversion operators.
2516 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2517 ImplicitConversionSequence ICS
2518 = S.TryImplicitConversion(Initializer, cv1T1,
2519 /*SuppressUserConversions=*/false, AllowExplicit,
2520 /*ForceRValue=*/false,
2521 /*FIXME:InOverloadResolution=*/false,
2522 /*UserCast=*/Kind.isExplicitCast());
2523
John McCall0d1da222010-01-12 00:44:57 +00002524 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002525 // FIXME: Use the conversion function set stored in ICS to turn
2526 // this into an overloading ambiguity diagnostic. However, we need
2527 // to keep that set as an OverloadCandidateSet rather than as some
2528 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002529 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2530 Sequence.SetOverloadFailure(
2531 InitializationSequence::FK_ReferenceInitOverloadFailed,
2532 ConvOvlResult);
2533 else
2534 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002535 return;
2536 }
2537
2538 // [...] If T1 is reference-related to T2, cv1 must be the
2539 // same cv-qualification as, or greater cv-qualification
2540 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002541 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2542 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002543 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00002544 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002545 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2546 return;
2547 }
2548
2549 // Perform the actual conversion.
2550 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2551 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2552 return;
2553}
2554
2555/// \brief Attempt character array initialization from a string literal
2556/// (C++ [dcl.init.string], C99 6.7.8).
2557static void TryStringLiteralInitialization(Sema &S,
2558 const InitializedEntity &Entity,
2559 const InitializationKind &Kind,
2560 Expr *Initializer,
2561 InitializationSequence &Sequence) {
Eli Friedman78275202009-12-19 08:11:05 +00002562 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregor1b303932009-12-22 15:35:07 +00002563 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002564}
2565
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002566/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2567/// enumerates the constructors of the initialized entity and performs overload
2568/// resolution to select the best.
2569static void TryConstructorInitialization(Sema &S,
2570 const InitializedEntity &Entity,
2571 const InitializationKind &Kind,
2572 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002573 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002574 InitializationSequence &Sequence) {
Douglas Gregore1314a62009-12-18 05:02:21 +00002575 if (Kind.getKind() == InitializationKind::IK_Copy)
2576 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2577 else
2578 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002579
2580 // Build the candidate set directly in the initialization sequence
2581 // structure, so that it will persist if we fail.
2582 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2583 CandidateSet.clear();
2584
2585 // Determine whether we are allowed to call explicit constructors or
2586 // explicit conversion operators.
2587 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2588 Kind.getKind() == InitializationKind::IK_Value ||
2589 Kind.getKind() == InitializationKind::IK_Default);
2590
2591 // The type we're converting to is a class type. Enumerate its constructors
2592 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002593 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2594 assert(DestRecordType && "Constructor initialization requires record type");
2595 CXXRecordDecl *DestRecordDecl
2596 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2597
2598 DeclarationName ConstructorName
2599 = S.Context.DeclarationNames.getCXXConstructorName(
2600 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2601 DeclContext::lookup_iterator Con, ConEnd;
2602 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2603 Con != ConEnd; ++Con) {
2604 // Find the constructor (which may be a template).
2605 CXXConstructorDecl *Constructor = 0;
2606 FunctionTemplateDecl *ConstructorTmpl
2607 = dyn_cast<FunctionTemplateDecl>(*Con);
2608 if (ConstructorTmpl)
2609 Constructor = cast<CXXConstructorDecl>(
2610 ConstructorTmpl->getTemplatedDecl());
2611 else
2612 Constructor = cast<CXXConstructorDecl>(*Con);
2613
2614 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002615 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002616 if (ConstructorTmpl)
2617 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2618 Args, NumArgs, CandidateSet);
2619 else
2620 S.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2621 }
2622 }
2623
2624 SourceLocation DeclLoc = Kind.getLocation();
2625
2626 // Perform overload resolution. If it fails, return the failed result.
2627 OverloadCandidateSet::iterator Best;
2628 if (OverloadingResult Result
2629 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2630 Sequence.SetOverloadFailure(
2631 InitializationSequence::FK_ConstructorOverloadFailed,
2632 Result);
2633 return;
2634 }
2635
2636 // Add the constructor initialization step. Any cv-qualification conversion is
2637 // subsumed by the initialization.
Douglas Gregore1314a62009-12-18 05:02:21 +00002638 if (Kind.getKind() == InitializationKind::IK_Copy) {
2639 Sequence.AddUserConversionStep(Best->Function, DestType);
2640 } else {
2641 Sequence.AddConstructorInitializationStep(
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002642 cast<CXXConstructorDecl>(Best->Function),
Douglas Gregore1314a62009-12-18 05:02:21 +00002643 DestType);
2644 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002645}
2646
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002647/// \brief Attempt value initialization (C++ [dcl.init]p7).
2648static void TryValueInitialization(Sema &S,
2649 const InitializedEntity &Entity,
2650 const InitializationKind &Kind,
2651 InitializationSequence &Sequence) {
2652 // C++ [dcl.init]p5:
2653 //
2654 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00002655 QualType T = Entity.getType();
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002656
2657 // -- if T is an array type, then each element is value-initialized;
2658 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2659 T = AT->getElementType();
2660
2661 if (const RecordType *RT = T->getAs<RecordType>()) {
2662 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2663 // -- if T is a class type (clause 9) with a user-declared
2664 // constructor (12.1), then the default constructor for T is
2665 // called (and the initialization is ill-formed if T has no
2666 // accessible default constructor);
2667 //
2668 // FIXME: we really want to refer to a single subobject of the array,
2669 // but Entity doesn't have a way to capture that (yet).
2670 if (ClassDecl->hasUserDeclaredConstructor())
2671 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2672
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002673 // -- if T is a (possibly cv-qualified) non-union class type
2674 // without a user-provided constructor, then the object is
2675 // zero-initialized and, if T’s implicitly-declared default
2676 // constructor is non-trivial, that constructor is called.
2677 if ((ClassDecl->getTagKind() == TagDecl::TK_class ||
2678 ClassDecl->getTagKind() == TagDecl::TK_struct) &&
2679 !ClassDecl->hasTrivialConstructor()) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002680 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002681 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2682 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002683 }
2684 }
2685
Douglas Gregor1b303932009-12-22 15:35:07 +00002686 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002687 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2688}
2689
Douglas Gregor85dabae2009-12-16 01:38:02 +00002690/// \brief Attempt default initialization (C++ [dcl.init]p6).
2691static void TryDefaultInitialization(Sema &S,
2692 const InitializedEntity &Entity,
2693 const InitializationKind &Kind,
2694 InitializationSequence &Sequence) {
2695 assert(Kind.getKind() == InitializationKind::IK_Default);
2696
2697 // C++ [dcl.init]p6:
2698 // To default-initialize an object of type T means:
2699 // - if T is an array type, each element is default-initialized;
Douglas Gregor1b303932009-12-22 15:35:07 +00002700 QualType DestType = Entity.getType();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002701 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2702 DestType = Array->getElementType();
2703
2704 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2705 // constructor for T is called (and the initialization is ill-formed if
2706 // T has no accessible default constructor);
2707 if (DestType->isRecordType()) {
2708 // FIXME: If a program calls for the default initialization of an object of
2709 // a const-qualified type T, T shall be a class type with a user-provided
2710 // default constructor.
2711 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2712 Sequence);
2713 }
2714
2715 // - otherwise, no initialization is performed.
2716 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2717
2718 // If a program calls for the default initialization of an object of
2719 // a const-qualified type T, T shall be a class type with a user-provided
2720 // default constructor.
2721 if (DestType.isConstQualified())
2722 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2723}
2724
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002725/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2726/// which enumerates all conversion functions and performs overload resolution
2727/// to select the best.
2728static void TryUserDefinedConversion(Sema &S,
2729 const InitializedEntity &Entity,
2730 const InitializationKind &Kind,
2731 Expr *Initializer,
2732 InitializationSequence &Sequence) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002733 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2734
Douglas Gregor1b303932009-12-22 15:35:07 +00002735 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002736 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2737 QualType SourceType = Initializer->getType();
2738 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2739 "Must have a class type to perform a user-defined conversion");
2740
2741 // Build the candidate set directly in the initialization sequence
2742 // structure, so that it will persist if we fail.
2743 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2744 CandidateSet.clear();
2745
2746 // Determine whether we are allowed to call explicit constructors or
2747 // explicit conversion operators.
2748 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2749
2750 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2751 // The type we're converting to is a class type. Enumerate its constructors
2752 // to see if there is a suitable conversion.
2753 CXXRecordDecl *DestRecordDecl
2754 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2755
2756 DeclarationName ConstructorName
2757 = S.Context.DeclarationNames.getCXXConstructorName(
2758 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2759 DeclContext::lookup_iterator Con, ConEnd;
2760 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2761 Con != ConEnd; ++Con) {
2762 // Find the constructor (which may be a template).
2763 CXXConstructorDecl *Constructor = 0;
2764 FunctionTemplateDecl *ConstructorTmpl
2765 = dyn_cast<FunctionTemplateDecl>(*Con);
2766 if (ConstructorTmpl)
2767 Constructor = cast<CXXConstructorDecl>(
2768 ConstructorTmpl->getTemplatedDecl());
2769 else
2770 Constructor = cast<CXXConstructorDecl>(*Con);
2771
2772 if (!Constructor->isInvalidDecl() &&
2773 Constructor->isConvertingConstructor(AllowExplicit)) {
2774 if (ConstructorTmpl)
2775 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2776 &Initializer, 1, CandidateSet);
2777 else
2778 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2779 }
2780 }
2781 }
Eli Friedman78275202009-12-19 08:11:05 +00002782
2783 SourceLocation DeclLoc = Initializer->getLocStart();
2784
Douglas Gregor540c3b02009-12-14 17:27:33 +00002785 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2786 // The type we're converting from is a class type, enumerate its conversion
2787 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00002788
Eli Friedman4afe9a32009-12-20 22:12:03 +00002789 // We can only enumerate the conversion functions for a complete type; if
2790 // the type isn't complete, simply skip this step.
2791 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2792 CXXRecordDecl *SourceRecordDecl
2793 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002794
John McCallad371252010-01-20 00:46:10 +00002795 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00002796 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002797 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman4afe9a32009-12-20 22:12:03 +00002798 E = Conversions->end();
2799 I != E; ++I) {
2800 NamedDecl *D = *I;
2801 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2802 if (isa<UsingShadowDecl>(D))
2803 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2804
2805 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2806 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00002807 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00002808 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002809 else
Eli Friedman4afe9a32009-12-20 22:12:03 +00002810 Conv = cast<CXXConversionDecl>(*I);
2811
2812 if (AllowExplicit || !Conv->isExplicit()) {
2813 if (ConvTemplate)
2814 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC,
2815 Initializer, DestType,
2816 CandidateSet);
2817 else
2818 S.AddConversionCandidate(Conv, ActingDC, Initializer, DestType,
2819 CandidateSet);
2820 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002821 }
2822 }
2823 }
2824
Douglas Gregor540c3b02009-12-14 17:27:33 +00002825 // Perform overload resolution. If it fails, return the failed result.
2826 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00002827 if (OverloadingResult Result
Douglas Gregor540c3b02009-12-14 17:27:33 +00002828 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2829 Sequence.SetOverloadFailure(
2830 InitializationSequence::FK_UserConversionOverloadFailed,
2831 Result);
2832 return;
2833 }
John McCall0d1da222010-01-12 00:44:57 +00002834
Douglas Gregor540c3b02009-12-14 17:27:33 +00002835 FunctionDecl *Function = Best->Function;
2836
2837 if (isa<CXXConstructorDecl>(Function)) {
2838 // Add the user-defined conversion step. Any cv-qualification conversion is
2839 // subsumed by the initialization.
2840 Sequence.AddUserConversionStep(Function, DestType);
2841 return;
2842 }
2843
2844 // Add the user-defined conversion step that calls the conversion function.
2845 QualType ConvType = Function->getResultType().getNonReferenceType();
2846 Sequence.AddUserConversionStep(Function, ConvType);
2847
2848 // If the conversion following the call to the conversion function is
2849 // interesting, add it as a separate step.
2850 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2851 Best->FinalConversion.Third) {
2852 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00002853 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002854 ICS.Standard = Best->FinalConversion;
2855 Sequence.AddConversionSequenceStep(ICS, DestType);
2856 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002857}
2858
2859/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2860/// non-class type to another.
2861static void TryImplicitConversion(Sema &S,
2862 const InitializedEntity &Entity,
2863 const InitializationKind &Kind,
2864 Expr *Initializer,
2865 InitializationSequence &Sequence) {
2866 ImplicitConversionSequence ICS
Douglas Gregor1b303932009-12-22 15:35:07 +00002867 = S.TryImplicitConversion(Initializer, Entity.getType(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002868 /*SuppressUserConversions=*/true,
2869 /*AllowExplicit=*/false,
2870 /*ForceRValue=*/false,
2871 /*FIXME:InOverloadResolution=*/false,
2872 /*UserCast=*/Kind.isExplicitCast());
2873
John McCall0d1da222010-01-12 00:44:57 +00002874 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002875 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2876 return;
2877 }
2878
Douglas Gregor1b303932009-12-22 15:35:07 +00002879 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002880}
2881
2882InitializationSequence::InitializationSequence(Sema &S,
2883 const InitializedEntity &Entity,
2884 const InitializationKind &Kind,
2885 Expr **Args,
2886 unsigned NumArgs) {
2887 ASTContext &Context = S.Context;
2888
2889 // C++0x [dcl.init]p16:
2890 // The semantics of initializers are as follows. The destination type is
2891 // the type of the object or reference being initialized and the source
2892 // type is the type of the initializer expression. The source type is not
2893 // defined when the initializer is a braced-init-list or when it is a
2894 // parenthesized list of expressions.
Douglas Gregor1b303932009-12-22 15:35:07 +00002895 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002896
2897 if (DestType->isDependentType() ||
2898 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2899 SequenceKind = DependentSequence;
2900 return;
2901 }
2902
2903 QualType SourceType;
2904 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00002905 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002906 Initializer = Args[0];
2907 if (!isa<InitListExpr>(Initializer))
2908 SourceType = Initializer->getType();
2909 }
2910
2911 // - If the initializer is a braced-init-list, the object is
2912 // list-initialized (8.5.4).
2913 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2914 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00002915 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002916 }
2917
2918 // - If the destination type is a reference type, see 8.5.3.
2919 if (DestType->isReferenceType()) {
2920 // C++0x [dcl.init.ref]p1:
2921 // A variable declared to be a T& or T&&, that is, "reference to type T"
2922 // (8.3.2), shall be initialized by an object, or function, of type T or
2923 // by an object that can be converted into a T.
2924 // (Therefore, multiple arguments are not permitted.)
2925 if (NumArgs != 1)
2926 SetFailed(FK_TooManyInitsForReference);
2927 else
2928 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2929 return;
2930 }
2931
2932 // - If the destination type is an array of characters, an array of
2933 // char16_t, an array of char32_t, or an array of wchar_t, and the
2934 // initializer is a string literal, see 8.5.2.
2935 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2936 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2937 return;
2938 }
2939
2940 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002941 if (Kind.getKind() == InitializationKind::IK_Value ||
2942 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002943 TryValueInitialization(S, Entity, Kind, *this);
2944 return;
2945 }
2946
Douglas Gregor85dabae2009-12-16 01:38:02 +00002947 // Handle default initialization.
2948 if (Kind.getKind() == InitializationKind::IK_Default){
2949 TryDefaultInitialization(S, Entity, Kind, *this);
2950 return;
2951 }
Douglas Gregore1314a62009-12-18 05:02:21 +00002952
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002953 // - Otherwise, if the destination type is an array, the program is
2954 // ill-formed.
2955 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2956 if (AT->getElementType()->isAnyCharacterType())
2957 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2958 else
2959 SetFailed(FK_ArrayNeedsInitList);
2960
2961 return;
2962 }
Eli Friedman78275202009-12-19 08:11:05 +00002963
2964 // Handle initialization in C
2965 if (!S.getLangOptions().CPlusPlus) {
2966 setSequenceKind(CAssignment);
2967 AddCAssignmentStep(DestType);
2968 return;
2969 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002970
2971 // - If the destination type is a (possibly cv-qualified) class type:
2972 if (DestType->isRecordType()) {
2973 // - If the initialization is direct-initialization, or if it is
2974 // copy-initialization where the cv-unqualified version of the
2975 // source type is the same class as, or a derived class of, the
2976 // class of the destination, constructors are considered. [...]
2977 if (Kind.getKind() == InitializationKind::IK_Direct ||
2978 (Kind.getKind() == InitializationKind::IK_Copy &&
2979 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2980 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002981 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregor1b303932009-12-22 15:35:07 +00002982 Entity.getType(), *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002983 // - Otherwise (i.e., for the remaining copy-initialization cases),
2984 // user-defined conversion sequences that can convert from the source
2985 // type to the destination type or (when a conversion function is
2986 // used) to a derived class thereof are enumerated as described in
2987 // 13.3.1.4, and the best one is chosen through overload resolution
2988 // (13.3).
2989 else
2990 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2991 return;
2992 }
2993
Douglas Gregor85dabae2009-12-16 01:38:02 +00002994 if (NumArgs > 1) {
2995 SetFailed(FK_TooManyInitsForScalar);
2996 return;
2997 }
2998 assert(NumArgs == 1 && "Zero-argument case handled above");
2999
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003000 // - Otherwise, if the source type is a (possibly cv-qualified) class
3001 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003002 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003003 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3004 return;
3005 }
3006
3007 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00003008 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003009 // conversions (Clause 4) will be used, if necessary, to convert the
3010 // initializer expression to the cv-unqualified version of the
3011 // destination type; no user-defined conversions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003012 setSequenceKind(StandardConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003013 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
3014}
3015
3016InitializationSequence::~InitializationSequence() {
3017 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3018 StepEnd = Steps.end();
3019 Step != StepEnd; ++Step)
3020 Step->Destroy();
3021}
3022
3023//===----------------------------------------------------------------------===//
3024// Perform initialization
3025//===----------------------------------------------------------------------===//
Douglas Gregore1314a62009-12-18 05:02:21 +00003026static Sema::AssignmentAction
3027getAssignmentAction(const InitializedEntity &Entity) {
3028 switch(Entity.getKind()) {
3029 case InitializedEntity::EK_Variable:
3030 case InitializedEntity::EK_New:
3031 return Sema::AA_Initializing;
3032
3033 case InitializedEntity::EK_Parameter:
3034 // FIXME: Can we tell when we're sending vs. passing?
3035 return Sema::AA_Passing;
3036
3037 case InitializedEntity::EK_Result:
3038 return Sema::AA_Returning;
3039
3040 case InitializedEntity::EK_Exception:
3041 case InitializedEntity::EK_Base:
3042 llvm_unreachable("No assignment action for C++-specific initialization");
3043 break;
3044
3045 case InitializedEntity::EK_Temporary:
3046 // FIXME: Can we tell apart casting vs. converting?
3047 return Sema::AA_Casting;
3048
3049 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003050 case InitializedEntity::EK_ArrayElement:
3051 case InitializedEntity::EK_VectorElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003052 return Sema::AA_Initializing;
3053 }
3054
3055 return Sema::AA_Converting;
3056}
3057
3058static bool shouldBindAsTemporary(const InitializedEntity &Entity,
3059 bool IsCopy) {
3060 switch (Entity.getKind()) {
3061 case InitializedEntity::EK_Result:
3062 case InitializedEntity::EK_Exception:
3063 return !IsCopy;
3064
3065 case InitializedEntity::EK_New:
3066 case InitializedEntity::EK_Variable:
3067 case InitializedEntity::EK_Base:
3068 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003069 case InitializedEntity::EK_ArrayElement:
3070 case InitializedEntity::EK_VectorElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003071 return false;
3072
3073 case InitializedEntity::EK_Parameter:
3074 case InitializedEntity::EK_Temporary:
3075 return true;
3076 }
3077
3078 llvm_unreachable("missed an InitializedEntity kind?");
3079}
3080
3081/// \brief If we need to perform an additional copy of the initialized object
3082/// for this kind of entity (e.g., the result of a function or an object being
3083/// thrown), make the copy.
3084static Sema::OwningExprResult CopyIfRequiredForEntity(Sema &S,
3085 const InitializedEntity &Entity,
Douglas Gregora4b592a2009-12-19 03:01:41 +00003086 const InitializationKind &Kind,
Douglas Gregore1314a62009-12-18 05:02:21 +00003087 Sema::OwningExprResult CurInit) {
3088 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003089
3090 switch (Entity.getKind()) {
3091 case InitializedEntity::EK_Result:
Douglas Gregor1b303932009-12-22 15:35:07 +00003092 if (Entity.getType()->isReferenceType())
Douglas Gregore1314a62009-12-18 05:02:21 +00003093 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003094 Loc = Entity.getReturnLoc();
3095 break;
3096
3097 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003098 Loc = Entity.getThrowLoc();
3099 break;
3100
3101 case InitializedEntity::EK_Variable:
Douglas Gregor1b303932009-12-22 15:35:07 +00003102 if (Entity.getType()->isReferenceType() ||
Douglas Gregora4b592a2009-12-19 03:01:41 +00003103 Kind.getKind() != InitializationKind::IK_Copy)
3104 return move(CurInit);
3105 Loc = Entity.getDecl()->getLocation();
3106 break;
3107
Douglas Gregore1314a62009-12-18 05:02:21 +00003108 case InitializedEntity::EK_Parameter:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003109 // FIXME: Do we need this initialization for a parameter?
3110 return move(CurInit);
3111
Douglas Gregore1314a62009-12-18 05:02:21 +00003112 case InitializedEntity::EK_New:
3113 case InitializedEntity::EK_Temporary:
3114 case InitializedEntity::EK_Base:
3115 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003116 case InitializedEntity::EK_ArrayElement:
3117 case InitializedEntity::EK_VectorElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003118 // We don't need to copy for any of these initialized entities.
3119 return move(CurInit);
3120 }
3121
3122 Expr *CurInitExpr = (Expr *)CurInit.get();
3123 CXXRecordDecl *Class = 0;
3124 if (const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>())
3125 Class = cast<CXXRecordDecl>(Record->getDecl());
3126 if (!Class)
3127 return move(CurInit);
3128
3129 // Perform overload resolution using the class's copy constructors.
3130 DeclarationName ConstructorName
3131 = S.Context.DeclarationNames.getCXXConstructorName(
3132 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
3133 DeclContext::lookup_iterator Con, ConEnd;
3134 OverloadCandidateSet CandidateSet;
3135 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
3136 Con != ConEnd; ++Con) {
3137 // Find the constructor (which may be a template).
3138 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3139 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor507eb872009-12-22 00:34:07 +00003140 !Constructor->isCopyConstructor())
Douglas Gregore1314a62009-12-18 05:02:21 +00003141 continue;
3142
3143 S.AddOverloadCandidate(Constructor, &CurInitExpr, 1, CandidateSet);
3144 }
3145
3146 OverloadCandidateSet::iterator Best;
3147 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3148 case OR_Success:
3149 break;
3150
3151 case OR_No_Viable_Function:
3152 S.Diag(Loc, diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003153 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003154 << CurInitExpr->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003155 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
3156 &CurInitExpr, 1);
Douglas Gregore1314a62009-12-18 05:02:21 +00003157 return S.ExprError();
3158
3159 case OR_Ambiguous:
3160 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003161 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003162 << CurInitExpr->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003163 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_ViableCandidates,
3164 &CurInitExpr, 1);
Douglas Gregore1314a62009-12-18 05:02:21 +00003165 return S.ExprError();
3166
3167 case OR_Deleted:
3168 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003169 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003170 << CurInitExpr->getSourceRange();
3171 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3172 << Best->Function->isDeleted();
3173 return S.ExprError();
3174 }
3175
3176 CurInit.release();
3177 return S.BuildCXXConstructExpr(Loc, CurInitExpr->getType(),
3178 cast<CXXConstructorDecl>(Best->Function),
3179 /*Elidable=*/true,
3180 Sema::MultiExprArg(S,
3181 (void**)&CurInitExpr, 1));
3182}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003183
3184Action::OwningExprResult
3185InitializationSequence::Perform(Sema &S,
3186 const InitializedEntity &Entity,
3187 const InitializationKind &Kind,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003188 Action::MultiExprArg Args,
3189 QualType *ResultType) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003190 if (SequenceKind == FailedSequence) {
3191 unsigned NumArgs = Args.size();
3192 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3193 return S.ExprError();
3194 }
3195
3196 if (SequenceKind == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003197 // If the declaration is a non-dependent, incomplete array type
3198 // that has an initializer, then its type will be completed once
3199 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00003200 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00003201 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003202 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003203 if (const IncompleteArrayType *ArrayT
3204 = S.Context.getAsIncompleteArrayType(DeclType)) {
3205 // FIXME: We don't currently have the ability to accurately
3206 // compute the length of an initializer list without
3207 // performing full type-checking of the initializer list
3208 // (since we have to determine where braces are implicitly
3209 // introduced and such). So, we fall back to making the array
3210 // type a dependently-sized array type with no specified
3211 // bound.
3212 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3213 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00003214
Douglas Gregor51e77d52009-12-10 17:56:55 +00003215 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00003216 if (DeclaratorDecl *DD = Entity.getDecl()) {
3217 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3218 TypeLoc TL = TInfo->getTypeLoc();
3219 if (IncompleteArrayTypeLoc *ArrayLoc
3220 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3221 Brackets = ArrayLoc->getBracketsRange();
3222 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00003223 }
3224
3225 *ResultType
3226 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3227 /*NumElts=*/0,
3228 ArrayT->getSizeModifier(),
3229 ArrayT->getIndexTypeCVRQualifiers(),
3230 Brackets);
3231 }
3232
3233 }
3234 }
3235
Eli Friedmana553d4a2009-12-22 02:35:53 +00003236 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003237 return Sema::OwningExprResult(S, Args.release()[0]);
3238
3239 unsigned NumArgs = Args.size();
3240 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3241 SourceLocation(),
3242 (Expr **)Args.release(),
3243 NumArgs,
3244 SourceLocation()));
3245 }
3246
Douglas Gregor85dabae2009-12-16 01:38:02 +00003247 if (SequenceKind == NoInitialization)
3248 return S.Owned((Expr *)0);
3249
Douglas Gregor1b303932009-12-22 15:35:07 +00003250 QualType DestType = Entity.getType().getNonReferenceType();
3251 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00003252 // the same as Entity.getDecl()->getType() in cases involving type merging,
3253 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003254 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003255 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00003256 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003257
Douglas Gregor85dabae2009-12-16 01:38:02 +00003258 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3259
3260 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3261
3262 // For initialization steps that start with a single initializer,
3263 // grab the only argument out the Args and place it into the "current"
3264 // initializer.
3265 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003266 case SK_ResolveAddressOfOverloadedFunction:
3267 case SK_CastDerivedToBaseRValue:
3268 case SK_CastDerivedToBaseLValue:
3269 case SK_BindReference:
3270 case SK_BindReferenceToTemporary:
3271 case SK_UserConversion:
3272 case SK_QualificationConversionLValue:
3273 case SK_QualificationConversionRValue:
3274 case SK_ConversionSequence:
3275 case SK_ListInitialization:
3276 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003277 case SK_StringInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00003278 assert(Args.size() == 1);
3279 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3280 if (CurInit.isInvalid())
3281 return S.ExprError();
3282 break;
3283
3284 case SK_ConstructorInitialization:
3285 case SK_ZeroInitialization:
3286 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003287 }
3288
3289 // Walk through the computed steps for the initialization sequence,
3290 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003291 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003292 for (step_iterator Step = step_begin(), StepEnd = step_end();
3293 Step != StepEnd; ++Step) {
3294 if (CurInit.isInvalid())
3295 return S.ExprError();
3296
3297 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003298 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003299
3300 switch (Step->Kind) {
3301 case SK_ResolveAddressOfOverloadedFunction:
3302 // Overload resolution determined which function invoke; update the
3303 // initializer to reflect that choice.
3304 CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function);
3305 break;
3306
3307 case SK_CastDerivedToBaseRValue:
3308 case SK_CastDerivedToBaseLValue: {
3309 // We have a derived-to-base cast that produces either an rvalue or an
3310 // lvalue. Perform that cast.
3311
3312 // Casts to inaccessible base classes are allowed with C-style casts.
3313 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3314 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3315 CurInitExpr->getLocStart(),
3316 CurInitExpr->getSourceRange(),
3317 IgnoreBaseAccess))
3318 return S.ExprError();
3319
3320 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3321 CastExpr::CK_DerivedToBase,
3322 (Expr*)CurInit.release(),
3323 Step->Kind == SK_CastDerivedToBaseLValue));
3324 break;
3325 }
3326
3327 case SK_BindReference:
3328 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3329 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3330 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00003331 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003332 << BitField->getDeclName()
3333 << CurInitExpr->getSourceRange();
3334 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3335 return S.ExprError();
3336 }
3337
3338 // Reference binding does not have any corresponding ASTs.
3339
3340 // Check exception specifications
3341 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3342 return S.ExprError();
3343 break;
3344
3345 case SK_BindReferenceToTemporary:
3346 // Check exception specifications
3347 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3348 return S.ExprError();
3349
3350 // FIXME: At present, we have no AST to describe when we need to make a
3351 // temporary to bind a reference to. We should.
3352 break;
3353
3354 case SK_UserConversion: {
3355 // We have a user-defined conversion that invokes either a constructor
3356 // or a conversion function.
3357 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregore1314a62009-12-18 05:02:21 +00003358 bool IsCopy = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003359 if (CXXConstructorDecl *Constructor
3360 = dyn_cast<CXXConstructorDecl>(Step->Function)) {
3361 // Build a call to the selected constructor.
3362 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3363 SourceLocation Loc = CurInitExpr->getLocStart();
3364 CurInit.release(); // Ownership transferred into MultiExprArg, below.
3365
3366 // Determine the arguments required to actually perform the constructor
3367 // call.
3368 if (S.CompleteConstructorCall(Constructor,
3369 Sema::MultiExprArg(S,
3370 (void **)&CurInitExpr,
3371 1),
3372 Loc, ConstructorArgs))
3373 return S.ExprError();
3374
3375 // Build the an expression that constructs a temporary.
3376 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3377 move_arg(ConstructorArgs));
3378 if (CurInit.isInvalid())
3379 return S.ExprError();
3380
3381 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00003382 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3383 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3384 S.IsDerivedFrom(SourceType, Class))
3385 IsCopy = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003386 } else {
3387 // Build a call to the conversion function.
3388 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function);
Douglas Gregore1314a62009-12-18 05:02:21 +00003389
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003390 // FIXME: Should we move this initialization into a separate
3391 // derived-to-base conversion? I believe the answer is "no", because
3392 // we don't want to turn off access control here for c-style casts.
3393 if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion))
3394 return S.ExprError();
3395
3396 // Do a little dance to make sure that CurInit has the proper
3397 // pointer.
3398 CurInit.release();
3399
3400 // Build the actual call to the conversion function.
3401 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3402 if (CurInit.isInvalid() || !CurInit.get())
3403 return S.ExprError();
3404
3405 CastKind = CastExpr::CK_UserDefinedConversion;
3406 }
3407
Douglas Gregore1314a62009-12-18 05:02:21 +00003408 if (shouldBindAsTemporary(Entity, IsCopy))
3409 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3410
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003411 CurInitExpr = CurInit.takeAs<Expr>();
3412 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3413 CastKind,
3414 CurInitExpr,
Douglas Gregore1314a62009-12-18 05:02:21 +00003415 false));
3416
3417 if (!IsCopy)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003418 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003419 break;
3420 }
3421
3422 case SK_QualificationConversionLValue:
3423 case SK_QualificationConversionRValue:
3424 // Perform a qualification conversion; these can never go wrong.
3425 S.ImpCastExprToType(CurInitExpr, Step->Type,
3426 CastExpr::CK_NoOp,
3427 Step->Kind == SK_QualificationConversionLValue);
3428 CurInit.release();
3429 CurInit = S.Owned(CurInitExpr);
3430 break;
3431
3432 case SK_ConversionSequence:
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003433 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003434 false, false, *Step->ICS))
3435 return S.ExprError();
3436
3437 CurInit.release();
3438 CurInit = S.Owned(CurInitExpr);
3439 break;
Douglas Gregor51e77d52009-12-10 17:56:55 +00003440
3441 case SK_ListInitialization: {
3442 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3443 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00003444 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregor51e77d52009-12-10 17:56:55 +00003445 return S.ExprError();
3446
3447 CurInit.release();
3448 CurInit = S.Owned(InitList);
3449 break;
3450 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003451
3452 case SK_ConstructorInitialization: {
3453 CXXConstructorDecl *Constructor
3454 = cast<CXXConstructorDecl>(Step->Function);
3455
3456 // Build a call to the selected constructor.
3457 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3458 SourceLocation Loc = Kind.getLocation();
3459
3460 // Determine the arguments required to actually perform the constructor
3461 // call.
3462 if (S.CompleteConstructorCall(Constructor, move(Args),
3463 Loc, ConstructorArgs))
3464 return S.ExprError();
3465
3466 // Build the an expression that constructs a temporary.
Douglas Gregor1b303932009-12-22 15:35:07 +00003467 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
Douglas Gregor39c778b2009-12-20 22:01:25 +00003468 Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003469 move_arg(ConstructorArgs),
3470 ConstructorInitRequiresZeroInit);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003471 if (CurInit.isInvalid())
3472 return S.ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003473
3474 bool Elidable
3475 = cast<CXXConstructExpr>((Expr *)CurInit.get())->isElidable();
3476 if (shouldBindAsTemporary(Entity, Elidable))
3477 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3478
3479 if (!Elidable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003480 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003481 break;
3482 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003483
3484 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003485 step_iterator NextStep = Step;
3486 ++NextStep;
3487 if (NextStep != StepEnd &&
3488 NextStep->Kind == SK_ConstructorInitialization) {
3489 // The need for zero-initialization is recorded directly into
3490 // the call to the object's constructor within the next step.
3491 ConstructorInitRequiresZeroInit = true;
3492 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3493 S.getLangOptions().CPlusPlus &&
3494 !Kind.isImplicitValueInit()) {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003495 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3496 Kind.getRange().getBegin(),
3497 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003498 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003499 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003500 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003501 break;
3502 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003503
3504 case SK_CAssignment: {
3505 QualType SourceType = CurInitExpr->getType();
3506 Sema::AssignConvertType ConvTy =
3507 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregor96596c92009-12-22 07:24:36 +00003508
3509 // If this is a call, allow conversion to a transparent union.
3510 if (ConvTy != Sema::Compatible &&
3511 Entity.getKind() == InitializedEntity::EK_Parameter &&
3512 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3513 == Sema::Compatible)
3514 ConvTy = Sema::Compatible;
3515
Douglas Gregore1314a62009-12-18 05:02:21 +00003516 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3517 Step->Type, SourceType,
3518 CurInitExpr, getAssignmentAction(Entity)))
3519 return S.ExprError();
3520
3521 CurInit.release();
3522 CurInit = S.Owned(CurInitExpr);
3523 break;
3524 }
Eli Friedman78275202009-12-19 08:11:05 +00003525
3526 case SK_StringInit: {
3527 QualType Ty = Step->Type;
3528 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3529 break;
3530 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003531 }
3532 }
3533
3534 return move(CurInit);
3535}
3536
3537//===----------------------------------------------------------------------===//
3538// Diagnose initialization failures
3539//===----------------------------------------------------------------------===//
3540bool InitializationSequence::Diagnose(Sema &S,
3541 const InitializedEntity &Entity,
3542 const InitializationKind &Kind,
3543 Expr **Args, unsigned NumArgs) {
3544 if (SequenceKind != FailedSequence)
3545 return false;
3546
Douglas Gregor1b303932009-12-22 15:35:07 +00003547 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003548 switch (Failure) {
3549 case FK_TooManyInitsForReference:
3550 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3551 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
3552 break;
3553
3554 case FK_ArrayNeedsInitList:
3555 case FK_ArrayNeedsInitListOrStringLiteral:
3556 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3557 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3558 break;
3559
3560 case FK_AddressOfOverloadFailed:
3561 S.ResolveAddressOfOverloadedFunction(Args[0],
3562 DestType.getNonReferenceType(),
3563 true);
3564 break;
3565
3566 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00003567 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003568 switch (FailedOverloadResult) {
3569 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00003570 if (Failure == FK_UserConversionOverloadFailed)
3571 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3572 << Args[0]->getType() << DestType
3573 << Args[0]->getSourceRange();
3574 else
3575 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3576 << DestType << Args[0]->getType()
3577 << Args[0]->getSourceRange();
3578
John McCallad907772010-01-12 07:18:19 +00003579 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_ViableCandidates,
3580 Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003581 break;
3582
3583 case OR_No_Viable_Function:
3584 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3585 << Args[0]->getType() << DestType.getNonReferenceType()
3586 << Args[0]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003587 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3588 Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003589 break;
3590
3591 case OR_Deleted: {
3592 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3593 << Args[0]->getType() << DestType.getNonReferenceType()
3594 << Args[0]->getSourceRange();
3595 OverloadCandidateSet::iterator Best;
3596 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3597 Kind.getLocation(),
3598 Best);
3599 if (Ovl == OR_Deleted) {
3600 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3601 << Best->Function->isDeleted();
3602 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003603 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003604 }
3605 break;
3606 }
3607
3608 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003609 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003610 break;
3611 }
3612 break;
3613
3614 case FK_NonConstLValueReferenceBindingToTemporary:
3615 case FK_NonConstLValueReferenceBindingToUnrelated:
3616 S.Diag(Kind.getLocation(),
3617 Failure == FK_NonConstLValueReferenceBindingToTemporary
3618 ? diag::err_lvalue_reference_bind_to_temporary
3619 : diag::err_lvalue_reference_bind_to_unrelated)
3620 << DestType.getNonReferenceType()
3621 << Args[0]->getType()
3622 << Args[0]->getSourceRange();
3623 break;
3624
3625 case FK_RValueReferenceBindingToLValue:
3626 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3627 << Args[0]->getSourceRange();
3628 break;
3629
3630 case FK_ReferenceInitDropsQualifiers:
3631 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3632 << DestType.getNonReferenceType()
3633 << Args[0]->getType()
3634 << Args[0]->getSourceRange();
3635 break;
3636
3637 case FK_ReferenceInitFailed:
3638 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3639 << DestType.getNonReferenceType()
3640 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3641 << Args[0]->getType()
3642 << Args[0]->getSourceRange();
3643 break;
3644
3645 case FK_ConversionFailed:
Douglas Gregore1314a62009-12-18 05:02:21 +00003646 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
3647 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003648 << DestType
3649 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3650 << Args[0]->getType()
3651 << Args[0]->getSourceRange();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003652 break;
3653
3654 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003655 SourceRange R;
3656
3657 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3658 R = SourceRange(InitList->getInit(1)->getLocStart(),
3659 InitList->getLocEnd());
3660 else
3661 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00003662
3663 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor85dabae2009-12-16 01:38:02 +00003664 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00003665 break;
3666 }
3667
3668 case FK_ReferenceBindingToInitList:
3669 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3670 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3671 break;
3672
3673 case FK_InitListBadDestinationType:
3674 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3675 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3676 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003677
3678 case FK_ConstructorOverloadFailed: {
3679 SourceRange ArgsRange;
3680 if (NumArgs)
3681 ArgsRange = SourceRange(Args[0]->getLocStart(),
3682 Args[NumArgs - 1]->getLocEnd());
3683
3684 // FIXME: Using "DestType" for the entity we're printing is probably
3685 // bad.
3686 switch (FailedOverloadResult) {
3687 case OR_Ambiguous:
3688 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3689 << DestType << ArgsRange;
John McCall12f97bc2010-01-08 04:41:39 +00003690 S.PrintOverloadCandidates(FailedCandidateSet,
John McCallad907772010-01-12 07:18:19 +00003691 Sema::OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003692 break;
3693
3694 case OR_No_Viable_Function:
3695 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3696 << DestType << ArgsRange;
John McCallad907772010-01-12 07:18:19 +00003697 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3698 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003699 break;
3700
3701 case OR_Deleted: {
3702 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3703 << true << DestType << ArgsRange;
3704 OverloadCandidateSet::iterator Best;
3705 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3706 Kind.getLocation(),
3707 Best);
3708 if (Ovl == OR_Deleted) {
3709 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3710 << Best->Function->isDeleted();
3711 } else {
3712 llvm_unreachable("Inconsistent overload resolution?");
3713 }
3714 break;
3715 }
3716
3717 case OR_Success:
3718 llvm_unreachable("Conversion did not fail!");
3719 break;
3720 }
3721 break;
3722 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003723
3724 case FK_DefaultInitOfConst:
3725 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3726 << DestType;
3727 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003728 }
3729
3730 return true;
3731}
Douglas Gregore1314a62009-12-18 05:02:21 +00003732
3733//===----------------------------------------------------------------------===//
3734// Initialization helper functions
3735//===----------------------------------------------------------------------===//
3736Sema::OwningExprResult
3737Sema::PerformCopyInitialization(const InitializedEntity &Entity,
3738 SourceLocation EqualLoc,
3739 OwningExprResult Init) {
3740 if (Init.isInvalid())
3741 return ExprError();
3742
3743 Expr *InitE = (Expr *)Init.get();
3744 assert(InitE && "No initialization expression?");
3745
3746 if (EqualLoc.isInvalid())
3747 EqualLoc = InitE->getLocStart();
3748
3749 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
3750 EqualLoc);
3751 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
3752 Init.release();
3753 return Seq.Perform(*this, Entity, Kind,
3754 MultiExprArg(*this, (void**)&InitE, 1));
3755}