blob: f831b4151213da8c89d3e815172b5b20aec6a01e [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"
Steve Narofff8ecff22008-05-01 22:18:59 +000019#include "Sema.h"
Douglas Gregore4a0bb72009-01-22 00:58:24 +000020#include "clang/Parse/Designator.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000021#include "clang/AST/ASTContext.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000022#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000023#include "clang/AST/ExprObjC.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000024#include "llvm/Support/ErrorHandling.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000025#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000026using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000027
Chris Lattner0cb78032009-02-24 22:27:37 +000028//===----------------------------------------------------------------------===//
29// Sema Initialization Checking
30//===----------------------------------------------------------------------===//
31
Chris Lattnerd8b741c82009-02-24 23:10:27 +000032static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattnera9196812009-02-26 23:26:43 +000033 const ArrayType *AT = Context.getAsArrayType(DeclType);
34 if (!AT) return 0;
35
Eli Friedman893abe42009-05-29 18:22:49 +000036 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
37 return 0;
38
Chris Lattnera9196812009-02-26 23:26:43 +000039 // See if this is a string literal or @encode.
40 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000041
Chris Lattnera9196812009-02-26 23:26:43 +000042 // Handle @encode, which is a narrow string.
43 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
44 return Init;
45
46 // Otherwise we can only handle string literals.
47 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000048 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000049
50 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattnera9196812009-02-26 23:26:43 +000051 // char array can be initialized with a narrow string.
52 // Only allow char x[] = "foo"; not char x[] = L"foo";
53 if (!SL->isWide())
Eli Friedman42a84652009-05-31 10:54:53 +000054 return ElemTy->isCharType() ? Init : 0;
Chris Lattnera9196812009-02-26 23:26:43 +000055
Eli Friedman42a84652009-05-31 10:54:53 +000056 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
57 // correction from DR343): "An array with element type compatible with a
58 // qualified or unqualified version of wchar_t may be initialized by a wide
59 // string literal, optionally enclosed in braces."
60 if (Context.typesAreCompatible(Context.getWCharType(),
61 ElemTy.getUnqualifiedType()))
Chris Lattnera9196812009-02-26 23:26:43 +000062 return Init;
Mike Stump11289f42009-09-09 15:08:12 +000063
Chris Lattner0cb78032009-02-24 22:27:37 +000064 return 0;
65}
66
Mike Stump11289f42009-09-09 15:08:12 +000067static bool CheckSingleInitializer(Expr *&Init, QualType DeclType,
Chris Lattner94d2f682009-02-24 22:46:58 +000068 bool DirectInit, Sema &S) {
Chris Lattner0cb78032009-02-24 22:27:37 +000069 // Get the type before calling CheckSingleAssignmentConstraints(), since
70 // it can promote the expression.
Mike Stump11289f42009-09-09 15:08:12 +000071 QualType InitType = Init->getType();
72
Chris Lattner94d2f682009-02-24 22:46:58 +000073 if (S.getLangOptions().CPlusPlus) {
Chris Lattner0cb78032009-02-24 22:27:37 +000074 // FIXME: I dislike this error message. A lot.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +000075 if (S.PerformImplicitConversion(Init, DeclType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +000076 Sema::AA_Initializing, DirectInit)) {
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +000077 ImplicitConversionSequence ICS;
78 OverloadCandidateSet CandidateSet;
79 if (S.IsUserDefinedConversion(Init, DeclType, ICS.UserDefined,
80 CandidateSet,
Douglas Gregor3e1e5272009-12-09 23:02:17 +000081 true, false, false) != OR_Ambiguous)
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +000082 return S.Diag(Init->getSourceRange().getBegin(),
83 diag::err_typecheck_convert_incompatible)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +000084 << DeclType << Init->getType() << Sema::AA_Initializing
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +000085 << Init->getSourceRange();
86 S.Diag(Init->getSourceRange().getBegin(),
87 diag::err_typecheck_convert_ambiguous)
88 << DeclType << Init->getType() << Init->getSourceRange();
89 S.PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
90 return true;
91 }
Chris Lattner0cb78032009-02-24 22:27:37 +000092 return false;
93 }
Mike Stump11289f42009-09-09 15:08:12 +000094
Chris Lattner94d2f682009-02-24 22:46:58 +000095 Sema::AssignConvertType ConvTy =
96 S.CheckSingleAssignmentConstraints(DeclType, Init);
97 return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +000098 InitType, Init, Sema::AA_Initializing);
Chris Lattner0cb78032009-02-24 22:27:37 +000099}
100
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000101static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
102 // Get the length of the string as parsed.
103 uint64_t StrLength =
104 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
105
Mike Stump11289f42009-09-09 15:08:12 +0000106
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000107 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000108 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +0000109 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +0000110 // being initialized to a string literal.
111 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000112 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +0000113 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +0000114 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
115 ConstVal,
116 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000117 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000118 }
Mike Stump11289f42009-09-09 15:08:12 +0000119
Eli Friedman893abe42009-05-29 18:22:49 +0000120 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000121
Eli Friedman893abe42009-05-29 18:22:49 +0000122 // C99 6.7.8p14. We have an array of character type with known size. However,
123 // the size may be smaller or larger than the string we are initializing.
124 // FIXME: Avoid truncation for 64-bit length strings.
125 if (StrLength-1 > CAT->getSize().getZExtValue())
126 S.Diag(Str->getSourceRange().getBegin(),
127 diag::warn_initializer_string_for_char_array_too_long)
128 << Str->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +0000129
Eli Friedman893abe42009-05-29 18:22:49 +0000130 // Set the type to the actual size that we are initializing. If we have
131 // something like:
132 // char x[1] = "foo";
133 // then this will set the string literal's type to char[1].
134 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000135}
136
Chris Lattner0cb78032009-02-24 22:27:37 +0000137//===----------------------------------------------------------------------===//
138// Semantic checking for initializer lists.
139//===----------------------------------------------------------------------===//
140
Douglas Gregorcde232f2009-01-29 01:05:33 +0000141/// @brief Semantic checking for initializer lists.
142///
143/// The InitListChecker class contains a set of routines that each
144/// handle the initialization of a certain kind of entity, e.g.,
145/// arrays, vectors, struct/union types, scalars, etc. The
146/// InitListChecker itself performs a recursive walk of the subobject
147/// structure of the type to be initialized, while stepping through
148/// the initializer list one element at a time. The IList and Index
149/// parameters to each of the Check* routines contain the active
150/// (syntactic) initializer list and the index into that initializer
151/// list that represents the current initializer. Each routine is
152/// responsible for moving that Index forward as it consumes elements.
153///
154/// Each Check* routine also has a StructuredList/StructuredIndex
155/// arguments, which contains the current the "structured" (semantic)
156/// initializer list and the index into that initializer list where we
157/// are copying initializers as we map them over to the semantic
158/// list. Once we have completed our recursive walk of the subobject
159/// structure, we will have constructed a full semantic initializer
160/// list.
161///
162/// C99 designators cause changes in the initializer list traversal,
163/// because they make the initialization "jump" into a specific
164/// subobject and then continue the initialization from that
165/// point. CheckDesignatedInitializer() recursively steps into the
166/// designated subobject and manages backing out the recursion to
167/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000168namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000169class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000170 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000171 bool hadError;
172 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
173 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000174
175 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000176 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000177 unsigned &StructuredIndex,
178 bool TopLevelObject = false);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000179 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000180 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000181 unsigned &StructuredIndex,
182 bool TopLevelObject = false);
Mike Stump11289f42009-09-09 15:08:12 +0000183 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
184 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000185 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000186 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000187 unsigned &StructuredIndex,
188 bool TopLevelObject = false);
Mike Stump11289f42009-09-09 15:08:12 +0000189 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000190 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000191 InitListExpr *StructuredList,
192 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000193 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000194 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000195 InitListExpr *StructuredList,
196 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000197 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000198 unsigned &Index,
199 InitListExpr *StructuredList,
200 unsigned &StructuredIndex);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000201 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000202 InitListExpr *StructuredList,
203 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000204 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
205 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000206 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000207 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000208 unsigned &StructuredIndex,
209 bool TopLevelObject = false);
Mike Stump11289f42009-09-09 15:08:12 +0000210 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
211 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000212 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000213 InitListExpr *StructuredList,
214 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000215 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000216 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000217 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000218 RecordDecl::field_iterator *NextField,
219 llvm::APSInt *NextElementIndex,
220 unsigned &Index,
221 InitListExpr *StructuredList,
222 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000223 bool FinishSubobjectInit,
224 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000225 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
226 QualType CurrentObjectType,
227 InitListExpr *StructuredList,
228 unsigned StructuredIndex,
229 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000230 void UpdateStructuredListElement(InitListExpr *StructuredList,
231 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000232 Expr *expr);
233 int numArrayElements(QualType DeclType);
234 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000235
Douglas Gregor2bb07652009-12-22 00:05:34 +0000236 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
237 const InitializedEntity &ParentEntity,
238 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000239 void FillInValueInitializations(const InitializedEntity &Entity,
240 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000241public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000242 InitListChecker(Sema &S, const InitializedEntity &Entity,
243 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000244 bool HadError() { return hadError; }
245
246 // @brief Retrieves the fully-structured initializer list used for
247 // semantic analysis and code generation.
248 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
249};
Chris Lattner9ececce2009-02-24 22:48:58 +0000250} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000251
Douglas Gregor2bb07652009-12-22 00:05:34 +0000252void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
253 const InitializedEntity &ParentEntity,
254 InitListExpr *ILE,
255 bool &RequiresSecondPass) {
256 SourceLocation Loc = ILE->getSourceRange().getBegin();
257 unsigned NumInits = ILE->getNumInits();
258 InitializedEntity MemberEntity
259 = InitializedEntity::InitializeMember(Field, &ParentEntity);
260 if (Init >= NumInits || !ILE->getInit(Init)) {
261 // FIXME: We probably don't need to handle references
262 // specially here, since value-initialization of references is
263 // handled in InitializationSequence.
264 if (Field->getType()->isReferenceType()) {
265 // C++ [dcl.init.aggr]p9:
266 // If an incomplete or empty initializer-list leaves a
267 // member of reference type uninitialized, the program is
268 // ill-formed.
269 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
270 << Field->getType()
271 << ILE->getSyntacticForm()->getSourceRange();
272 SemaRef.Diag(Field->getLocation(),
273 diag::note_uninit_reference_member);
274 hadError = true;
275 return;
276 }
277
278 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
279 true);
280 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
281 if (!InitSeq) {
282 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
283 hadError = true;
284 return;
285 }
286
287 Sema::OwningExprResult MemberInit
288 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
289 Sema::MultiExprArg(SemaRef, 0, 0));
290 if (MemberInit.isInvalid()) {
291 hadError = true;
292 return;
293 }
294
295 if (hadError) {
296 // Do nothing
297 } else if (Init < NumInits) {
298 ILE->setInit(Init, MemberInit.takeAs<Expr>());
299 } else if (InitSeq.getKind()
300 == InitializationSequence::ConstructorInitialization) {
301 // Value-initialization requires a constructor call, so
302 // extend the initializer list to include the constructor
303 // call and make a note that we'll need to take another pass
304 // through the initializer list.
305 ILE->updateInit(Init, MemberInit.takeAs<Expr>());
306 RequiresSecondPass = true;
307 }
308 } else if (InitListExpr *InnerILE
309 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
310 FillInValueInitializations(MemberEntity, InnerILE,
311 RequiresSecondPass);
312}
313
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000314/// Recursively replaces NULL values within the given initializer list
315/// with expressions that perform value-initialization of the
316/// appropriate type.
Douglas Gregor723796a2009-12-16 06:35:08 +0000317void
318InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
319 InitListExpr *ILE,
320 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000321 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000322 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000323 SourceLocation Loc = ILE->getSourceRange().getBegin();
324 if (ILE->getSyntacticForm())
325 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000326
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000327 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000328 if (RType->getDecl()->isUnion() &&
329 ILE->getInitializedFieldInUnion())
330 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
331 Entity, ILE, RequiresSecondPass);
332 else {
333 unsigned Init = 0;
334 for (RecordDecl::field_iterator
335 Field = RType->getDecl()->field_begin(),
336 FieldEnd = RType->getDecl()->field_end();
337 Field != FieldEnd; ++Field) {
338 if (Field->isUnnamedBitfield())
339 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000340
Douglas Gregor2bb07652009-12-22 00:05:34 +0000341 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000342 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000343
344 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
345 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000346 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000347
Douglas Gregor2bb07652009-12-22 00:05:34 +0000348 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000349
Douglas Gregor2bb07652009-12-22 00:05:34 +0000350 // Only look at the first initialization of a union.
351 if (RType->getDecl()->isUnion())
352 break;
353 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000354 }
355
356 return;
Mike Stump11289f42009-09-09 15:08:12 +0000357 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000358
359 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000360
Douglas Gregor723796a2009-12-16 06:35:08 +0000361 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000362 unsigned NumInits = ILE->getNumInits();
363 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000364 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000365 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000366 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
367 NumElements = CAType->getSize().getZExtValue();
Douglas Gregor723796a2009-12-16 06:35:08 +0000368 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
369 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000370 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000371 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000372 NumElements = VType->getNumElements();
Douglas Gregor723796a2009-12-16 06:35:08 +0000373 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
374 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000375 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000376 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000377
Douglas Gregor723796a2009-12-16 06:35:08 +0000378
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000379 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000380 if (hadError)
381 return;
382
Douglas Gregor723796a2009-12-16 06:35:08 +0000383 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayOrVectorElement)
384 ElementEntity.setElementIndex(Init);
385
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000386 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000387 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
388 true);
389 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
390 if (!InitSeq) {
391 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000392 hadError = true;
393 return;
394 }
395
Douglas Gregor723796a2009-12-16 06:35:08 +0000396 Sema::OwningExprResult ElementInit
397 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
398 Sema::MultiExprArg(SemaRef, 0, 0));
399 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000400 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000401 return;
402 }
403
404 if (hadError) {
405 // Do nothing
406 } else if (Init < NumInits) {
407 ILE->setInit(Init, ElementInit.takeAs<Expr>());
408 } else if (InitSeq.getKind()
409 == InitializationSequence::ConstructorInitialization) {
410 // Value-initialization requires a constructor call, so
411 // extend the initializer list to include the constructor
412 // call and make a note that we'll need to take another pass
413 // through the initializer list.
414 ILE->updateInit(Init, ElementInit.takeAs<Expr>());
415 RequiresSecondPass = true;
416 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000417 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000418 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
419 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000420 }
421}
422
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000423
Douglas Gregor723796a2009-12-16 06:35:08 +0000424InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
425 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000426 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000427 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000428
Eli Friedman23a9e312008-05-19 19:16:24 +0000429 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000430 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000431 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000432 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000433 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
434 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000435
Douglas Gregor723796a2009-12-16 06:35:08 +0000436 if (!hadError) {
437 bool RequiresSecondPass = false;
438 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000439 if (RequiresSecondPass && !hadError)
Douglas Gregor723796a2009-12-16 06:35:08 +0000440 FillInValueInitializations(Entity, FullyStructuredList,
441 RequiresSecondPass);
442 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000443}
444
445int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000446 // FIXME: use a proper constant
447 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000448 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000449 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000450 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
451 }
452 return maxElements;
453}
454
455int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000456 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000457 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000458 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000459 Field = structDecl->field_begin(),
460 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000461 Field != FieldEnd; ++Field) {
462 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
463 ++InitializableMembers;
464 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000465 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000466 return std::min(InitializableMembers, 1);
467 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000468}
469
Mike Stump11289f42009-09-09 15:08:12 +0000470void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000471 QualType T, unsigned &Index,
472 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000473 unsigned &StructuredIndex,
474 bool TopLevelObject) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000475 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000476
Steve Narofff8ecff22008-05-01 22:18:59 +0000477 if (T->isArrayType())
478 maxElements = numArrayElements(T);
479 else if (T->isStructureType() || T->isUnionType())
480 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000481 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000482 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000483 else
484 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000485
Eli Friedmane0f832b2008-05-25 13:49:22 +0000486 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000487 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000488 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000489 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000490 hadError = true;
491 return;
492 }
493
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000494 // Build a structured initializer list corresponding to this subobject.
495 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000496 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
497 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000498 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
499 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000500 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000501
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000502 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000503 unsigned StartIndex = Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000504 CheckListElementTypes(ParentIList, T, false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000505 StructuredSubobjectInitList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000506 StructuredSubobjectInitIndex,
507 TopLevelObject);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000508 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000509 StructuredSubobjectInitList->setType(T);
510
Douglas Gregor5741efb2009-03-01 17:12:46 +0000511 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000512 // range corresponds with the end of the last initializer it used.
513 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000514 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000515 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
516 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
517 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000518}
519
Steve Naroff125d73d2008-05-06 00:23:44 +0000520void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000521 unsigned &Index,
522 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000523 unsigned &StructuredIndex,
524 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000525 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000526 SyntacticToSemantic[IList] = StructuredList;
527 StructuredList->setSyntacticForm(IList);
Mike Stump11289f42009-09-09 15:08:12 +0000528 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000529 StructuredIndex, TopLevelObject);
Steve Naroff125d73d2008-05-06 00:23:44 +0000530 IList->setType(T);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000531 StructuredList->setType(T);
Eli Friedman85f54972008-05-25 13:22:35 +0000532 if (hadError)
533 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000534
Eli Friedman85f54972008-05-25 13:22:35 +0000535 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000536 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000537 if (StructuredIndex == 1 &&
538 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000539 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000540 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000541 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000542 hadError = true;
543 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000544 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000545 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000546 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000547 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000548 // Don't complain for incomplete types, since we'll get an error
549 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000550 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000551 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000552 CurrentObjectType->isArrayType()? 0 :
553 CurrentObjectType->isVectorType()? 1 :
554 CurrentObjectType->isScalarType()? 2 :
555 CurrentObjectType->isUnionType()? 3 :
556 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000557
558 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000559 if (SemaRef.getLangOptions().CPlusPlus) {
560 DK = diag::err_excess_initializers;
561 hadError = true;
562 }
Nate Begeman425038c2009-07-07 21:53:06 +0000563 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
564 DK = diag::err_excess_initializers;
565 hadError = true;
566 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000567
Chris Lattnerb0912a52009-02-24 22:50:46 +0000568 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000569 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000570 }
571 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000572
Eli Friedman0b4af8f2009-05-16 11:45:48 +0000573 if (T->isScalarType() && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000574 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000575 << IList->getSourceRange()
Chris Lattner3c7b86f2009-12-06 17:36:05 +0000576 << CodeModificationHint::CreateRemoval(IList->getLocStart())
577 << CodeModificationHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000578}
579
Eli Friedman23a9e312008-05-19 19:16:24 +0000580void InitListChecker::CheckListElementTypes(InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000581 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000582 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000583 unsigned &Index,
584 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000585 unsigned &StructuredIndex,
586 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000587 if (DeclType->isScalarType()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000588 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000589 } else if (DeclType->isVectorType()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000590 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000591 } else if (DeclType->isAggregateType()) {
592 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000593 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000594 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000595 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000596 StructuredList, StructuredIndex,
597 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000598 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000599 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000600 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000601 false);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000602 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
603 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000604 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000605 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000606 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
607 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000608 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000609 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000610 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000611 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000612 } else if (DeclType->isRecordType()) {
613 // C++ [dcl.init]p14:
614 // [...] If the class is an aggregate (8.5.1), and the initializer
615 // is a brace-enclosed list, see 8.5.1.
616 //
617 // Note: 8.5.1 is handled below; here, we diagnose the case where
618 // we have an initializer list and a destination type that is not
619 // an aggregate.
620 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000621 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000622 << DeclType << IList->getSourceRange();
623 hadError = true;
624 } else if (DeclType->isReferenceType()) {
625 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000626 } else {
627 // In C, all types are either scalars or aggregates, but
Mike Stump11289f42009-09-09 15:08:12 +0000628 // additional handling is needed here for C++ (and possibly others?).
Steve Narofff8ecff22008-05-01 22:18:59 +0000629 assert(0 && "Unsupported initializer type");
630 }
631}
632
Eli Friedman23a9e312008-05-19 19:16:24 +0000633void InitListChecker::CheckSubElementType(InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000634 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000635 unsigned &Index,
636 InitListExpr *StructuredList,
637 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000638 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000639 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
640 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000641 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000642 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000643 = getStructuredSubobjectInit(IList, Index, ElemType,
644 StructuredList, StructuredIndex,
645 SubInitList->getSourceRange());
Mike Stump11289f42009-09-09 15:08:12 +0000646 CheckExplicitInitList(SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000647 newStructuredList, newStructuredIndex);
648 ++StructuredIndex;
649 ++Index;
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000650 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
651 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000652 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000653 ++Index;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000654 } else if (ElemType->isScalarType()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000655 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000656 } else if (ElemType->isReferenceType()) {
657 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedman23a9e312008-05-19 19:16:24 +0000658 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000659 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000660 // C++ [dcl.init.aggr]p12:
661 // All implicit type conversions (clause 4) are considered when
662 // initializing the aggregate member with an ini- tializer from
663 // an initializer-list. If the initializer can initialize a
664 // member, the member is initialized. [...]
Mike Stump11289f42009-09-09 15:08:12 +0000665 ImplicitConversionSequence ICS
Anders Carlsson03068aa2009-08-27 17:18:13 +0000666 = SemaRef.TryCopyInitialization(expr, ElemType,
667 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +0000668 /*ForceRValue=*/false,
669 /*InOverloadResolution=*/false);
Anders Carlsson03068aa2009-08-27 17:18:13 +0000670
Douglas Gregord14247a2009-01-30 22:09:00 +0000671 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Mike Stump11289f42009-09-09 15:08:12 +0000672 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000673 Sema::AA_Initializing))
Douglas Gregord14247a2009-01-30 22:09:00 +0000674 hadError = true;
675 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
676 ++Index;
677 return;
678 }
679
680 // Fall through for subaggregate initialization
681 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000682 // C99 6.7.8p13:
Douglas Gregord14247a2009-01-30 22:09:00 +0000683 //
684 // The initializer for a structure or union object that has
685 // automatic storage duration shall be either an initializer
686 // list as described below, or a single expression that has
687 // compatible structure or union type. In the latter case, the
688 // initial value of the object, including unnamed members, is
689 // that of the expression.
Eli Friedman9782caa2009-06-13 10:38:46 +0000690 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman893abe42009-05-29 18:22:49 +0000691 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000692 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
693 ++Index;
694 return;
695 }
696
697 // Fall through for subaggregate initialization
698 }
699
700 // C++ [dcl.init.aggr]p12:
Mike Stump11289f42009-09-09 15:08:12 +0000701 //
Douglas Gregord14247a2009-01-30 22:09:00 +0000702 // [...] Otherwise, if the member is itself a non-empty
703 // subaggregate, brace elision is assumed and the initializer is
704 // considered for the initialization of the first member of
705 // the subaggregate.
706 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000707 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
Douglas Gregord14247a2009-01-30 22:09:00 +0000708 StructuredIndex);
709 ++StructuredIndex;
710 } else {
711 // We cannot initialize this element, so let
712 // PerformCopyInitialization produce the appropriate diagnostic.
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000713 SemaRef.PerformCopyInitialization(expr, ElemType, Sema::AA_Initializing);
Douglas Gregord14247a2009-01-30 22:09:00 +0000714 hadError = true;
715 ++Index;
716 ++StructuredIndex;
717 }
718 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000719}
720
Douglas Gregord14247a2009-01-30 22:09:00 +0000721void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000722 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000723 InitListExpr *StructuredList,
724 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000725 if (Index < IList->getNumInits()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000726 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000727 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000728 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000729 diag::err_many_braces_around_scalar_init)
730 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000731 hadError = true;
732 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000733 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000734 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000735 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump11289f42009-09-09 15:08:12 +0000736 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000737 diag::err_designator_for_scalar_init)
738 << DeclType << expr->getSourceRange();
739 hadError = true;
740 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000741 ++StructuredIndex;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000742 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000743 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000744
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000745 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000746 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000747 hadError = true; // types weren't compatible.
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000748 else if (savExpr != expr) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000749 // The type was promoted, update initializer list.
Douglas Gregorf6d27522009-01-29 00:39:20 +0000750 IList->setInit(Index, expr);
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000751 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000752 if (hadError)
753 ++StructuredIndex;
754 else
755 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Narofff8ecff22008-05-01 22:18:59 +0000756 ++Index;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000757 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000758 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000759 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000760 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000761 ++Index;
762 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000763 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000764 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000765}
766
Douglas Gregord14247a2009-01-30 22:09:00 +0000767void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
768 unsigned &Index,
769 InitListExpr *StructuredList,
770 unsigned &StructuredIndex) {
771 if (Index < IList->getNumInits()) {
772 Expr *expr = IList->getInit(Index);
773 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000774 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000775 << DeclType << IList->getSourceRange();
776 hadError = true;
777 ++Index;
778 ++StructuredIndex;
779 return;
Mike Stump11289f42009-09-09 15:08:12 +0000780 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000781
782 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Anders Carlsson271e3a42009-08-27 17:30:43 +0000783 if (SemaRef.CheckReferenceInit(expr, DeclType,
Douglas Gregorc809cc22009-09-23 23:04:10 +0000784 /*FIXME:*/expr->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +0000785 /*SuppressUserConversions=*/false,
786 /*AllowExplicit=*/false,
Mike Stump11289f42009-09-09 15:08:12 +0000787 /*ForceRValue=*/false))
Douglas Gregord14247a2009-01-30 22:09:00 +0000788 hadError = true;
789 else if (savExpr != expr) {
790 // The type was promoted, update initializer list.
791 IList->setInit(Index, expr);
792 }
793 if (hadError)
794 ++StructuredIndex;
795 else
796 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
797 ++Index;
798 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000799 // FIXME: It would be wonderful if we could point at the actual member. In
800 // general, it would be useful to pass location information down the stack,
801 // so that we know the location (or decl) of the "current object" being
802 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000803 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000804 diag::err_init_reference_member_uninitialized)
805 << DeclType
806 << IList->getSourceRange();
807 hadError = true;
808 ++Index;
809 ++StructuredIndex;
810 return;
811 }
812}
813
Mike Stump11289f42009-09-09 15:08:12 +0000814void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000815 unsigned &Index,
816 InitListExpr *StructuredList,
817 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000818 if (Index < IList->getNumInits()) {
John McCall9dd450b2009-09-21 23:43:11 +0000819 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000820 unsigned maxElements = VT->getNumElements();
821 unsigned numEltsInit = 0;
Steve Narofff8ecff22008-05-01 22:18:59 +0000822 QualType elementType = VT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +0000823
Nate Begeman5ec4b312009-08-10 23:49:36 +0000824 if (!SemaRef.getLangOptions().OpenCL) {
825 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
826 // Don't attempt to go past the end of the init list
827 if (Index >= IList->getNumInits())
828 break;
829 CheckSubElementType(IList, elementType, Index,
830 StructuredList, StructuredIndex);
831 }
832 } else {
833 // OpenCL initializers allows vectors to be constructed from vectors.
834 for (unsigned i = 0; i < maxElements; ++i) {
835 // Don't attempt to go past the end of the init list
836 if (Index >= IList->getNumInits())
837 break;
838 QualType IType = IList->getInit(Index)->getType();
839 if (!IType->isVectorType()) {
840 CheckSubElementType(IList, elementType, Index,
841 StructuredList, StructuredIndex);
842 ++numEltsInit;
843 } else {
John McCall9dd450b2009-09-21 23:43:11 +0000844 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000845 unsigned numIElts = IVT->getNumElements();
846 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
847 numIElts);
848 CheckSubElementType(IList, VecType, Index,
849 StructuredList, StructuredIndex);
850 numEltsInit += numIElts;
851 }
852 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000853 }
Mike Stump11289f42009-09-09 15:08:12 +0000854
Nate Begeman5ec4b312009-08-10 23:49:36 +0000855 // OpenCL & AltiVec require all elements to be initialized.
856 if (numEltsInit != maxElements)
857 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
858 SemaRef.Diag(IList->getSourceRange().getBegin(),
859 diag::err_vector_incorrect_num_initializers)
860 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000861 }
862}
863
Mike Stump11289f42009-09-09 15:08:12 +0000864void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000865 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000866 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000867 unsigned &Index,
868 InitListExpr *StructuredList,
869 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000870 // Check for the special-case of initializing an array with a string.
871 if (Index < IList->getNumInits()) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000872 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
873 SemaRef.Context)) {
874 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000875 // We place the string literal directly into the resulting
876 // initializer list. This is the only place where the structure
877 // of the structured initializer list doesn't match exactly,
878 // because doing so would involve allocating one character
879 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000880 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +0000881 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000882 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000883 return;
884 }
885 }
Chris Lattner7adf0762008-08-04 07:31:14 +0000886 if (const VariableArrayType *VAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000887 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman85f54972008-05-25 13:22:35 +0000888 // Check for VLAs; in standard C it would be possible to check this
889 // earlier, but I don't know where clang accepts VLAs (gcc accepts
890 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +0000891 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000892 diag::err_variable_object_no_init)
893 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +0000894 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000895 ++Index;
896 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +0000897 return;
898 }
899
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000900 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000901 llvm::APSInt maxElements(elementIndex.getBitWidth(),
902 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000903 bool maxElementsKnown = false;
904 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000905 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000906 maxElements = CAT->getSize();
Douglas Gregor033d1252009-01-23 16:54:12 +0000907 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000908 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000909 maxElementsKnown = true;
910 }
911
Chris Lattnerb0912a52009-02-24 22:50:46 +0000912 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattner7adf0762008-08-04 07:31:14 +0000913 ->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000914 while (Index < IList->getNumInits()) {
915 Expr *Init = IList->getInit(Index);
916 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000917 // If we're not the subobject that matches up with the '{' for
918 // the designator, we shouldn't be handling the
919 // designator. Return immediately.
920 if (!SubobjectIsDesignatorContext)
921 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000922
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000923 // Handle this designated initializer. elementIndex will be
924 // updated to be the next array element we'll initialize.
Mike Stump11289f42009-09-09 15:08:12 +0000925 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000926 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000927 StructuredList, StructuredIndex, true,
928 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000929 hadError = true;
930 continue;
931 }
932
Douglas Gregor033d1252009-01-23 16:54:12 +0000933 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
934 maxElements.extend(elementIndex.getBitWidth());
935 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
936 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000937 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +0000938
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000939 // If the array is of incomplete type, keep track of the number of
940 // elements in the initializer.
941 if (!maxElementsKnown && elementIndex > maxElements)
942 maxElements = elementIndex;
943
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000944 continue;
945 }
946
947 // If we know the maximum number of elements, and we've already
948 // hit it, stop consuming elements in the initializer list.
949 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +0000950 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000951
952 // Check this element.
Douglas Gregorf6d27522009-01-29 00:39:20 +0000953 CheckSubElementType(IList, elementType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000954 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000955 ++elementIndex;
956
957 // If the array is of incomplete type, keep track of the number of
958 // elements in the initializer.
959 if (!maxElementsKnown && elementIndex > maxElements)
960 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +0000961 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +0000962 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000963 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000964 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000965 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000966 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000967 // Sizing an array implicitly to zero is not allowed by ISO C,
968 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000969 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000970 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +0000971 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000972
Mike Stump11289f42009-09-09 15:08:12 +0000973 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000974 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +0000975 }
976}
977
Mike Stump11289f42009-09-09 15:08:12 +0000978void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
979 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000980 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +0000981 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000982 unsigned &Index,
983 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000984 unsigned &StructuredIndex,
985 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000986 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000987
Eli Friedman23a9e312008-05-19 19:16:24 +0000988 // If the record is invalid, some of it's members are invalid. To avoid
989 // confusion, we forgo checking the intializer for the entire record.
990 if (structDecl->isInvalidDecl()) {
991 hadError = true;
992 return;
Mike Stump11289f42009-09-09 15:08:12 +0000993 }
Douglas Gregor0202cb42009-01-29 17:44:32 +0000994
995 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
996 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000997 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000998 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +0000999 Field != FieldEnd; ++Field) {
1000 if (Field->getDeclName()) {
1001 StructuredList->setInitializedFieldInUnion(*Field);
1002 break;
1003 }
1004 }
1005 return;
1006 }
1007
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001008 // If structDecl is a forward declaration, this loop won't do
1009 // anything except look at designated initializers; That's okay,
1010 // because an error should get printed out elsewhere. It might be
1011 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001012 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001013 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001014 bool InitializedSomething = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001015 while (Index < IList->getNumInits()) {
1016 Expr *Init = IList->getInit(Index);
1017
1018 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001019 // If we're not the subobject that matches up with the '{' for
1020 // the designator, we shouldn't be handling the
1021 // designator. Return immediately.
1022 if (!SubobjectIsDesignatorContext)
1023 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001024
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001025 // Handle this designated initializer. Field will be updated to
1026 // the next field that we'll be initializing.
Mike Stump11289f42009-09-09 15:08:12 +00001027 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001028 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001029 StructuredList, StructuredIndex,
1030 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001031 hadError = true;
1032
Douglas Gregora9add4e2009-02-12 19:00:39 +00001033 InitializedSomething = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001034 continue;
1035 }
1036
1037 if (Field == FieldEnd) {
1038 // We've run out of fields. We're done.
1039 break;
1040 }
1041
Douglas Gregora9add4e2009-02-12 19:00:39 +00001042 // We've already initialized a member of a union. We're done.
1043 if (InitializedSomething && DeclType->isUnionType())
1044 break;
1045
Douglas Gregor91f84212008-12-11 16:49:14 +00001046 // If we've hit the flexible array member at the end, we're done.
1047 if (Field->getType()->isIncompleteArrayType())
1048 break;
1049
Douglas Gregor51695702009-01-29 16:53:55 +00001050 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001051 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001052 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001053 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001054 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001055
Douglas Gregorf6d27522009-01-29 00:39:20 +00001056 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001057 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001058 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001059
1060 if (DeclType->isUnionType()) {
1061 // Initialize the first field within the union.
1062 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001063 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001064
1065 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001066 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001067
Mike Stump11289f42009-09-09 15:08:12 +00001068 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001069 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001070 return;
1071
1072 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001073 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001074 (!isa<InitListExpr>(IList->getInit(Index)) ||
1075 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001076 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001077 diag::err_flexible_array_init_nonempty)
1078 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001079 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001080 << *Field;
1081 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001082 ++Index;
1083 return;
1084 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001085 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001086 diag::ext_flexible_array_init)
1087 << IList->getInit(Index)->getSourceRange().getBegin();
1088 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1089 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001090 }
1091
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001092 if (isa<InitListExpr>(IList->getInit(Index)))
1093 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1094 StructuredIndex);
1095 else
1096 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1097 StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001098}
Steve Narofff8ecff22008-05-01 22:18:59 +00001099
Douglas Gregord5846a12009-04-15 06:41:24 +00001100/// \brief Expand a field designator that refers to a member of an
1101/// anonymous struct or union into a series of field designators that
1102/// refers to the field within the appropriate subobject.
1103///
1104/// Field/FieldIndex will be updated to point to the (new)
1105/// currently-designated field.
1106static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001107 DesignatedInitExpr *DIE,
1108 unsigned DesigIdx,
Douglas Gregord5846a12009-04-15 06:41:24 +00001109 FieldDecl *Field,
1110 RecordDecl::field_iterator &FieldIter,
1111 unsigned &FieldIndex) {
1112 typedef DesignatedInitExpr::Designator Designator;
1113
1114 // Build the path from the current object to the member of the
1115 // anonymous struct/union (backwards).
1116 llvm::SmallVector<FieldDecl *, 4> Path;
1117 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump11289f42009-09-09 15:08:12 +00001118
Douglas Gregord5846a12009-04-15 06:41:24 +00001119 // Build the replacement designators.
1120 llvm::SmallVector<Designator, 4> Replacements;
1121 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1122 FI = Path.rbegin(), FIEnd = Path.rend();
1123 FI != FIEnd; ++FI) {
1124 if (FI + 1 == FIEnd)
Mike Stump11289f42009-09-09 15:08:12 +00001125 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001126 DIE->getDesignator(DesigIdx)->getDotLoc(),
1127 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1128 else
1129 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1130 SourceLocation()));
1131 Replacements.back().setField(*FI);
1132 }
1133
1134 // Expand the current designator into the set of replacement
1135 // designators, so we have a full subobject path down to where the
1136 // member of the anonymous struct/union is actually stored.
Mike Stump11289f42009-09-09 15:08:12 +00001137 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001138 &Replacements[0] + Replacements.size());
Mike Stump11289f42009-09-09 15:08:12 +00001139
Douglas Gregord5846a12009-04-15 06:41:24 +00001140 // Update FieldIter/FieldIndex;
1141 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001142 FieldIter = Record->field_begin();
Douglas Gregord5846a12009-04-15 06:41:24 +00001143 FieldIndex = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001144 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregord5846a12009-04-15 06:41:24 +00001145 FieldIter != FEnd; ++FieldIter) {
1146 if (FieldIter->isUnnamedBitfield())
1147 continue;
1148
1149 if (*FieldIter == Path.back())
1150 return;
1151
1152 ++FieldIndex;
1153 }
1154
1155 assert(false && "Unable to find anonymous struct/union field");
1156}
1157
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001158/// @brief Check the well-formedness of a C99 designated initializer.
1159///
1160/// Determines whether the designated initializer @p DIE, which
1161/// resides at the given @p Index within the initializer list @p
1162/// IList, is well-formed for a current object of type @p DeclType
1163/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001164/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001165/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001166///
1167/// @param IList The initializer list in which this designated
1168/// initializer occurs.
1169///
Douglas Gregora5324162009-04-15 04:56:10 +00001170/// @param DIE The designated initializer expression.
1171///
1172/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001173///
1174/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1175/// into which the designation in @p DIE should refer.
1176///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001177/// @param NextField If non-NULL and the first designator in @p DIE is
1178/// a field, this will be set to the field declaration corresponding
1179/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001180///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001181/// @param NextElementIndex If non-NULL and the first designator in @p
1182/// DIE is an array designator or GNU array-range designator, this
1183/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001184///
1185/// @param Index Index into @p IList where the designated initializer
1186/// @p DIE occurs.
1187///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001188/// @param StructuredList The initializer list expression that
1189/// describes all of the subobject initializers in the order they'll
1190/// actually be initialized.
1191///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001192/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001193bool
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001194InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001195 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001196 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001197 QualType &CurrentObjectType,
1198 RecordDecl::field_iterator *NextField,
1199 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001200 unsigned &Index,
1201 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001202 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001203 bool FinishSubobjectInit,
1204 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001205 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001206 // Check the actual initialization for the designated object type.
1207 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001208
1209 // Temporarily remove the designator expression from the
1210 // initializer list that the child calls see, so that we don't try
1211 // to re-process the designator.
1212 unsigned OldIndex = Index;
1213 IList->setInit(OldIndex, DIE->getInit());
1214
1215 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001216 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001217
1218 // Restore the designated initializer expression in the syntactic
1219 // form of the initializer list.
1220 if (IList->getInit(OldIndex) != DIE->getInit())
1221 DIE->setInit(IList->getInit(OldIndex));
1222 IList->setInit(OldIndex, DIE);
1223
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001224 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001225 }
1226
Douglas Gregora5324162009-04-15 04:56:10 +00001227 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001228 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001229 "Need a non-designated initializer list to start from");
1230
Douglas Gregora5324162009-04-15 04:56:10 +00001231 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001232 // Determine the structural initializer list that corresponds to the
1233 // current subobject.
1234 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001235 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001236 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001237 SourceRange(D->getStartLocation(),
1238 DIE->getSourceRange().getEnd()));
1239 assert(StructuredList && "Expected a structured initializer list");
1240
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001241 if (D->isFieldDesignator()) {
1242 // C99 6.7.8p7:
1243 //
1244 // If a designator has the form
1245 //
1246 // . identifier
1247 //
1248 // then the current object (defined below) shall have
1249 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001250 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001251 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001252 if (!RT) {
1253 SourceLocation Loc = D->getDotLoc();
1254 if (Loc.isInvalid())
1255 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001256 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1257 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001258 ++Index;
1259 return true;
1260 }
1261
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001262 // Note: we perform a linear search of the fields here, despite
1263 // the fact that we have a faster lookup method, because we always
1264 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001265 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001266 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001267 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001268 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001269 Field = RT->getDecl()->field_begin(),
1270 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001271 for (; Field != FieldEnd; ++Field) {
1272 if (Field->isUnnamedBitfield())
1273 continue;
1274
Douglas Gregord5846a12009-04-15 06:41:24 +00001275 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001276 break;
1277
1278 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001279 }
1280
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001281 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001282 // There was no normal field in the struct with the designated
1283 // name. Perform another lookup for this name, which may find
1284 // something that we can't designate (e.g., a member function),
1285 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001286 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001287 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001288 if (Lookup.first == Lookup.second) {
1289 // Name lookup didn't find anything.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001290 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001291 << FieldName << CurrentObjectType;
Douglas Gregord5846a12009-04-15 06:41:24 +00001292 ++Index;
1293 return true;
1294 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1295 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1296 ->isAnonymousStructOrUnion()) {
1297 // Handle an field designator that refers to a member of an
1298 // anonymous struct or union.
Mike Stump11289f42009-09-09 15:08:12 +00001299 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
Douglas Gregord5846a12009-04-15 06:41:24 +00001300 cast<FieldDecl>(*Lookup.first),
1301 Field, FieldIndex);
Eli Friedman8d25b092009-04-16 17:49:48 +00001302 D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001303 } else {
1304 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001305 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001306 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001307 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001308 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001309 ++Index;
1310 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001311 }
1312 } else if (!KnownField &&
1313 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001314 ->isAnonymousStructOrUnion()) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001315 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1316 Field, FieldIndex);
1317 D = DIE->getDesignator(DesigIdx);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001318 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001319
1320 // All of the fields of a union are located at the same place in
1321 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001322 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001323 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001324 StructuredList->setInitializedFieldInUnion(*Field);
1325 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001326
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001327 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001328 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001329
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001330 // Make sure that our non-designated initializer list has space
1331 // for a subobject corresponding to this field.
1332 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001333 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001334
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001335 // This designator names a flexible array member.
1336 if (Field->getType()->isIncompleteArrayType()) {
1337 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001338 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001339 // We can't designate an object within the flexible array
1340 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001341 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001342 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001343 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001344 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001345 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001346 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001347 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001348 << *Field;
1349 Invalid = true;
1350 }
1351
1352 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1353 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001354 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001355 diag::err_flexible_array_init_needs_braces)
1356 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001357 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001358 << *Field;
1359 Invalid = true;
1360 }
1361
1362 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001363 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001364 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001365 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001366 diag::err_flexible_array_init_nonempty)
1367 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001368 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001369 << *Field;
1370 Invalid = true;
1371 }
1372
1373 if (Invalid) {
1374 ++Index;
1375 return true;
1376 }
1377
1378 // Initialize the array.
1379 bool prevHadError = hadError;
1380 unsigned newStructuredIndex = FieldIndex;
1381 unsigned OldIndex = Index;
1382 IList->setInit(Index, DIE->getInit());
Mike Stump11289f42009-09-09 15:08:12 +00001383 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001384 StructuredList, newStructuredIndex);
1385 IList->setInit(OldIndex, DIE);
1386 if (hadError && !prevHadError) {
1387 ++Field;
1388 ++FieldIndex;
1389 if (NextField)
1390 *NextField = Field;
1391 StructuredIndex = FieldIndex;
1392 return true;
1393 }
1394 } else {
1395 // Recurse to check later designated subobjects.
1396 QualType FieldType = (*Field)->getType();
1397 unsigned newStructuredIndex = FieldIndex;
Douglas Gregora5324162009-04-15 04:56:10 +00001398 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1399 Index, StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001400 true, false))
1401 return true;
1402 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001403
1404 // Find the position of the next field to be initialized in this
1405 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001406 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001407 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001408
1409 // If this the first designator, our caller will continue checking
1410 // the rest of this struct/class/union subobject.
1411 if (IsFirstDesignator) {
1412 if (NextField)
1413 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001414 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001415 return false;
1416 }
1417
Douglas Gregor17bd0942009-01-28 23:36:17 +00001418 if (!FinishSubobjectInit)
1419 return false;
1420
Douglas Gregord5846a12009-04-15 06:41:24 +00001421 // We've already initialized something in the union; we're done.
1422 if (RT->getDecl()->isUnion())
1423 return hadError;
1424
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001425 // Check the remaining fields within this class/struct/union subobject.
1426 bool prevHadError = hadError;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001427 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1428 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001429 return hadError && !prevHadError;
1430 }
1431
1432 // C99 6.7.8p6:
1433 //
1434 // If a designator has the form
1435 //
1436 // [ constant-expression ]
1437 //
1438 // then the current object (defined below) shall have array
1439 // type and the expression shall be an integer constant
1440 // expression. If the array is of unknown size, any
1441 // nonnegative value is valid.
1442 //
1443 // Additionally, cope with the GNU extension that permits
1444 // designators of the form
1445 //
1446 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001447 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001448 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001449 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001450 << CurrentObjectType;
1451 ++Index;
1452 return true;
1453 }
1454
1455 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001456 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1457 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001458 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001459 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001460 DesignatedEndIndex = DesignatedStartIndex;
1461 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001462 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001463
Mike Stump11289f42009-09-09 15:08:12 +00001464
1465 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001466 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001467 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001468 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001469 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001470
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001471 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001472 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001473 }
1474
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001475 if (isa<ConstantArrayType>(AT)) {
1476 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001477 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1478 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1479 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1480 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1481 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001482 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001483 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001484 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001485 << IndexExpr->getSourceRange();
1486 ++Index;
1487 return true;
1488 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001489 } else {
1490 // Make sure the bit-widths and signedness match.
1491 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1492 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001493 else if (DesignatedStartIndex.getBitWidth() <
1494 DesignatedEndIndex.getBitWidth())
Douglas Gregor17bd0942009-01-28 23:36:17 +00001495 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1496 DesignatedStartIndex.setIsUnsigned(true);
1497 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001498 }
Mike Stump11289f42009-09-09 15:08:12 +00001499
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001500 // Make sure that our non-designated initializer list has space
1501 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001502 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001503 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001504 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001505
Douglas Gregor17bd0942009-01-28 23:36:17 +00001506 // Repeatedly perform subobject initializations in the range
1507 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001508
Douglas Gregor17bd0942009-01-28 23:36:17 +00001509 // Move to the next designator
1510 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1511 unsigned OldIndex = Index;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001512 while (DesignatedStartIndex <= DesignatedEndIndex) {
1513 // Recurse to check later designated subobjects.
1514 QualType ElementType = AT->getElementType();
1515 Index = OldIndex;
Douglas Gregora5324162009-04-15 04:56:10 +00001516 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1517 Index, StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001518 (DesignatedStartIndex == DesignatedEndIndex),
1519 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001520 return true;
1521
1522 // Move to the next index in the array that we'll be initializing.
1523 ++DesignatedStartIndex;
1524 ElementIndex = DesignatedStartIndex.getZExtValue();
1525 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001526
1527 // If this the first designator, our caller will continue checking
1528 // the rest of this array subobject.
1529 if (IsFirstDesignator) {
1530 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001531 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001532 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001533 return false;
1534 }
Mike Stump11289f42009-09-09 15:08:12 +00001535
Douglas Gregor17bd0942009-01-28 23:36:17 +00001536 if (!FinishSubobjectInit)
1537 return false;
1538
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001539 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001540 bool prevHadError = hadError;
Douglas Gregoraef040a2009-02-09 19:45:19 +00001541 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001542 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001543 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001544}
1545
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001546// Get the structured initializer list for a subobject of type
1547// @p CurrentObjectType.
1548InitListExpr *
1549InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1550 QualType CurrentObjectType,
1551 InitListExpr *StructuredList,
1552 unsigned StructuredIndex,
1553 SourceRange InitRange) {
1554 Expr *ExistingInit = 0;
1555 if (!StructuredList)
1556 ExistingInit = SyntacticToSemantic[IList];
1557 else if (StructuredIndex < StructuredList->getNumInits())
1558 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001559
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001560 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1561 return Result;
1562
1563 if (ExistingInit) {
1564 // We are creating an initializer list that initializes the
1565 // subobjects of the current object, but there was already an
1566 // initialization that completely initialized the current
1567 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001568 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001569 // struct X { int a, b; };
1570 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001571 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001572 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1573 // designated initializer re-initializes the whole
1574 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001575 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001576 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001577 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001578 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001579 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001580 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001581 << ExistingInit->getSourceRange();
1582 }
1583
Mike Stump11289f42009-09-09 15:08:12 +00001584 InitListExpr *Result
1585 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001586 InitRange.getEnd());
1587
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001588 Result->setType(CurrentObjectType);
1589
Douglas Gregor6d00c992009-03-20 23:58:33 +00001590 // Pre-allocate storage for the structured initializer list.
1591 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001592 unsigned NumInits = 0;
1593 if (!StructuredList)
1594 NumInits = IList->getNumInits();
1595 else if (Index < IList->getNumInits()) {
1596 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1597 NumInits = SubList->getNumInits();
1598 }
1599
Mike Stump11289f42009-09-09 15:08:12 +00001600 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001601 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1602 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1603 NumElements = CAType->getSize().getZExtValue();
1604 // Simple heuristic so that we don't allocate a very large
1605 // initializer with many empty entries at the end.
Douglas Gregor221c9a52009-03-21 18:13:52 +00001606 if (NumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001607 NumElements = 0;
1608 }
John McCall9dd450b2009-09-21 23:43:11 +00001609 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001610 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001611 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001612 RecordDecl *RDecl = RType->getDecl();
1613 if (RDecl->isUnion())
1614 NumElements = 1;
1615 else
Mike Stump11289f42009-09-09 15:08:12 +00001616 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001617 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001618 }
1619
Douglas Gregor221c9a52009-03-21 18:13:52 +00001620 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001621 NumElements = IList->getNumInits();
1622
1623 Result->reserveInits(NumElements);
1624
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001625 // Link this new initializer list into the structured initializer
1626 // lists.
1627 if (StructuredList)
1628 StructuredList->updateInit(StructuredIndex, Result);
1629 else {
1630 Result->setSyntacticForm(IList);
1631 SyntacticToSemantic[IList] = Result;
1632 }
1633
1634 return Result;
1635}
1636
1637/// Update the initializer at index @p StructuredIndex within the
1638/// structured initializer list to the value @p expr.
1639void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1640 unsigned &StructuredIndex,
1641 Expr *expr) {
1642 // No structured initializer list to update
1643 if (!StructuredList)
1644 return;
1645
1646 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1647 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001648 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001649 diag::warn_initializer_overrides)
1650 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001651 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001652 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001653 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001654 << PrevInit->getSourceRange();
1655 }
Mike Stump11289f42009-09-09 15:08:12 +00001656
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001657 ++StructuredIndex;
1658}
1659
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001660/// Check that the given Index expression is a valid array designator
1661/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001662/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001663/// and produces a reasonable diagnostic if there is a
1664/// failure. Returns true if there was an error, false otherwise. If
1665/// everything went okay, Value will receive the value of the constant
1666/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001667static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001668CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001669 SourceLocation Loc = Index->getSourceRange().getBegin();
1670
1671 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001672 if (S.VerifyIntegerConstantExpression(Index, &Value))
1673 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001674
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001675 if (Value.isSigned() && Value.isNegative())
1676 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001677 << Value.toString(10) << Index->getSourceRange();
1678
Douglas Gregor51650d32009-01-23 21:04:18 +00001679 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001680 return false;
1681}
1682
1683Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1684 SourceLocation Loc,
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00001685 bool GNUSyntax,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001686 OwningExprResult Init) {
1687 typedef DesignatedInitExpr::Designator ASTDesignator;
1688
1689 bool Invalid = false;
1690 llvm::SmallVector<ASTDesignator, 32> Designators;
1691 llvm::SmallVector<Expr *, 32> InitExpressions;
1692
1693 // Build designators and check array designator expressions.
1694 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1695 const Designator &D = Desig.getDesignator(Idx);
1696 switch (D.getKind()) {
1697 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001698 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001699 D.getFieldLoc()));
1700 break;
1701
1702 case Designator::ArrayDesignator: {
1703 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1704 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001705 if (!Index->isTypeDependent() &&
1706 !Index->isValueDependent() &&
1707 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001708 Invalid = true;
1709 else {
1710 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001711 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001712 D.getRBracketLoc()));
1713 InitExpressions.push_back(Index);
1714 }
1715 break;
1716 }
1717
1718 case Designator::ArrayRangeDesignator: {
1719 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1720 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1721 llvm::APSInt StartValue;
1722 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001723 bool StartDependent = StartIndex->isTypeDependent() ||
1724 StartIndex->isValueDependent();
1725 bool EndDependent = EndIndex->isTypeDependent() ||
1726 EndIndex->isValueDependent();
1727 if ((!StartDependent &&
1728 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1729 (!EndDependent &&
1730 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001731 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001732 else {
1733 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001734 if (StartDependent || EndDependent) {
1735 // Nothing to compute.
1736 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregor7a95b082009-01-23 22:22:29 +00001737 EndValue.extend(StartValue.getBitWidth());
1738 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1739 StartValue.extend(EndValue.getBitWidth());
1740
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001741 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001742 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001743 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001744 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1745 Invalid = true;
1746 } else {
1747 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001748 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001749 D.getEllipsisLoc(),
1750 D.getRBracketLoc()));
1751 InitExpressions.push_back(StartIndex);
1752 InitExpressions.push_back(EndIndex);
1753 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001754 }
1755 break;
1756 }
1757 }
1758 }
1759
1760 if (Invalid || Init.isInvalid())
1761 return ExprError();
1762
1763 // Clear out the expressions within the designation.
1764 Desig.ClearExprs(*this);
1765
1766 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001767 = DesignatedInitExpr::Create(Context,
1768 Designators.data(), Designators.size(),
1769 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001770 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001771 return Owned(DIE);
1772}
Douglas Gregor85df8d82009-01-29 00:45:39 +00001773
Douglas Gregor723796a2009-12-16 06:35:08 +00001774bool Sema::CheckInitList(const InitializedEntity &Entity,
1775 InitListExpr *&InitList, QualType &DeclType) {
1776 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00001777 if (!CheckInitList.HadError())
1778 InitList = CheckInitList.getFullyStructuredList();
1779
1780 return CheckInitList.HadError();
1781}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00001782
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001783//===----------------------------------------------------------------------===//
1784// Initialization entity
1785//===----------------------------------------------------------------------===//
1786
Douglas Gregor723796a2009-12-16 06:35:08 +00001787InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1788 const InitializedEntity &Parent)
1789 : Kind(EK_ArrayOrVectorElement), Parent(&Parent), Index(Index)
1790{
1791 if (isa<ArrayType>(Parent.TL.getType())) {
1792 TL = cast<ArrayTypeLoc>(Parent.TL).getElementLoc();
1793 return;
1794 }
1795
1796 // FIXME: should be able to get type location information for vectors, too.
1797
1798 QualType T;
1799 if (const ArrayType *AT = Context.getAsArrayType(Parent.TL.getType()))
1800 T = AT->getElementType();
1801 else
1802 T = Parent.TL.getType()->getAs<VectorType>()->getElementType();
1803
1804 // FIXME: Once we've gone through the effort to create the fake
1805 // TypeSourceInfo, should we cache it somewhere? (If not, we "leak" it).
1806 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(T);
1807 DI->getTypeLoc().initialize(Parent.TL.getSourceRange().getBegin());
1808 TL = DI->getTypeLoc();
1809}
1810
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001811void InitializedEntity::InitDeclLoc() {
1812 assert((Kind == EK_Variable || Kind == EK_Parameter || Kind == EK_Member) &&
1813 "InitDeclLoc cannot be used with non-declaration entities.");
Douglas Gregor96596c92009-12-22 07:24:36 +00001814
1815 ASTContext &Context = VariableOrMember->getASTContext();
1816 if (Kind == EK_Parameter &&
1817 !Context.hasSameUnqualifiedType(
1818 cast<ParmVarDecl>(VariableOrMember)->getOriginalType(),
1819 VariableOrMember->getType())) {
1820 // For a parameter whose type has decayed, use the decayed type to
1821 // build new source information.
1822 } else if (TypeSourceInfo *DI = VariableOrMember->getTypeSourceInfo()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001823 TL = DI->getTypeLoc();
1824 return;
1825 }
1826
1827 // FIXME: Once we've gone through the effort to create the fake
1828 // TypeSourceInfo, should we cache it in the declaration?
1829 // (If not, we "leak" it).
Douglas Gregor96596c92009-12-22 07:24:36 +00001830 TypeSourceInfo *DI
1831 = Context.CreateTypeSourceInfo(VariableOrMember->getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001832 DI->getTypeLoc().initialize(VariableOrMember->getLocation());
1833 TL = DI->getTypeLoc();
1834}
1835
1836InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1837 CXXBaseSpecifier *Base)
1838{
1839 InitializedEntity Result;
1840 Result.Kind = EK_Base;
1841 Result.Base = Base;
1842 // FIXME: CXXBaseSpecifier should store a TypeLoc.
1843 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Base->getType());
1844 DI->getTypeLoc().initialize(Base->getSourceRange().getBegin());
1845 Result.TL = DI->getTypeLoc();
1846 return Result;
1847}
1848
Douglas Gregor85dabae2009-12-16 01:38:02 +00001849DeclarationName InitializedEntity::getName() const {
1850 switch (getKind()) {
1851 case EK_Variable:
1852 case EK_Parameter:
1853 case EK_Member:
1854 return VariableOrMember->getDeclName();
1855
1856 case EK_Result:
1857 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00001858 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001859 case EK_Temporary:
1860 case EK_Base:
Douglas Gregor723796a2009-12-16 06:35:08 +00001861 case EK_ArrayOrVectorElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001862 return DeclarationName();
1863 }
1864
1865 // Silence GCC warning
1866 return DeclarationName();
1867}
1868
Douglas Gregora4b592a2009-12-19 03:01:41 +00001869DeclaratorDecl *InitializedEntity::getDecl() const {
1870 switch (getKind()) {
1871 case EK_Variable:
1872 case EK_Parameter:
1873 case EK_Member:
1874 return VariableOrMember;
1875
1876 case EK_Result:
1877 case EK_Exception:
1878 case EK_New:
1879 case EK_Temporary:
1880 case EK_Base:
1881 case EK_ArrayOrVectorElement:
1882 return 0;
1883 }
1884
1885 // Silence GCC warning
1886 return 0;
1887}
1888
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001889//===----------------------------------------------------------------------===//
1890// Initialization sequence
1891//===----------------------------------------------------------------------===//
1892
1893void InitializationSequence::Step::Destroy() {
1894 switch (Kind) {
1895 case SK_ResolveAddressOfOverloadedFunction:
1896 case SK_CastDerivedToBaseRValue:
1897 case SK_CastDerivedToBaseLValue:
1898 case SK_BindReference:
1899 case SK_BindReferenceToTemporary:
1900 case SK_UserConversion:
1901 case SK_QualificationConversionRValue:
1902 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00001903 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00001904 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00001905 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00001906 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00001907 case SK_StringInit:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001908 break;
1909
1910 case SK_ConversionSequence:
1911 delete ICS;
1912 }
1913}
1914
1915void InitializationSequence::AddAddressOverloadResolutionStep(
1916 FunctionDecl *Function) {
1917 Step S;
1918 S.Kind = SK_ResolveAddressOfOverloadedFunction;
1919 S.Type = Function->getType();
1920 S.Function = Function;
1921 Steps.push_back(S);
1922}
1923
1924void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
1925 bool IsLValue) {
1926 Step S;
1927 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
1928 S.Type = BaseType;
1929 Steps.push_back(S);
1930}
1931
1932void InitializationSequence::AddReferenceBindingStep(QualType T,
1933 bool BindingTemporary) {
1934 Step S;
1935 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
1936 S.Type = T;
1937 Steps.push_back(S);
1938}
1939
Eli Friedmanad6c2e52009-12-11 02:42:07 +00001940void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
1941 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001942 Step S;
1943 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00001944 S.Type = T;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001945 S.Function = Function;
1946 Steps.push_back(S);
1947}
1948
1949void InitializationSequence::AddQualificationConversionStep(QualType Ty,
1950 bool IsLValue) {
1951 Step S;
1952 S.Kind = IsLValue? SK_QualificationConversionLValue
1953 : SK_QualificationConversionRValue;
1954 S.Type = Ty;
1955 Steps.push_back(S);
1956}
1957
1958void InitializationSequence::AddConversionSequenceStep(
1959 const ImplicitConversionSequence &ICS,
1960 QualType T) {
1961 Step S;
1962 S.Kind = SK_ConversionSequence;
1963 S.Type = T;
1964 S.ICS = new ImplicitConversionSequence(ICS);
1965 Steps.push_back(S);
1966}
1967
Douglas Gregor51e77d52009-12-10 17:56:55 +00001968void InitializationSequence::AddListInitializationStep(QualType T) {
1969 Step S;
1970 S.Kind = SK_ListInitialization;
1971 S.Type = T;
1972 Steps.push_back(S);
1973}
1974
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00001975void
1976InitializationSequence::AddConstructorInitializationStep(
1977 CXXConstructorDecl *Constructor,
1978 QualType T) {
1979 Step S;
1980 S.Kind = SK_ConstructorInitialization;
1981 S.Type = T;
1982 S.Function = Constructor;
1983 Steps.push_back(S);
1984}
1985
Douglas Gregor7dc42e52009-12-15 00:01:57 +00001986void InitializationSequence::AddZeroInitializationStep(QualType T) {
1987 Step S;
1988 S.Kind = SK_ZeroInitialization;
1989 S.Type = T;
1990 Steps.push_back(S);
1991}
1992
Douglas Gregore1314a62009-12-18 05:02:21 +00001993void InitializationSequence::AddCAssignmentStep(QualType T) {
1994 Step S;
1995 S.Kind = SK_CAssignment;
1996 S.Type = T;
1997 Steps.push_back(S);
1998}
1999
Eli Friedman78275202009-12-19 08:11:05 +00002000void InitializationSequence::AddStringInitStep(QualType T) {
2001 Step S;
2002 S.Kind = SK_StringInit;
2003 S.Type = T;
2004 Steps.push_back(S);
2005}
2006
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002007void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2008 OverloadingResult Result) {
2009 SequenceKind = FailedSequence;
2010 this->Failure = Failure;
2011 this->FailedOverloadResult = Result;
2012}
2013
2014//===----------------------------------------------------------------------===//
2015// Attempt initialization
2016//===----------------------------------------------------------------------===//
2017
2018/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregor51e77d52009-12-10 17:56:55 +00002019static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002020 const InitializedEntity &Entity,
2021 const InitializationKind &Kind,
2022 InitListExpr *InitList,
2023 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00002024 // FIXME: We only perform rudimentary checking of list
2025 // initializations at this point, then assume that any list
2026 // initialization of an array, aggregate, or scalar will be
2027 // well-formed. We we actually "perform" list initialization, we'll
2028 // do all of the necessary checking. C++0x initializer lists will
2029 // force us to perform more checking here.
2030 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2031
2032 QualType DestType = Entity.getType().getType();
2033
2034 // C++ [dcl.init]p13:
2035 // If T is a scalar type, then a declaration of the form
2036 //
2037 // T x = { a };
2038 //
2039 // is equivalent to
2040 //
2041 // T x = a;
2042 if (DestType->isScalarType()) {
2043 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2044 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2045 return;
2046 }
2047
2048 // Assume scalar initialization from a single value works.
2049 } else if (DestType->isAggregateType()) {
2050 // Assume aggregate initialization works.
2051 } else if (DestType->isVectorType()) {
2052 // Assume vector initialization works.
2053 } else if (DestType->isReferenceType()) {
2054 // FIXME: C++0x defines behavior for this.
2055 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2056 return;
2057 } else if (DestType->isRecordType()) {
2058 // FIXME: C++0x defines behavior for this
2059 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2060 }
2061
2062 // Add a general "list initialization" step.
2063 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002064}
2065
2066/// \brief Try a reference initialization that involves calling a conversion
2067/// function.
2068///
2069/// FIXME: look intos DRs 656, 896
2070static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2071 const InitializedEntity &Entity,
2072 const InitializationKind &Kind,
2073 Expr *Initializer,
2074 bool AllowRValues,
2075 InitializationSequence &Sequence) {
2076 QualType DestType = Entity.getType().getType();
2077 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2078 QualType T1 = cv1T1.getUnqualifiedType();
2079 QualType cv2T2 = Initializer->getType();
2080 QualType T2 = cv2T2.getUnqualifiedType();
2081
2082 bool DerivedToBase;
2083 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2084 T1, T2, DerivedToBase) &&
2085 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002086 (void)DerivedToBase;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002087
2088 // Build the candidate set directly in the initialization sequence
2089 // structure, so that it will persist if we fail.
2090 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2091 CandidateSet.clear();
2092
2093 // Determine whether we are allowed to call explicit constructors or
2094 // explicit conversion operators.
2095 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2096
2097 const RecordType *T1RecordType = 0;
2098 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2099 // The type we're converting to is a class type. Enumerate its constructors
2100 // to see if there is a suitable conversion.
2101 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2102
2103 DeclarationName ConstructorName
2104 = S.Context.DeclarationNames.getCXXConstructorName(
2105 S.Context.getCanonicalType(T1).getUnqualifiedType());
2106 DeclContext::lookup_iterator Con, ConEnd;
2107 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2108 Con != ConEnd; ++Con) {
2109 // Find the constructor (which may be a template).
2110 CXXConstructorDecl *Constructor = 0;
2111 FunctionTemplateDecl *ConstructorTmpl
2112 = dyn_cast<FunctionTemplateDecl>(*Con);
2113 if (ConstructorTmpl)
2114 Constructor = cast<CXXConstructorDecl>(
2115 ConstructorTmpl->getTemplatedDecl());
2116 else
2117 Constructor = cast<CXXConstructorDecl>(*Con);
2118
2119 if (!Constructor->isInvalidDecl() &&
2120 Constructor->isConvertingConstructor(AllowExplicit)) {
2121 if (ConstructorTmpl)
2122 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2123 &Initializer, 1, CandidateSet);
2124 else
2125 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2126 }
2127 }
2128 }
2129
2130 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2131 // The type we're converting from is a class type, enumerate its conversion
2132 // functions.
2133 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2134
2135 // Determine the type we are converting to. If we are allowed to
2136 // convert to an rvalue, take the type that the destination type
2137 // refers to.
2138 QualType ToType = AllowRValues? cv1T1 : DestType;
2139
2140 const UnresolvedSet *Conversions
2141 = T2RecordDecl->getVisibleConversionFunctions();
2142 for (UnresolvedSet::iterator I = Conversions->begin(),
2143 E = Conversions->end();
2144 I != E; ++I) {
2145 NamedDecl *D = *I;
2146 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2147 if (isa<UsingShadowDecl>(D))
2148 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2149
2150 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2151 CXXConversionDecl *Conv;
2152 if (ConvTemplate)
2153 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2154 else
2155 Conv = cast<CXXConversionDecl>(*I);
2156
2157 // If the conversion function doesn't return a reference type,
2158 // it can't be considered for this conversion unless we're allowed to
2159 // consider rvalues.
2160 // FIXME: Do we need to make sure that we only consider conversion
2161 // candidates with reference-compatible results? That might be needed to
2162 // break recursion.
2163 if ((AllowExplicit || !Conv->isExplicit()) &&
2164 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2165 if (ConvTemplate)
2166 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2167 ToType, CandidateSet);
2168 else
2169 S.AddConversionCandidate(Conv, ActingDC, Initializer, cv1T1,
2170 CandidateSet);
2171 }
2172 }
2173 }
2174
2175 SourceLocation DeclLoc = Initializer->getLocStart();
2176
2177 // Perform overload resolution. If it fails, return the failed result.
2178 OverloadCandidateSet::iterator Best;
2179 if (OverloadingResult Result
2180 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2181 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002182
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002183 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002184
2185 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002186 if (isa<CXXConversionDecl>(Function))
2187 T2 = Function->getResultType();
2188 else
2189 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002190
2191 // Add the user-defined conversion step.
2192 Sequence.AddUserConversionStep(Function, T2.getNonReferenceType());
2193
2194 // Determine whether we need to perform derived-to-base or
2195 // cv-qualification adjustments.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002196 bool NewDerivedToBase = false;
2197 Sema::ReferenceCompareResult NewRefRelationship
2198 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2199 NewDerivedToBase);
2200 assert(NewRefRelationship != Sema::Ref_Incompatible &&
2201 "Overload resolution picked a bad conversion function");
2202 (void)NewRefRelationship;
2203 if (NewDerivedToBase)
2204 Sequence.AddDerivedToBaseCastStep(
2205 S.Context.getQualifiedType(T1,
2206 T2.getNonReferenceType().getQualifiers()),
2207 /*isLValue=*/true);
2208
2209 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2210 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2211
2212 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2213 return OR_Success;
2214}
2215
2216/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2217static void TryReferenceInitialization(Sema &S,
2218 const InitializedEntity &Entity,
2219 const InitializationKind &Kind,
2220 Expr *Initializer,
2221 InitializationSequence &Sequence) {
2222 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2223
2224 QualType DestType = Entity.getType().getType();
2225 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2226 QualType T1 = cv1T1.getUnqualifiedType();
2227 QualType cv2T2 = Initializer->getType();
2228 QualType T2 = cv2T2.getUnqualifiedType();
2229 SourceLocation DeclLoc = Initializer->getLocStart();
2230
2231 // If the initializer is the address of an overloaded function, try
2232 // to resolve the overloaded function. If all goes well, T2 is the
2233 // type of the resulting function.
2234 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2235 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2236 T1,
2237 false);
2238 if (!Fn) {
2239 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2240 return;
2241 }
2242
2243 Sequence.AddAddressOverloadResolutionStep(Fn);
2244 cv2T2 = Fn->getType();
2245 T2 = cv2T2.getUnqualifiedType();
2246 }
2247
2248 // FIXME: Rvalue references
2249 bool ForceRValue = false;
2250
2251 // Compute some basic properties of the types and the initializer.
2252 bool isLValueRef = DestType->isLValueReferenceType();
2253 bool isRValueRef = !isLValueRef;
2254 bool DerivedToBase = false;
2255 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2256 Initializer->isLvalue(S.Context);
2257 Sema::ReferenceCompareResult RefRelationship
2258 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2259
2260 // C++0x [dcl.init.ref]p5:
2261 // A reference to type "cv1 T1" is initialized by an expression of type
2262 // "cv2 T2" as follows:
2263 //
2264 // - If the reference is an lvalue reference and the initializer
2265 // expression
2266 OverloadingResult ConvOvlResult = OR_Success;
2267 if (isLValueRef) {
2268 if (InitLvalue == Expr::LV_Valid &&
2269 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2270 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2271 // reference-compatible with "cv2 T2," or
2272 //
2273 // Per C++ [over.best.ics]p2, we ignore whether the lvalue is a
2274 // bit-field when we're determining whether the reference initialization
2275 // can occur. This property will be checked by PerformInitialization.
2276 if (DerivedToBase)
2277 Sequence.AddDerivedToBaseCastStep(
2278 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()),
2279 /*isLValue=*/true);
2280 if (cv1T1.getQualifiers() != cv2T2.getQualifiers())
2281 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
2282 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/false);
2283 return;
2284 }
2285
2286 // - has a class type (i.e., T2 is a class type), where T1 is not
2287 // reference-related to T2, and can be implicitly converted to an
2288 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2289 // with "cv3 T3" (this conversion is selected by enumerating the
2290 // applicable conversion functions (13.3.1.6) and choosing the best
2291 // one through overload resolution (13.3)),
2292 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2293 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2294 Initializer,
2295 /*AllowRValues=*/false,
2296 Sequence);
2297 if (ConvOvlResult == OR_Success)
2298 return;
2299 }
2300 }
2301
2302 // - Otherwise, the reference shall be an lvalue reference to a
2303 // non-volatile const type (i.e., cv1 shall be const), or the reference
2304 // shall be an rvalue reference and the initializer expression shall
2305 // be an rvalue.
2306 if (!((isLValueRef && cv1T1.getCVRQualifiers() == Qualifiers::Const) ||
2307 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2308 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2309 Sequence.SetOverloadFailure(
2310 InitializationSequence::FK_ReferenceInitOverloadFailed,
2311 ConvOvlResult);
2312 else if (isLValueRef)
2313 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2314 ? (RefRelationship == Sema::Ref_Related
2315 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2316 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2317 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2318 else
2319 Sequence.SetFailed(
2320 InitializationSequence::FK_RValueReferenceBindingToLValue);
2321
2322 return;
2323 }
2324
2325 // - If T1 and T2 are class types and
2326 if (T1->isRecordType() && T2->isRecordType()) {
2327 // - the initializer expression is an rvalue and "cv1 T1" is
2328 // reference-compatible with "cv2 T2", or
2329 if (InitLvalue != Expr::LV_Valid &&
2330 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2331 if (DerivedToBase)
2332 Sequence.AddDerivedToBaseCastStep(
2333 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()),
2334 /*isLValue=*/false);
2335 if (cv1T1.getQualifiers() != cv2T2.getQualifiers())
2336 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2337 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2338 return;
2339 }
2340
2341 // - T1 is not reference-related to T2 and the initializer expression
2342 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2343 // conversion is selected by enumerating the applicable conversion
2344 // functions (13.3.1.6) and choosing the best one through overload
2345 // resolution (13.3)),
2346 if (RefRelationship == Sema::Ref_Incompatible) {
2347 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2348 Kind, Initializer,
2349 /*AllowRValues=*/true,
2350 Sequence);
2351 if (ConvOvlResult)
2352 Sequence.SetOverloadFailure(
2353 InitializationSequence::FK_ReferenceInitOverloadFailed,
2354 ConvOvlResult);
2355
2356 return;
2357 }
2358
2359 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2360 return;
2361 }
2362
2363 // - If the initializer expression is an rvalue, with T2 an array type,
2364 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2365 // is bound to the object represented by the rvalue (see 3.10).
2366 // FIXME: How can an array type be reference-compatible with anything?
2367 // Don't we mean the element types of T1 and T2?
2368
2369 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2370 // from the initializer expression using the rules for a non-reference
2371 // copy initialization (8.5). The reference is then bound to the
2372 // temporary. [...]
2373 // Determine whether we are allowed to call explicit constructors or
2374 // explicit conversion operators.
2375 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2376 ImplicitConversionSequence ICS
2377 = S.TryImplicitConversion(Initializer, cv1T1,
2378 /*SuppressUserConversions=*/false, AllowExplicit,
2379 /*ForceRValue=*/false,
2380 /*FIXME:InOverloadResolution=*/false,
2381 /*UserCast=*/Kind.isExplicitCast());
2382
2383 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
2384 // FIXME: Use the conversion function set stored in ICS to turn
2385 // this into an overloading ambiguity diagnostic. However, we need
2386 // to keep that set as an OverloadCandidateSet rather than as some
2387 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002388 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2389 Sequence.SetOverloadFailure(
2390 InitializationSequence::FK_ReferenceInitOverloadFailed,
2391 ConvOvlResult);
2392 else
2393 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002394 return;
2395 }
2396
2397 // [...] If T1 is reference-related to T2, cv1 must be the
2398 // same cv-qualification as, or greater cv-qualification
2399 // than, cv2; otherwise, the program is ill-formed.
2400 if (RefRelationship == Sema::Ref_Related &&
2401 !cv1T1.isAtLeastAsQualifiedAs(cv2T2)) {
2402 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2403 return;
2404 }
2405
2406 // Perform the actual conversion.
2407 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2408 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2409 return;
2410}
2411
2412/// \brief Attempt character array initialization from a string literal
2413/// (C++ [dcl.init.string], C99 6.7.8).
2414static void TryStringLiteralInitialization(Sema &S,
2415 const InitializedEntity &Entity,
2416 const InitializationKind &Kind,
2417 Expr *Initializer,
2418 InitializationSequence &Sequence) {
Eli Friedman78275202009-12-19 08:11:05 +00002419 Sequence.setSequenceKind(InitializationSequence::StringInit);
2420 Sequence.AddStringInitStep(Entity.getType().getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002421}
2422
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002423/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2424/// enumerates the constructors of the initialized entity and performs overload
2425/// resolution to select the best.
2426static void TryConstructorInitialization(Sema &S,
2427 const InitializedEntity &Entity,
2428 const InitializationKind &Kind,
2429 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002430 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002431 InitializationSequence &Sequence) {
Douglas Gregore1314a62009-12-18 05:02:21 +00002432 if (Kind.getKind() == InitializationKind::IK_Copy)
2433 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2434 else
2435 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002436
2437 // Build the candidate set directly in the initialization sequence
2438 // structure, so that it will persist if we fail.
2439 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2440 CandidateSet.clear();
2441
2442 // Determine whether we are allowed to call explicit constructors or
2443 // explicit conversion operators.
2444 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2445 Kind.getKind() == InitializationKind::IK_Value ||
2446 Kind.getKind() == InitializationKind::IK_Default);
2447
2448 // The type we're converting to is a class type. Enumerate its constructors
2449 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002450 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2451 assert(DestRecordType && "Constructor initialization requires record type");
2452 CXXRecordDecl *DestRecordDecl
2453 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2454
2455 DeclarationName ConstructorName
2456 = S.Context.DeclarationNames.getCXXConstructorName(
2457 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2458 DeclContext::lookup_iterator Con, ConEnd;
2459 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2460 Con != ConEnd; ++Con) {
2461 // Find the constructor (which may be a template).
2462 CXXConstructorDecl *Constructor = 0;
2463 FunctionTemplateDecl *ConstructorTmpl
2464 = dyn_cast<FunctionTemplateDecl>(*Con);
2465 if (ConstructorTmpl)
2466 Constructor = cast<CXXConstructorDecl>(
2467 ConstructorTmpl->getTemplatedDecl());
2468 else
2469 Constructor = cast<CXXConstructorDecl>(*Con);
2470
2471 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002472 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002473 if (ConstructorTmpl)
2474 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2475 Args, NumArgs, CandidateSet);
2476 else
2477 S.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2478 }
2479 }
2480
2481 SourceLocation DeclLoc = Kind.getLocation();
2482
2483 // Perform overload resolution. If it fails, return the failed result.
2484 OverloadCandidateSet::iterator Best;
2485 if (OverloadingResult Result
2486 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2487 Sequence.SetOverloadFailure(
2488 InitializationSequence::FK_ConstructorOverloadFailed,
2489 Result);
2490 return;
2491 }
2492
2493 // Add the constructor initialization step. Any cv-qualification conversion is
2494 // subsumed by the initialization.
Douglas Gregore1314a62009-12-18 05:02:21 +00002495 if (Kind.getKind() == InitializationKind::IK_Copy) {
2496 Sequence.AddUserConversionStep(Best->Function, DestType);
2497 } else {
2498 Sequence.AddConstructorInitializationStep(
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002499 cast<CXXConstructorDecl>(Best->Function),
Douglas Gregore1314a62009-12-18 05:02:21 +00002500 DestType);
2501 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002502}
2503
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002504/// \brief Attempt value initialization (C++ [dcl.init]p7).
2505static void TryValueInitialization(Sema &S,
2506 const InitializedEntity &Entity,
2507 const InitializationKind &Kind,
2508 InitializationSequence &Sequence) {
2509 // C++ [dcl.init]p5:
2510 //
2511 // To value-initialize an object of type T means:
2512 QualType T = Entity.getType().getType();
2513
2514 // -- if T is an array type, then each element is value-initialized;
2515 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2516 T = AT->getElementType();
2517
2518 if (const RecordType *RT = T->getAs<RecordType>()) {
2519 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2520 // -- if T is a class type (clause 9) with a user-declared
2521 // constructor (12.1), then the default constructor for T is
2522 // called (and the initialization is ill-formed if T has no
2523 // accessible default constructor);
2524 //
2525 // FIXME: we really want to refer to a single subobject of the array,
2526 // but Entity doesn't have a way to capture that (yet).
2527 if (ClassDecl->hasUserDeclaredConstructor())
2528 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2529
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002530 // -- if T is a (possibly cv-qualified) non-union class type
2531 // without a user-provided constructor, then the object is
2532 // zero-initialized and, if T’s implicitly-declared default
2533 // constructor is non-trivial, that constructor is called.
2534 if ((ClassDecl->getTagKind() == TagDecl::TK_class ||
2535 ClassDecl->getTagKind() == TagDecl::TK_struct) &&
2536 !ClassDecl->hasTrivialConstructor()) {
2537 Sequence.AddZeroInitializationStep(Entity.getType().getType());
2538 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2539 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002540 }
2541 }
2542
2543 Sequence.AddZeroInitializationStep(Entity.getType().getType());
2544 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2545}
2546
Douglas Gregor85dabae2009-12-16 01:38:02 +00002547/// \brief Attempt default initialization (C++ [dcl.init]p6).
2548static void TryDefaultInitialization(Sema &S,
2549 const InitializedEntity &Entity,
2550 const InitializationKind &Kind,
2551 InitializationSequence &Sequence) {
2552 assert(Kind.getKind() == InitializationKind::IK_Default);
2553
2554 // C++ [dcl.init]p6:
2555 // To default-initialize an object of type T means:
2556 // - if T is an array type, each element is default-initialized;
2557 QualType DestType = Entity.getType().getType();
2558 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2559 DestType = Array->getElementType();
2560
2561 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2562 // constructor for T is called (and the initialization is ill-formed if
2563 // T has no accessible default constructor);
2564 if (DestType->isRecordType()) {
2565 // FIXME: If a program calls for the default initialization of an object of
2566 // a const-qualified type T, T shall be a class type with a user-provided
2567 // default constructor.
2568 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2569 Sequence);
2570 }
2571
2572 // - otherwise, no initialization is performed.
2573 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2574
2575 // If a program calls for the default initialization of an object of
2576 // a const-qualified type T, T shall be a class type with a user-provided
2577 // default constructor.
2578 if (DestType.isConstQualified())
2579 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2580}
2581
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002582/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2583/// which enumerates all conversion functions and performs overload resolution
2584/// to select the best.
2585static void TryUserDefinedConversion(Sema &S,
2586 const InitializedEntity &Entity,
2587 const InitializationKind &Kind,
2588 Expr *Initializer,
2589 InitializationSequence &Sequence) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002590 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2591
2592 QualType DestType = Entity.getType().getType();
2593 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2594 QualType SourceType = Initializer->getType();
2595 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2596 "Must have a class type to perform a user-defined conversion");
2597
2598 // Build the candidate set directly in the initialization sequence
2599 // structure, so that it will persist if we fail.
2600 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2601 CandidateSet.clear();
2602
2603 // Determine whether we are allowed to call explicit constructors or
2604 // explicit conversion operators.
2605 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2606
2607 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2608 // The type we're converting to is a class type. Enumerate its constructors
2609 // to see if there is a suitable conversion.
2610 CXXRecordDecl *DestRecordDecl
2611 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2612
2613 DeclarationName ConstructorName
2614 = S.Context.DeclarationNames.getCXXConstructorName(
2615 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2616 DeclContext::lookup_iterator Con, ConEnd;
2617 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2618 Con != ConEnd; ++Con) {
2619 // Find the constructor (which may be a template).
2620 CXXConstructorDecl *Constructor = 0;
2621 FunctionTemplateDecl *ConstructorTmpl
2622 = dyn_cast<FunctionTemplateDecl>(*Con);
2623 if (ConstructorTmpl)
2624 Constructor = cast<CXXConstructorDecl>(
2625 ConstructorTmpl->getTemplatedDecl());
2626 else
2627 Constructor = cast<CXXConstructorDecl>(*Con);
2628
2629 if (!Constructor->isInvalidDecl() &&
2630 Constructor->isConvertingConstructor(AllowExplicit)) {
2631 if (ConstructorTmpl)
2632 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2633 &Initializer, 1, CandidateSet);
2634 else
2635 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2636 }
2637 }
2638 }
Eli Friedman78275202009-12-19 08:11:05 +00002639
2640 SourceLocation DeclLoc = Initializer->getLocStart();
2641
Douglas Gregor540c3b02009-12-14 17:27:33 +00002642 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2643 // The type we're converting from is a class type, enumerate its conversion
2644 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00002645
Eli Friedman4afe9a32009-12-20 22:12:03 +00002646 // We can only enumerate the conversion functions for a complete type; if
2647 // the type isn't complete, simply skip this step.
2648 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2649 CXXRecordDecl *SourceRecordDecl
2650 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002651
Eli Friedman4afe9a32009-12-20 22:12:03 +00002652 const UnresolvedSet *Conversions
2653 = SourceRecordDecl->getVisibleConversionFunctions();
2654 for (UnresolvedSet::iterator I = Conversions->begin(),
2655 E = Conversions->end();
2656 I != E; ++I) {
2657 NamedDecl *D = *I;
2658 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2659 if (isa<UsingShadowDecl>(D))
2660 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2661
2662 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2663 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00002664 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00002665 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002666 else
Eli Friedman4afe9a32009-12-20 22:12:03 +00002667 Conv = cast<CXXConversionDecl>(*I);
2668
2669 if (AllowExplicit || !Conv->isExplicit()) {
2670 if (ConvTemplate)
2671 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC,
2672 Initializer, DestType,
2673 CandidateSet);
2674 else
2675 S.AddConversionCandidate(Conv, ActingDC, Initializer, DestType,
2676 CandidateSet);
2677 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002678 }
2679 }
2680 }
2681
Douglas Gregor540c3b02009-12-14 17:27:33 +00002682 // Perform overload resolution. If it fails, return the failed result.
2683 OverloadCandidateSet::iterator Best;
2684 if (OverloadingResult Result
2685 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2686 Sequence.SetOverloadFailure(
2687 InitializationSequence::FK_UserConversionOverloadFailed,
2688 Result);
2689 return;
2690 }
2691
2692 FunctionDecl *Function = Best->Function;
2693
2694 if (isa<CXXConstructorDecl>(Function)) {
2695 // Add the user-defined conversion step. Any cv-qualification conversion is
2696 // subsumed by the initialization.
2697 Sequence.AddUserConversionStep(Function, DestType);
2698 return;
2699 }
2700
2701 // Add the user-defined conversion step that calls the conversion function.
2702 QualType ConvType = Function->getResultType().getNonReferenceType();
2703 Sequence.AddUserConversionStep(Function, ConvType);
2704
2705 // If the conversion following the call to the conversion function is
2706 // interesting, add it as a separate step.
2707 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2708 Best->FinalConversion.Third) {
2709 ImplicitConversionSequence ICS;
2710 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2711 ICS.Standard = Best->FinalConversion;
2712 Sequence.AddConversionSequenceStep(ICS, DestType);
2713 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002714}
2715
2716/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2717/// non-class type to another.
2718static void TryImplicitConversion(Sema &S,
2719 const InitializedEntity &Entity,
2720 const InitializationKind &Kind,
2721 Expr *Initializer,
2722 InitializationSequence &Sequence) {
2723 ImplicitConversionSequence ICS
2724 = S.TryImplicitConversion(Initializer, Entity.getType().getType(),
2725 /*SuppressUserConversions=*/true,
2726 /*AllowExplicit=*/false,
2727 /*ForceRValue=*/false,
2728 /*FIXME:InOverloadResolution=*/false,
2729 /*UserCast=*/Kind.isExplicitCast());
2730
2731 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
2732 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2733 return;
2734 }
2735
2736 Sequence.AddConversionSequenceStep(ICS, Entity.getType().getType());
2737}
2738
2739InitializationSequence::InitializationSequence(Sema &S,
2740 const InitializedEntity &Entity,
2741 const InitializationKind &Kind,
2742 Expr **Args,
2743 unsigned NumArgs) {
2744 ASTContext &Context = S.Context;
2745
2746 // C++0x [dcl.init]p16:
2747 // The semantics of initializers are as follows. The destination type is
2748 // the type of the object or reference being initialized and the source
2749 // type is the type of the initializer expression. The source type is not
2750 // defined when the initializer is a braced-init-list or when it is a
2751 // parenthesized list of expressions.
2752 QualType DestType = Entity.getType().getType();
2753
2754 if (DestType->isDependentType() ||
2755 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2756 SequenceKind = DependentSequence;
2757 return;
2758 }
2759
2760 QualType SourceType;
2761 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00002762 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002763 Initializer = Args[0];
2764 if (!isa<InitListExpr>(Initializer))
2765 SourceType = Initializer->getType();
2766 }
2767
2768 // - If the initializer is a braced-init-list, the object is
2769 // list-initialized (8.5.4).
2770 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2771 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00002772 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002773 }
2774
2775 // - If the destination type is a reference type, see 8.5.3.
2776 if (DestType->isReferenceType()) {
2777 // C++0x [dcl.init.ref]p1:
2778 // A variable declared to be a T& or T&&, that is, "reference to type T"
2779 // (8.3.2), shall be initialized by an object, or function, of type T or
2780 // by an object that can be converted into a T.
2781 // (Therefore, multiple arguments are not permitted.)
2782 if (NumArgs != 1)
2783 SetFailed(FK_TooManyInitsForReference);
2784 else
2785 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2786 return;
2787 }
2788
2789 // - If the destination type is an array of characters, an array of
2790 // char16_t, an array of char32_t, or an array of wchar_t, and the
2791 // initializer is a string literal, see 8.5.2.
2792 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2793 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2794 return;
2795 }
2796
2797 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002798 if (Kind.getKind() == InitializationKind::IK_Value ||
2799 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002800 TryValueInitialization(S, Entity, Kind, *this);
2801 return;
2802 }
2803
Douglas Gregor85dabae2009-12-16 01:38:02 +00002804 // Handle default initialization.
2805 if (Kind.getKind() == InitializationKind::IK_Default){
2806 TryDefaultInitialization(S, Entity, Kind, *this);
2807 return;
2808 }
Douglas Gregore1314a62009-12-18 05:02:21 +00002809
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002810 // - Otherwise, if the destination type is an array, the program is
2811 // ill-formed.
2812 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2813 if (AT->getElementType()->isAnyCharacterType())
2814 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2815 else
2816 SetFailed(FK_ArrayNeedsInitList);
2817
2818 return;
2819 }
Eli Friedman78275202009-12-19 08:11:05 +00002820
2821 // Handle initialization in C
2822 if (!S.getLangOptions().CPlusPlus) {
2823 setSequenceKind(CAssignment);
2824 AddCAssignmentStep(DestType);
2825 return;
2826 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002827
2828 // - If the destination type is a (possibly cv-qualified) class type:
2829 if (DestType->isRecordType()) {
2830 // - If the initialization is direct-initialization, or if it is
2831 // copy-initialization where the cv-unqualified version of the
2832 // source type is the same class as, or a derived class of, the
2833 // class of the destination, constructors are considered. [...]
2834 if (Kind.getKind() == InitializationKind::IK_Direct ||
2835 (Kind.getKind() == InitializationKind::IK_Copy &&
2836 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2837 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002838 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
2839 Entity.getType().getType(), *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002840 // - Otherwise (i.e., for the remaining copy-initialization cases),
2841 // user-defined conversion sequences that can convert from the source
2842 // type to the destination type or (when a conversion function is
2843 // used) to a derived class thereof are enumerated as described in
2844 // 13.3.1.4, and the best one is chosen through overload resolution
2845 // (13.3).
2846 else
2847 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2848 return;
2849 }
2850
Douglas Gregor85dabae2009-12-16 01:38:02 +00002851 if (NumArgs > 1) {
2852 SetFailed(FK_TooManyInitsForScalar);
2853 return;
2854 }
2855 assert(NumArgs == 1 && "Zero-argument case handled above");
2856
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002857 // - Otherwise, if the source type is a (possibly cv-qualified) class
2858 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002859 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002860 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2861 return;
2862 }
2863
2864 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00002865 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002866 // conversions (Clause 4) will be used, if necessary, to convert the
2867 // initializer expression to the cv-unqualified version of the
2868 // destination type; no user-defined conversions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002869 setSequenceKind(StandardConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002870 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
2871}
2872
2873InitializationSequence::~InitializationSequence() {
2874 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
2875 StepEnd = Steps.end();
2876 Step != StepEnd; ++Step)
2877 Step->Destroy();
2878}
2879
2880//===----------------------------------------------------------------------===//
2881// Perform initialization
2882//===----------------------------------------------------------------------===//
Douglas Gregore1314a62009-12-18 05:02:21 +00002883static Sema::AssignmentAction
2884getAssignmentAction(const InitializedEntity &Entity) {
2885 switch(Entity.getKind()) {
2886 case InitializedEntity::EK_Variable:
2887 case InitializedEntity::EK_New:
2888 return Sema::AA_Initializing;
2889
2890 case InitializedEntity::EK_Parameter:
2891 // FIXME: Can we tell when we're sending vs. passing?
2892 return Sema::AA_Passing;
2893
2894 case InitializedEntity::EK_Result:
2895 return Sema::AA_Returning;
2896
2897 case InitializedEntity::EK_Exception:
2898 case InitializedEntity::EK_Base:
2899 llvm_unreachable("No assignment action for C++-specific initialization");
2900 break;
2901
2902 case InitializedEntity::EK_Temporary:
2903 // FIXME: Can we tell apart casting vs. converting?
2904 return Sema::AA_Casting;
2905
2906 case InitializedEntity::EK_Member:
2907 case InitializedEntity::EK_ArrayOrVectorElement:
2908 return Sema::AA_Initializing;
2909 }
2910
2911 return Sema::AA_Converting;
2912}
2913
2914static bool shouldBindAsTemporary(const InitializedEntity &Entity,
2915 bool IsCopy) {
2916 switch (Entity.getKind()) {
2917 case InitializedEntity::EK_Result:
2918 case InitializedEntity::EK_Exception:
2919 return !IsCopy;
2920
2921 case InitializedEntity::EK_New:
2922 case InitializedEntity::EK_Variable:
2923 case InitializedEntity::EK_Base:
2924 case InitializedEntity::EK_Member:
2925 case InitializedEntity::EK_ArrayOrVectorElement:
2926 return false;
2927
2928 case InitializedEntity::EK_Parameter:
2929 case InitializedEntity::EK_Temporary:
2930 return true;
2931 }
2932
2933 llvm_unreachable("missed an InitializedEntity kind?");
2934}
2935
2936/// \brief If we need to perform an additional copy of the initialized object
2937/// for this kind of entity (e.g., the result of a function or an object being
2938/// thrown), make the copy.
2939static Sema::OwningExprResult CopyIfRequiredForEntity(Sema &S,
2940 const InitializedEntity &Entity,
Douglas Gregora4b592a2009-12-19 03:01:41 +00002941 const InitializationKind &Kind,
Douglas Gregore1314a62009-12-18 05:02:21 +00002942 Sema::OwningExprResult CurInit) {
2943 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00002944
2945 switch (Entity.getKind()) {
2946 case InitializedEntity::EK_Result:
2947 if (Entity.getType().getType()->isReferenceType())
2948 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00002949 Loc = Entity.getReturnLoc();
2950 break;
2951
2952 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002953 Loc = Entity.getThrowLoc();
2954 break;
2955
2956 case InitializedEntity::EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002957 if (Entity.getType().getType()->isReferenceType() ||
2958 Kind.getKind() != InitializationKind::IK_Copy)
2959 return move(CurInit);
2960 Loc = Entity.getDecl()->getLocation();
2961 break;
2962
Douglas Gregore1314a62009-12-18 05:02:21 +00002963 case InitializedEntity::EK_Parameter:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002964 // FIXME: Do we need this initialization for a parameter?
2965 return move(CurInit);
2966
Douglas Gregore1314a62009-12-18 05:02:21 +00002967 case InitializedEntity::EK_New:
2968 case InitializedEntity::EK_Temporary:
2969 case InitializedEntity::EK_Base:
2970 case InitializedEntity::EK_Member:
2971 case InitializedEntity::EK_ArrayOrVectorElement:
2972 // We don't need to copy for any of these initialized entities.
2973 return move(CurInit);
2974 }
2975
2976 Expr *CurInitExpr = (Expr *)CurInit.get();
2977 CXXRecordDecl *Class = 0;
2978 if (const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>())
2979 Class = cast<CXXRecordDecl>(Record->getDecl());
2980 if (!Class)
2981 return move(CurInit);
2982
2983 // Perform overload resolution using the class's copy constructors.
2984 DeclarationName ConstructorName
2985 = S.Context.DeclarationNames.getCXXConstructorName(
2986 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
2987 DeclContext::lookup_iterator Con, ConEnd;
2988 OverloadCandidateSet CandidateSet;
2989 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
2990 Con != ConEnd; ++Con) {
2991 // Find the constructor (which may be a template).
2992 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
2993 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor507eb872009-12-22 00:34:07 +00002994 !Constructor->isCopyConstructor())
Douglas Gregore1314a62009-12-18 05:02:21 +00002995 continue;
2996
2997 S.AddOverloadCandidate(Constructor, &CurInitExpr, 1, CandidateSet);
2998 }
2999
3000 OverloadCandidateSet::iterator Best;
3001 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3002 case OR_Success:
3003 break;
3004
3005 case OR_No_Viable_Function:
3006 S.Diag(Loc, diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003007 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003008 << CurInitExpr->getSourceRange();
3009 S.PrintOverloadCandidates(CandidateSet, false);
3010 return S.ExprError();
3011
3012 case OR_Ambiguous:
3013 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003014 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003015 << CurInitExpr->getSourceRange();
3016 S.PrintOverloadCandidates(CandidateSet, true);
3017 return S.ExprError();
3018
3019 case OR_Deleted:
3020 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003021 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003022 << CurInitExpr->getSourceRange();
3023 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3024 << Best->Function->isDeleted();
3025 return S.ExprError();
3026 }
3027
3028 CurInit.release();
3029 return S.BuildCXXConstructExpr(Loc, CurInitExpr->getType(),
3030 cast<CXXConstructorDecl>(Best->Function),
3031 /*Elidable=*/true,
3032 Sema::MultiExprArg(S,
3033 (void**)&CurInitExpr, 1));
3034}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003035
3036Action::OwningExprResult
3037InitializationSequence::Perform(Sema &S,
3038 const InitializedEntity &Entity,
3039 const InitializationKind &Kind,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003040 Action::MultiExprArg Args,
3041 QualType *ResultType) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003042 if (SequenceKind == FailedSequence) {
3043 unsigned NumArgs = Args.size();
3044 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3045 return S.ExprError();
3046 }
3047
3048 if (SequenceKind == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003049 // If the declaration is a non-dependent, incomplete array type
3050 // that has an initializer, then its type will be completed once
3051 // the initializer is instantiated.
3052 if (ResultType && !Entity.getType().getType()->isDependentType() &&
3053 Args.size() == 1) {
3054 QualType DeclType = Entity.getType().getType();
3055 if (const IncompleteArrayType *ArrayT
3056 = S.Context.getAsIncompleteArrayType(DeclType)) {
3057 // FIXME: We don't currently have the ability to accurately
3058 // compute the length of an initializer list without
3059 // performing full type-checking of the initializer list
3060 // (since we have to determine where braces are implicitly
3061 // introduced and such). So, we fall back to making the array
3062 // type a dependently-sized array type with no specified
3063 // bound.
3064 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3065 SourceRange Brackets;
3066 // Scavange the location of the brackets from the entity, if we can.
3067 if (isa<IncompleteArrayTypeLoc>(Entity.getType())) {
3068 IncompleteArrayTypeLoc ArrayLoc
3069 = cast<IncompleteArrayTypeLoc>(Entity.getType());
3070 Brackets = ArrayLoc.getBracketsRange();
3071 }
3072
3073 *ResultType
3074 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3075 /*NumElts=*/0,
3076 ArrayT->getSizeModifier(),
3077 ArrayT->getIndexTypeCVRQualifiers(),
3078 Brackets);
3079 }
3080
3081 }
3082 }
3083
Eli Friedmana553d4a2009-12-22 02:35:53 +00003084 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003085 return Sema::OwningExprResult(S, Args.release()[0]);
3086
3087 unsigned NumArgs = Args.size();
3088 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3089 SourceLocation(),
3090 (Expr **)Args.release(),
3091 NumArgs,
3092 SourceLocation()));
3093 }
3094
Douglas Gregor85dabae2009-12-16 01:38:02 +00003095 if (SequenceKind == NoInitialization)
3096 return S.Owned((Expr *)0);
3097
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003098 QualType DestType = Entity.getType().getType().getNonReferenceType();
Eli Friedman463e5232009-12-22 02:10:53 +00003099 // FIXME: Ugly hack around the fact that Entity.getType().getType() is not
3100 // the same as Entity.getDecl()->getType() in cases involving type merging,
3101 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003102 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003103 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
3104 Entity.getType().getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003105
Douglas Gregor85dabae2009-12-16 01:38:02 +00003106 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3107
3108 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3109
3110 // For initialization steps that start with a single initializer,
3111 // grab the only argument out the Args and place it into the "current"
3112 // initializer.
3113 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003114 case SK_ResolveAddressOfOverloadedFunction:
3115 case SK_CastDerivedToBaseRValue:
3116 case SK_CastDerivedToBaseLValue:
3117 case SK_BindReference:
3118 case SK_BindReferenceToTemporary:
3119 case SK_UserConversion:
3120 case SK_QualificationConversionLValue:
3121 case SK_QualificationConversionRValue:
3122 case SK_ConversionSequence:
3123 case SK_ListInitialization:
3124 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003125 case SK_StringInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00003126 assert(Args.size() == 1);
3127 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3128 if (CurInit.isInvalid())
3129 return S.ExprError();
3130 break;
3131
3132 case SK_ConstructorInitialization:
3133 case SK_ZeroInitialization:
3134 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003135 }
3136
3137 // Walk through the computed steps for the initialization sequence,
3138 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003139 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003140 for (step_iterator Step = step_begin(), StepEnd = step_end();
3141 Step != StepEnd; ++Step) {
3142 if (CurInit.isInvalid())
3143 return S.ExprError();
3144
3145 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003146 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003147
3148 switch (Step->Kind) {
3149 case SK_ResolveAddressOfOverloadedFunction:
3150 // Overload resolution determined which function invoke; update the
3151 // initializer to reflect that choice.
3152 CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function);
3153 break;
3154
3155 case SK_CastDerivedToBaseRValue:
3156 case SK_CastDerivedToBaseLValue: {
3157 // We have a derived-to-base cast that produces either an rvalue or an
3158 // lvalue. Perform that cast.
3159
3160 // Casts to inaccessible base classes are allowed with C-style casts.
3161 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3162 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3163 CurInitExpr->getLocStart(),
3164 CurInitExpr->getSourceRange(),
3165 IgnoreBaseAccess))
3166 return S.ExprError();
3167
3168 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3169 CastExpr::CK_DerivedToBase,
3170 (Expr*)CurInit.release(),
3171 Step->Kind == SK_CastDerivedToBaseLValue));
3172 break;
3173 }
3174
3175 case SK_BindReference:
3176 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3177 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3178 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
3179 << Entity.getType().getType().isVolatileQualified()
3180 << BitField->getDeclName()
3181 << CurInitExpr->getSourceRange();
3182 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3183 return S.ExprError();
3184 }
3185
3186 // Reference binding does not have any corresponding ASTs.
3187
3188 // Check exception specifications
3189 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3190 return S.ExprError();
3191 break;
3192
3193 case SK_BindReferenceToTemporary:
3194 // Check exception specifications
3195 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3196 return S.ExprError();
3197
3198 // FIXME: At present, we have no AST to describe when we need to make a
3199 // temporary to bind a reference to. We should.
3200 break;
3201
3202 case SK_UserConversion: {
3203 // We have a user-defined conversion that invokes either a constructor
3204 // or a conversion function.
3205 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregore1314a62009-12-18 05:02:21 +00003206 bool IsCopy = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003207 if (CXXConstructorDecl *Constructor
3208 = dyn_cast<CXXConstructorDecl>(Step->Function)) {
3209 // Build a call to the selected constructor.
3210 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3211 SourceLocation Loc = CurInitExpr->getLocStart();
3212 CurInit.release(); // Ownership transferred into MultiExprArg, below.
3213
3214 // Determine the arguments required to actually perform the constructor
3215 // call.
3216 if (S.CompleteConstructorCall(Constructor,
3217 Sema::MultiExprArg(S,
3218 (void **)&CurInitExpr,
3219 1),
3220 Loc, ConstructorArgs))
3221 return S.ExprError();
3222
3223 // Build the an expression that constructs a temporary.
3224 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3225 move_arg(ConstructorArgs));
3226 if (CurInit.isInvalid())
3227 return S.ExprError();
3228
3229 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00003230 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3231 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3232 S.IsDerivedFrom(SourceType, Class))
3233 IsCopy = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003234 } else {
3235 // Build a call to the conversion function.
3236 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function);
Douglas Gregore1314a62009-12-18 05:02:21 +00003237
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003238 // FIXME: Should we move this initialization into a separate
3239 // derived-to-base conversion? I believe the answer is "no", because
3240 // we don't want to turn off access control here for c-style casts.
3241 if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion))
3242 return S.ExprError();
3243
3244 // Do a little dance to make sure that CurInit has the proper
3245 // pointer.
3246 CurInit.release();
3247
3248 // Build the actual call to the conversion function.
3249 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3250 if (CurInit.isInvalid() || !CurInit.get())
3251 return S.ExprError();
3252
3253 CastKind = CastExpr::CK_UserDefinedConversion;
3254 }
3255
Douglas Gregore1314a62009-12-18 05:02:21 +00003256 if (shouldBindAsTemporary(Entity, IsCopy))
3257 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3258
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003259 CurInitExpr = CurInit.takeAs<Expr>();
3260 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3261 CastKind,
3262 CurInitExpr,
Douglas Gregore1314a62009-12-18 05:02:21 +00003263 false));
3264
3265 if (!IsCopy)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003266 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003267 break;
3268 }
3269
3270 case SK_QualificationConversionLValue:
3271 case SK_QualificationConversionRValue:
3272 // Perform a qualification conversion; these can never go wrong.
3273 S.ImpCastExprToType(CurInitExpr, Step->Type,
3274 CastExpr::CK_NoOp,
3275 Step->Kind == SK_QualificationConversionLValue);
3276 CurInit.release();
3277 CurInit = S.Owned(CurInitExpr);
3278 break;
3279
3280 case SK_ConversionSequence:
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003281 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003282 false, false, *Step->ICS))
3283 return S.ExprError();
3284
3285 CurInit.release();
3286 CurInit = S.Owned(CurInitExpr);
3287 break;
Douglas Gregor51e77d52009-12-10 17:56:55 +00003288
3289 case SK_ListInitialization: {
3290 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3291 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00003292 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregor51e77d52009-12-10 17:56:55 +00003293 return S.ExprError();
3294
3295 CurInit.release();
3296 CurInit = S.Owned(InitList);
3297 break;
3298 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003299
3300 case SK_ConstructorInitialization: {
3301 CXXConstructorDecl *Constructor
3302 = cast<CXXConstructorDecl>(Step->Function);
3303
3304 // Build a call to the selected constructor.
3305 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3306 SourceLocation Loc = Kind.getLocation();
3307
3308 // Determine the arguments required to actually perform the constructor
3309 // call.
3310 if (S.CompleteConstructorCall(Constructor, move(Args),
3311 Loc, ConstructorArgs))
3312 return S.ExprError();
3313
3314 // Build the an expression that constructs a temporary.
Douglas Gregor39c778b2009-12-20 22:01:25 +00003315 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType().getType(),
3316 Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003317 move_arg(ConstructorArgs),
3318 ConstructorInitRequiresZeroInit);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003319 if (CurInit.isInvalid())
3320 return S.ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003321
3322 bool Elidable
3323 = cast<CXXConstructExpr>((Expr *)CurInit.get())->isElidable();
3324 if (shouldBindAsTemporary(Entity, Elidable))
3325 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3326
3327 if (!Elidable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003328 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003329 break;
3330 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003331
3332 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003333 step_iterator NextStep = Step;
3334 ++NextStep;
3335 if (NextStep != StepEnd &&
3336 NextStep->Kind == SK_ConstructorInitialization) {
3337 // The need for zero-initialization is recorded directly into
3338 // the call to the object's constructor within the next step.
3339 ConstructorInitRequiresZeroInit = true;
3340 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3341 S.getLangOptions().CPlusPlus &&
3342 !Kind.isImplicitValueInit()) {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003343 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3344 Kind.getRange().getBegin(),
3345 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003346 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003347 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003348 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003349 break;
3350 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003351
3352 case SK_CAssignment: {
3353 QualType SourceType = CurInitExpr->getType();
3354 Sema::AssignConvertType ConvTy =
3355 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregor96596c92009-12-22 07:24:36 +00003356
3357 // If this is a call, allow conversion to a transparent union.
3358 if (ConvTy != Sema::Compatible &&
3359 Entity.getKind() == InitializedEntity::EK_Parameter &&
3360 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3361 == Sema::Compatible)
3362 ConvTy = Sema::Compatible;
3363
Douglas Gregore1314a62009-12-18 05:02:21 +00003364 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3365 Step->Type, SourceType,
3366 CurInitExpr, getAssignmentAction(Entity)))
3367 return S.ExprError();
3368
3369 CurInit.release();
3370 CurInit = S.Owned(CurInitExpr);
3371 break;
3372 }
Eli Friedman78275202009-12-19 08:11:05 +00003373
3374 case SK_StringInit: {
3375 QualType Ty = Step->Type;
3376 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3377 break;
3378 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003379 }
3380 }
3381
3382 return move(CurInit);
3383}
3384
3385//===----------------------------------------------------------------------===//
3386// Diagnose initialization failures
3387//===----------------------------------------------------------------------===//
3388bool InitializationSequence::Diagnose(Sema &S,
3389 const InitializedEntity &Entity,
3390 const InitializationKind &Kind,
3391 Expr **Args, unsigned NumArgs) {
3392 if (SequenceKind != FailedSequence)
3393 return false;
3394
3395 QualType DestType = Entity.getType().getType();
3396 switch (Failure) {
3397 case FK_TooManyInitsForReference:
3398 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3399 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
3400 break;
3401
3402 case FK_ArrayNeedsInitList:
3403 case FK_ArrayNeedsInitListOrStringLiteral:
3404 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3405 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3406 break;
3407
3408 case FK_AddressOfOverloadFailed:
3409 S.ResolveAddressOfOverloadedFunction(Args[0],
3410 DestType.getNonReferenceType(),
3411 true);
3412 break;
3413
3414 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00003415 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003416 switch (FailedOverloadResult) {
3417 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00003418 if (Failure == FK_UserConversionOverloadFailed)
3419 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3420 << Args[0]->getType() << DestType
3421 << Args[0]->getSourceRange();
3422 else
3423 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3424 << DestType << Args[0]->getType()
3425 << Args[0]->getSourceRange();
3426
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003427 S.PrintOverloadCandidates(FailedCandidateSet, true);
3428 break;
3429
3430 case OR_No_Viable_Function:
3431 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3432 << Args[0]->getType() << DestType.getNonReferenceType()
3433 << Args[0]->getSourceRange();
3434 S.PrintOverloadCandidates(FailedCandidateSet, false);
3435 break;
3436
3437 case OR_Deleted: {
3438 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3439 << Args[0]->getType() << DestType.getNonReferenceType()
3440 << Args[0]->getSourceRange();
3441 OverloadCandidateSet::iterator Best;
3442 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3443 Kind.getLocation(),
3444 Best);
3445 if (Ovl == OR_Deleted) {
3446 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3447 << Best->Function->isDeleted();
3448 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003449 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003450 }
3451 break;
3452 }
3453
3454 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003455 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003456 break;
3457 }
3458 break;
3459
3460 case FK_NonConstLValueReferenceBindingToTemporary:
3461 case FK_NonConstLValueReferenceBindingToUnrelated:
3462 S.Diag(Kind.getLocation(),
3463 Failure == FK_NonConstLValueReferenceBindingToTemporary
3464 ? diag::err_lvalue_reference_bind_to_temporary
3465 : diag::err_lvalue_reference_bind_to_unrelated)
3466 << DestType.getNonReferenceType()
3467 << Args[0]->getType()
3468 << Args[0]->getSourceRange();
3469 break;
3470
3471 case FK_RValueReferenceBindingToLValue:
3472 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3473 << Args[0]->getSourceRange();
3474 break;
3475
3476 case FK_ReferenceInitDropsQualifiers:
3477 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3478 << DestType.getNonReferenceType()
3479 << Args[0]->getType()
3480 << Args[0]->getSourceRange();
3481 break;
3482
3483 case FK_ReferenceInitFailed:
3484 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3485 << DestType.getNonReferenceType()
3486 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3487 << Args[0]->getType()
3488 << Args[0]->getSourceRange();
3489 break;
3490
3491 case FK_ConversionFailed:
Douglas Gregore1314a62009-12-18 05:02:21 +00003492 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
3493 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003494 << DestType
3495 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3496 << Args[0]->getType()
3497 << Args[0]->getSourceRange();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003498 break;
3499
3500 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003501 SourceRange R;
3502
3503 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3504 R = SourceRange(InitList->getInit(1)->getLocStart(),
3505 InitList->getLocEnd());
3506 else
3507 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00003508
3509 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor85dabae2009-12-16 01:38:02 +00003510 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00003511 break;
3512 }
3513
3514 case FK_ReferenceBindingToInitList:
3515 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3516 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3517 break;
3518
3519 case FK_InitListBadDestinationType:
3520 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3521 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3522 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003523
3524 case FK_ConstructorOverloadFailed: {
3525 SourceRange ArgsRange;
3526 if (NumArgs)
3527 ArgsRange = SourceRange(Args[0]->getLocStart(),
3528 Args[NumArgs - 1]->getLocEnd());
3529
3530 // FIXME: Using "DestType" for the entity we're printing is probably
3531 // bad.
3532 switch (FailedOverloadResult) {
3533 case OR_Ambiguous:
3534 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3535 << DestType << ArgsRange;
3536 S.PrintOverloadCandidates(FailedCandidateSet, true);
3537 break;
3538
3539 case OR_No_Viable_Function:
3540 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3541 << DestType << ArgsRange;
3542 S.PrintOverloadCandidates(FailedCandidateSet, false);
3543 break;
3544
3545 case OR_Deleted: {
3546 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3547 << true << DestType << ArgsRange;
3548 OverloadCandidateSet::iterator Best;
3549 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3550 Kind.getLocation(),
3551 Best);
3552 if (Ovl == OR_Deleted) {
3553 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3554 << Best->Function->isDeleted();
3555 } else {
3556 llvm_unreachable("Inconsistent overload resolution?");
3557 }
3558 break;
3559 }
3560
3561 case OR_Success:
3562 llvm_unreachable("Conversion did not fail!");
3563 break;
3564 }
3565 break;
3566 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003567
3568 case FK_DefaultInitOfConst:
3569 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3570 << DestType;
3571 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003572 }
3573
3574 return true;
3575}
Douglas Gregore1314a62009-12-18 05:02:21 +00003576
3577//===----------------------------------------------------------------------===//
3578// Initialization helper functions
3579//===----------------------------------------------------------------------===//
3580Sema::OwningExprResult
3581Sema::PerformCopyInitialization(const InitializedEntity &Entity,
3582 SourceLocation EqualLoc,
3583 OwningExprResult Init) {
3584 if (Init.isInvalid())
3585 return ExprError();
3586
3587 Expr *InitE = (Expr *)Init.get();
3588 assert(InitE && "No initialization expression?");
3589
3590 if (EqualLoc.isInvalid())
3591 EqualLoc = InitE->getLocStart();
3592
3593 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
3594 EqualLoc);
3595 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
3596 Init.release();
3597 return Seq.Perform(*this, Entity, Kind,
3598 MultiExprArg(*this, (void**)&InitE, 1));
3599}