blob: cb2fdd2736cbacc3767b780d0978ed0e3e93e414 [file] [log] [blame]
Steve Naroff0cca7492008-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 Lattnerdd8e0062009-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//
14// This file also includes some miscellaneous other initialization checking
15// code that is part of Sema.
Steve Naroff0cca7492008-05-01 22:18:59 +000016//
17//===----------------------------------------------------------------------===//
18
19#include "Sema.h"
Douglas Gregor05c13a32009-01-22 00:58:24 +000020#include "clang/Parse/Designator.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000021#include "clang/AST/ASTContext.h"
22#include "clang/AST/Expr.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000023#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000024using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000025
Chris Lattnerdd8e0062009-02-24 22:27:37 +000026//===----------------------------------------------------------------------===//
27// Sema Initialization Checking
28//===----------------------------------------------------------------------===//
29
Chris Lattner6c291a82009-02-24 22:36:59 +000030static StringLiteral *IsStringInit(Expr *Init, QualType DeclType,
31 ASTContext &Context) {
Chris Lattnerdd8e0062009-02-24 22:27:37 +000032 if (const ArrayType *AT = Context.getAsArrayType(DeclType))
33 if (AT->getElementType()->isCharType())
34 return dyn_cast<StringLiteral>(Init->IgnoreParens());
35 return 0;
36}
37
Chris Lattner95e8d652009-02-24 22:46:58 +000038static bool CheckSingleInitializer(Expr *&Init, QualType DeclType,
39 bool DirectInit, Sema &S) {
Chris Lattnerdd8e0062009-02-24 22:27:37 +000040 // Get the type before calling CheckSingleAssignmentConstraints(), since
41 // it can promote the expression.
42 QualType InitType = Init->getType();
43
Chris Lattner95e8d652009-02-24 22:46:58 +000044 if (S.getLangOptions().CPlusPlus) {
Chris Lattnerdd8e0062009-02-24 22:27:37 +000045 // FIXME: I dislike this error message. A lot.
Chris Lattner95e8d652009-02-24 22:46:58 +000046 if (S.PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
47 return S.Diag(Init->getSourceRange().getBegin(),
48 diag::err_typecheck_convert_incompatible)
49 << DeclType << Init->getType() << "initializing"
50 << Init->getSourceRange();
Chris Lattnerdd8e0062009-02-24 22:27:37 +000051 return false;
52 }
53
Chris Lattner95e8d652009-02-24 22:46:58 +000054 Sema::AssignConvertType ConvTy =
55 S.CheckSingleAssignmentConstraints(DeclType, Init);
56 return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
Chris Lattnerdd8e0062009-02-24 22:27:37 +000057 InitType, Init, "initializing");
58}
59
Chris Lattnerf71ae8d2009-02-24 22:41:04 +000060static bool CheckStringLiteralInit(StringLiteral *Str, QualType &DeclT,
61 Sema &S) {
62 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +000063
64 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
65 // C99 6.7.8p14. We have an array of character type with unknown size
66 // being initialized to a string literal.
67 llvm::APSInt ConstVal(32);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +000068 ConstVal = Str->getByteLength() + 1;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000069 // Return a new array type (C99 6.7.8p22).
Chris Lattnerf71ae8d2009-02-24 22:41:04 +000070 DeclT = S.Context.getConstantArrayType(IAT->getElementType(), ConstVal,
71 ArrayType::Normal, 0);
Chris Lattnerdd8e0062009-02-24 22:27:37 +000072 } else {
73 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
74 // C99 6.7.8p14. We have an array of character type with known size.
75 // FIXME: Avoid truncation for 64-bit length strings.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +000076 if (Str->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
77 S.Diag(Str->getSourceRange().getBegin(),
78 diag::warn_initializer_string_for_char_array_too_long)
79 << Str->getSourceRange();
Chris Lattnerdd8e0062009-02-24 22:27:37 +000080 }
81 // Set type from "char *" to "constant array of char".
Chris Lattnerf71ae8d2009-02-24 22:41:04 +000082 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +000083 // For now, we always return false (meaning success).
84 return false;
85}
86
87bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
88 SourceLocation InitLoc,
89 DeclarationName InitEntity,
90 bool DirectInit) {
91 if (DeclType->isDependentType() || Init->isTypeDependent())
92 return false;
93
94 // C++ [dcl.init.ref]p1:
95 // A variable declared to be a T&, that is "reference to type T"
96 // (8.3.2), shall be initialized by an object, or function, of
97 // type T or by an object that can be converted into a T.
98 if (DeclType->isReferenceType())
99 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
100
101 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
102 // of unknown size ("[]") or an object type that is not a variable array type.
103 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
104 return Diag(InitLoc, diag::err_variable_object_no_init)
105 << VAT->getSizeExpr()->getSourceRange();
106
107 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
108 if (!InitList) {
109 // FIXME: Handle wide strings
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000110 if (StringLiteral *Str = IsStringInit(Init, DeclType, Context))
111 return CheckStringLiteralInit(Str, DeclType, *this);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000112
113 // C++ [dcl.init]p14:
114 // -- If the destination type is a (possibly cv-qualified) class
115 // type:
116 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
117 QualType DeclTypeC = Context.getCanonicalType(DeclType);
118 QualType InitTypeC = Context.getCanonicalType(Init->getType());
119
120 // -- If the initialization is direct-initialization, or if it is
121 // copy-initialization where the cv-unqualified version of the
122 // source type is the same class as, or a derived class of, the
123 // class of the destination, constructors are considered.
124 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
125 IsDerivedFrom(InitTypeC, DeclTypeC)) {
126 CXXConstructorDecl *Constructor
127 = PerformInitializationByConstructor(DeclType, &Init, 1,
128 InitLoc, Init->getSourceRange(),
129 InitEntity,
130 DirectInit? IK_Direct : IK_Copy);
131 return Constructor == 0;
132 }
133
134 // -- Otherwise (i.e., for the remaining copy-initialization
135 // cases), user-defined conversion sequences that can
136 // convert from the source type to the destination type or
137 // (when a conversion function is used) to a derived class
138 // thereof are enumerated as described in 13.3.1.4, and the
139 // best one is chosen through overload resolution
140 // (13.3). If the conversion cannot be done or is
141 // ambiguous, the initialization is ill-formed. The
142 // function selected is called with the initializer
143 // expression as its argument; if the function is a
144 // constructor, the call initializes a temporary of the
145 // destination type.
146 // FIXME: We're pretending to do copy elision here; return to
147 // this when we have ASTs for such things.
148 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
149 return false;
150
151 if (InitEntity)
152 return Diag(InitLoc, diag::err_cannot_initialize_decl)
153 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
154 << Init->getType() << Init->getSourceRange();
155 else
156 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
157 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
158 << Init->getType() << Init->getSourceRange();
159 }
160
161 // C99 6.7.8p16.
162 if (DeclType->isArrayType())
163 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
164 << Init->getSourceRange();
165
Chris Lattner95e8d652009-02-24 22:46:58 +0000166 return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000167 }
168
169 bool hadError = CheckInitList(InitList, DeclType);
170 Init = InitList;
171 return hadError;
172}
173
174//===----------------------------------------------------------------------===//
175// Semantic checking for initializer lists.
176//===----------------------------------------------------------------------===//
177
Douglas Gregor9e80f722009-01-29 01:05:33 +0000178/// @brief Semantic checking for initializer lists.
179///
180/// The InitListChecker class contains a set of routines that each
181/// handle the initialization of a certain kind of entity, e.g.,
182/// arrays, vectors, struct/union types, scalars, etc. The
183/// InitListChecker itself performs a recursive walk of the subobject
184/// structure of the type to be initialized, while stepping through
185/// the initializer list one element at a time. The IList and Index
186/// parameters to each of the Check* routines contain the active
187/// (syntactic) initializer list and the index into that initializer
188/// list that represents the current initializer. Each routine is
189/// responsible for moving that Index forward as it consumes elements.
190///
191/// Each Check* routine also has a StructuredList/StructuredIndex
192/// arguments, which contains the current the "structured" (semantic)
193/// initializer list and the index into that initializer list where we
194/// are copying initializers as we map them over to the semantic
195/// list. Once we have completed our recursive walk of the subobject
196/// structure, we will have constructed a full semantic initializer
197/// list.
198///
199/// C99 designators cause changes in the initializer list traversal,
200/// because they make the initialization "jump" into a specific
201/// subobject and then continue the initialization from that
202/// point. CheckDesignatedInitializer() recursively steps into the
203/// designated subobject and manages backing out the recursion to
204/// initialize the subobjects after the one designated.
Chris Lattner68355a52009-01-29 05:10:57 +0000205namespace clang {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000206class InitListChecker {
207 Sema *SemaRef;
208 bool hadError;
209 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
210 InitListExpr *FullyStructuredList;
211
212 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000213 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000214 unsigned &StructuredIndex,
215 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000216 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000217 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000218 unsigned &StructuredIndex,
219 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000220 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
221 bool SubobjectIsDesignatorContext,
222 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000223 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000224 unsigned &StructuredIndex,
225 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000226 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
227 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000228 InitListExpr *StructuredList,
229 unsigned &StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000230 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000231 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000232 InitListExpr *StructuredList,
233 unsigned &StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000234 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
235 unsigned &Index,
236 InitListExpr *StructuredList,
237 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000238 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000239 InitListExpr *StructuredList,
240 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000241 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
242 RecordDecl::field_iterator Field,
243 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000244 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000245 unsigned &StructuredIndex,
246 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000247 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
248 llvm::APSInt elementIndex,
249 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000250 InitListExpr *StructuredList,
251 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000252 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
253 DesignatedInitExpr::designators_iterator D,
254 QualType &CurrentObjectType,
255 RecordDecl::field_iterator *NextField,
256 llvm::APSInt *NextElementIndex,
257 unsigned &Index,
258 InitListExpr *StructuredList,
259 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000260 bool FinishSubobjectInit,
261 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000262 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
263 QualType CurrentObjectType,
264 InitListExpr *StructuredList,
265 unsigned StructuredIndex,
266 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000267 void UpdateStructuredListElement(InitListExpr *StructuredList,
268 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000269 Expr *expr);
270 int numArrayElements(QualType DeclType);
271 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000272
273 void FillInValueInitializations(InitListExpr *ILE);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000274public:
275 InitListChecker(Sema *S, InitListExpr *IL, QualType &T);
276 bool HadError() { return hadError; }
277
278 // @brief Retrieves the fully-structured initializer list used for
279 // semantic analysis and code generation.
280 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
281};
Chris Lattner68355a52009-01-29 05:10:57 +0000282}
283
Douglas Gregor4c678342009-01-28 21:54:33 +0000284/// Recursively replaces NULL values within the given initializer list
285/// with expressions that perform value-initialization of the
286/// appropriate type.
Douglas Gregor930d8b52009-01-30 22:09:00 +0000287void InitListChecker::FillInValueInitializations(InitListExpr *ILE) {
288 assert((ILE->getType() != SemaRef->Context.VoidTy) &&
289 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000290 SourceLocation Loc = ILE->getSourceRange().getBegin();
291 if (ILE->getSyntacticForm())
292 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
293
Douglas Gregor4c678342009-01-28 21:54:33 +0000294 if (const RecordType *RType = ILE->getType()->getAsRecordType()) {
295 unsigned Init = 0, NumInits = ILE->getNumInits();
296 for (RecordDecl::field_iterator Field = RType->getDecl()->field_begin(),
297 FieldEnd = RType->getDecl()->field_end();
298 Field != FieldEnd; ++Field) {
299 if (Field->isUnnamedBitfield())
300 continue;
301
Douglas Gregor87fd7032009-02-02 17:43:21 +0000302 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000303 if (Field->getType()->isReferenceType()) {
304 // C++ [dcl.init.aggr]p9:
305 // If an incomplete or empty initializer-list leaves a
306 // member of reference type uninitialized, the program is
307 // ill-formed.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000308 SemaRef->Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000309 << Field->getType()
310 << ILE->getSyntacticForm()->getSourceRange();
311 SemaRef->Diag(Field->getLocation(),
312 diag::note_uninit_reference_member);
313 hadError = true;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000314 return;
315 } else if (SemaRef->CheckValueInitialization(Field->getType(), Loc)) {
316 hadError = true;
317 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000318 }
Douglas Gregor87fd7032009-02-02 17:43:21 +0000319
320 // FIXME: If value-initialization involves calling a
321 // constructor, should we make that call explicit in the
322 // representation (even when it means extending the
323 // initializer list)?
324 if (Init < NumInits && !hadError)
325 ILE->setInit(Init,
326 new (SemaRef->Context) ImplicitValueInitExpr(Field->getType()));
327 } else if (InitListExpr *InnerILE
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000328 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000329 FillInValueInitializations(InnerILE);
Douglas Gregor4c678342009-01-28 21:54:33 +0000330 ++Init;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000331
332 // Only look at the first initialization of a union.
333 if (RType->getDecl()->isUnion())
334 break;
Douglas Gregor4c678342009-01-28 21:54:33 +0000335 }
336
337 return;
338 }
339
340 QualType ElementType;
341
Douglas Gregor87fd7032009-02-02 17:43:21 +0000342 unsigned NumInits = ILE->getNumInits();
343 unsigned NumElements = NumInits;
344 if (const ArrayType *AType = SemaRef->Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000345 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000346 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
347 NumElements = CAType->getSize().getZExtValue();
348 } else if (const VectorType *VType = ILE->getType()->getAsVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000349 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000350 NumElements = VType->getNumElements();
351 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000352 ElementType = ILE->getType();
353
Douglas Gregor87fd7032009-02-02 17:43:21 +0000354 for (unsigned Init = 0; Init != NumElements; ++Init) {
355 if (Init >= NumInits || !ILE->getInit(Init)) {
356 if (SemaRef->CheckValueInitialization(ElementType, Loc)) {
357 hadError = true;
358 return;
359 }
360
361 // FIXME: If value-initialization involves calling a
362 // constructor, should we make that call explicit in the
363 // representation (even when it means extending the
364 // initializer list)?
365 if (Init < NumInits && !hadError)
366 ILE->setInit(Init,
367 new (SemaRef->Context) ImplicitValueInitExpr(ElementType));
368 }
Chris Lattner68355a52009-01-29 05:10:57 +0000369 else if (InitListExpr *InnerILE =dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000370 FillInValueInitializations(InnerILE);
Douglas Gregor4c678342009-01-28 21:54:33 +0000371 }
372}
373
Chris Lattner68355a52009-01-29 05:10:57 +0000374
Steve Naroff0cca7492008-05-01 22:18:59 +0000375InitListChecker::InitListChecker(Sema *S, InitListExpr *IL, QualType &T) {
376 hadError = false;
377 SemaRef = S;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000378
Eli Friedmanb85f7072008-05-19 19:16:24 +0000379 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000380 unsigned newStructuredIndex = 0;
381 FullyStructuredList
382 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, SourceRange());
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000383 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
384 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000385
Douglas Gregor930d8b52009-01-30 22:09:00 +0000386 if (!hadError)
387 FillInValueInitializations(FullyStructuredList);
Steve Naroff0cca7492008-05-01 22:18:59 +0000388}
389
390int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000391 // FIXME: use a proper constant
392 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000393 if (const ConstantArrayType *CAT =
394 SemaRef->Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000395 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
396 }
397 return maxElements;
398}
399
400int InitListChecker::numStructUnionElements(QualType DeclType) {
401 RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000402 int InitializableMembers = 0;
403 for (RecordDecl::field_iterator Field = structDecl->field_begin(),
404 FieldEnd = structDecl->field_end();
405 Field != FieldEnd; ++Field) {
406 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
407 ++InitializableMembers;
408 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000409 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000410 return std::min(InitializableMembers, 1);
411 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000412}
413
414void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000415 QualType T, unsigned &Index,
416 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000417 unsigned &StructuredIndex,
418 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000419 int maxElements = 0;
420
421 if (T->isArrayType())
422 maxElements = numArrayElements(T);
423 else if (T->isStructureType() || T->isUnionType())
424 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000425 else if (T->isVectorType())
426 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000427 else
428 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000429
Eli Friedman402256f2008-05-25 13:49:22 +0000430 if (maxElements == 0) {
431 SemaRef->Diag(ParentIList->getInit(Index)->getLocStart(),
432 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000433 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000434 hadError = true;
435 return;
436 }
437
Douglas Gregor4c678342009-01-28 21:54:33 +0000438 // Build a structured initializer list corresponding to this subobject.
439 InitListExpr *StructuredSubobjectInitList
440 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
441 StructuredIndex,
442 ParentIList->getInit(Index)->getSourceRange());
443 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000444
Douglas Gregor4c678342009-01-28 21:54:33 +0000445 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000446 unsigned StartIndex = Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000447 CheckListElementTypes(ParentIList, T, false, Index,
448 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000449 StructuredSubobjectInitIndex,
450 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000451 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
452
453 // Update the structured sub-object initialize so that it's ending
454 // range corresponds with the end of the last initializer it used.
455 if (EndIndex < ParentIList->getNumInits()) {
456 SourceLocation EndLoc
457 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
458 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
459 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000460}
461
Steve Naroffa647caa2008-05-06 00:23:44 +0000462void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000463 unsigned &Index,
464 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000465 unsigned &StructuredIndex,
466 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000467 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000468 SyntacticToSemantic[IList] = StructuredList;
469 StructuredList->setSyntacticForm(IList);
470 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000471 StructuredIndex, TopLevelObject);
Steve Naroffa647caa2008-05-06 00:23:44 +0000472 IList->setType(T);
Douglas Gregor4c678342009-01-28 21:54:33 +0000473 StructuredList->setType(T);
Eli Friedman638e1442008-05-25 13:22:35 +0000474 if (hadError)
475 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000476
Eli Friedman638e1442008-05-25 13:22:35 +0000477 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000478 // We have leftover initializers
479 if (IList->getNumInits() > 0 &&
Chris Lattner6c291a82009-02-24 22:36:59 +0000480 IsStringInit(IList->getInit(Index), T, SemaRef->Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000481 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
482 if (SemaRef->getLangOptions().CPlusPlus)
483 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000484 // Special-case
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000485 SemaRef->Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000486 << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000487 hadError = true;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000488 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000489 // Don't complain for incomplete types, since we'll get an error
490 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000491 QualType CurrentObjectType = StructuredList->getType();
492 int initKind =
493 CurrentObjectType->isArrayType()? 0 :
494 CurrentObjectType->isVectorType()? 1 :
495 CurrentObjectType->isScalarType()? 2 :
496 CurrentObjectType->isUnionType()? 3 :
497 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000498
499 unsigned DK = diag::warn_excess_initializers;
500 if (SemaRef->getLangOptions().CPlusPlus)
501 DK = diag::err_excess_initializers;
502
503 SemaRef->Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000504 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000505 }
506 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000507
Eli Friedman638e1442008-05-25 13:22:35 +0000508 if (T->isScalarType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000509 SemaRef->Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
510 << IList->getSourceRange();
Steve Naroff0cca7492008-05-01 22:18:59 +0000511}
512
Eli Friedmanb85f7072008-05-19 19:16:24 +0000513void InitListChecker::CheckListElementTypes(InitListExpr *IList,
514 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000515 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000516 unsigned &Index,
517 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000518 unsigned &StructuredIndex,
519 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000520 if (DeclType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000521 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000522 } else if (DeclType->isVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000523 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000524 } else if (DeclType->isAggregateType()) {
525 if (DeclType->isRecordType()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000526 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
527 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000528 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000529 StructuredList, StructuredIndex,
530 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000531 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000532 llvm::APSInt Zero(
533 SemaRef->Context.getTypeSize(SemaRef->Context.getSizeType()),
534 false);
Douglas Gregor4c678342009-01-28 21:54:33 +0000535 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
536 StructuredList, StructuredIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000537 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000538 else
Douglas Gregor4c678342009-01-28 21:54:33 +0000539 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000540 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
541 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000542 ++Index;
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000543 SemaRef->Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000544 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000545 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000546 } else if (DeclType->isRecordType()) {
547 // C++ [dcl.init]p14:
548 // [...] If the class is an aggregate (8.5.1), and the initializer
549 // is a brace-enclosed list, see 8.5.1.
550 //
551 // Note: 8.5.1 is handled below; here, we diagnose the case where
552 // we have an initializer list and a destination type that is not
553 // an aggregate.
554 // FIXME: In C++0x, this is yet another form of initialization.
555 SemaRef->Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
556 << DeclType << IList->getSourceRange();
557 hadError = true;
558 } else if (DeclType->isReferenceType()) {
559 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000560 } else {
561 // In C, all types are either scalars or aggregates, but
562 // additional handling is needed here for C++ (and possibly others?).
563 assert(0 && "Unsupported initializer type");
564 }
565}
566
Eli Friedmanb85f7072008-05-19 19:16:24 +0000567void InitListChecker::CheckSubElementType(InitListExpr *IList,
568 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000569 unsigned &Index,
570 InitListExpr *StructuredList,
571 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000572 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000573 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
574 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000575 unsigned newStructuredIndex = 0;
576 InitListExpr *newStructuredList
577 = getStructuredSubobjectInit(IList, Index, ElemType,
578 StructuredList, StructuredIndex,
579 SubInitList->getSourceRange());
580 CheckExplicitInitList(SubInitList, ElemType, newIndex,
581 newStructuredList, newStructuredIndex);
582 ++StructuredIndex;
583 ++Index;
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000584 } else if (StringLiteral *Str = IsStringInit(expr, ElemType,
Chris Lattner6c291a82009-02-24 22:36:59 +0000585 SemaRef->Context)) {
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000586 CheckStringLiteralInit(Str, ElemType, *SemaRef);
587 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000588 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000589 } else if (ElemType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000590 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000591 } else if (ElemType->isReferenceType()) {
592 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000593 } else {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000594 if (SemaRef->getLangOptions().CPlusPlus) {
595 // C++ [dcl.init.aggr]p12:
596 // All implicit type conversions (clause 4) are considered when
597 // initializing the aggregate member with an ini- tializer from
598 // an initializer-list. If the initializer can initialize a
599 // member, the member is initialized. [...]
600 ImplicitConversionSequence ICS
601 = SemaRef->TryCopyInitialization(expr, ElemType);
602 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
603 if (SemaRef->PerformImplicitConversion(expr, ElemType, ICS,
604 "initializing"))
605 hadError = true;
606 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
607 ++Index;
608 return;
609 }
610
611 // Fall through for subaggregate initialization
612 } else {
613 // C99 6.7.8p13:
614 //
615 // The initializer for a structure or union object that has
616 // automatic storage duration shall be either an initializer
617 // list as described below, or a single expression that has
618 // compatible structure or union type. In the latter case, the
619 // initial value of the object, including unnamed members, is
620 // that of the expression.
621 QualType ExprType = SemaRef->Context.getCanonicalType(expr->getType());
622 QualType ElemTypeCanon = SemaRef->Context.getCanonicalType(ElemType);
623 if (SemaRef->Context.typesAreCompatible(ExprType.getUnqualifiedType(),
624 ElemTypeCanon.getUnqualifiedType())) {
625 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
626 ++Index;
627 return;
628 }
629
630 // Fall through for subaggregate initialization
631 }
632
633 // C++ [dcl.init.aggr]p12:
634 //
635 // [...] Otherwise, if the member is itself a non-empty
636 // subaggregate, brace elision is assumed and the initializer is
637 // considered for the initialization of the first member of
638 // the subaggregate.
639 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
640 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
641 StructuredIndex);
642 ++StructuredIndex;
643 } else {
644 // We cannot initialize this element, so let
645 // PerformCopyInitialization produce the appropriate diagnostic.
646 SemaRef->PerformCopyInitialization(expr, ElemType, "initializing");
647 hadError = true;
648 ++Index;
649 ++StructuredIndex;
650 }
651 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000652}
653
Douglas Gregor930d8b52009-01-30 22:09:00 +0000654void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000655 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000656 InitListExpr *StructuredList,
657 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000658 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000659 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000660 if (isa<InitListExpr>(expr)) {
Eli Friedmanbb504d32008-05-19 20:12:18 +0000661 SemaRef->Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000662 diag::err_many_braces_around_scalar_init)
663 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000664 hadError = true;
665 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000666 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000667 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000668 } else if (isa<DesignatedInitExpr>(expr)) {
669 SemaRef->Diag(expr->getSourceRange().getBegin(),
670 diag::err_designator_for_scalar_init)
671 << DeclType << expr->getSourceRange();
672 hadError = true;
673 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000674 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000675 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000676 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000677
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000678 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner95e8d652009-02-24 22:46:58 +0000679 if (CheckSingleInitializer(expr, DeclType, false, *SemaRef))
Eli Friedmanbb504d32008-05-19 20:12:18 +0000680 hadError = true; // types weren't compatible.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000681 else if (savExpr != expr) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000682 // The type was promoted, update initializer list.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000683 IList->setInit(Index, expr);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000684 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000685 if (hadError)
686 ++StructuredIndex;
687 else
688 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000689 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000690 } else {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000691 SemaRef->Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
692 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000693 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000694 ++Index;
695 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000696 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000697 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000698}
699
Douglas Gregor930d8b52009-01-30 22:09:00 +0000700void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
701 unsigned &Index,
702 InitListExpr *StructuredList,
703 unsigned &StructuredIndex) {
704 if (Index < IList->getNumInits()) {
705 Expr *expr = IList->getInit(Index);
706 if (isa<InitListExpr>(expr)) {
707 SemaRef->Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
708 << DeclType << IList->getSourceRange();
709 hadError = true;
710 ++Index;
711 ++StructuredIndex;
712 return;
713 }
714
715 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
716 if (SemaRef->CheckReferenceInit(expr, DeclType))
717 hadError = true;
718 else if (savExpr != expr) {
719 // The type was promoted, update initializer list.
720 IList->setInit(Index, expr);
721 }
722 if (hadError)
723 ++StructuredIndex;
724 else
725 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
726 ++Index;
727 } else {
728 // FIXME: It would be wonderful if we could point at the actual
729 // member. In general, it would be useful to pass location
730 // information down the stack, so that we know the location (or
731 // decl) of the "current object" being initialized.
732 SemaRef->Diag(IList->getLocStart(),
733 diag::err_init_reference_member_uninitialized)
734 << DeclType
735 << IList->getSourceRange();
736 hadError = true;
737 ++Index;
738 ++StructuredIndex;
739 return;
740 }
741}
742
Steve Naroff0cca7492008-05-01 22:18:59 +0000743void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000744 unsigned &Index,
745 InitListExpr *StructuredList,
746 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000747 if (Index < IList->getNumInits()) {
748 const VectorType *VT = DeclType->getAsVectorType();
749 int maxElements = VT->getNumElements();
750 QualType elementType = VT->getElementType();
751
752 for (int i = 0; i < maxElements; ++i) {
753 // Don't attempt to go past the end of the init list
754 if (Index >= IList->getNumInits())
755 break;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000756 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000757 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000758 }
759 }
760}
761
762void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000763 llvm::APSInt elementIndex,
764 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000765 unsigned &Index,
766 InitListExpr *StructuredList,
767 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000768 // Check for the special-case of initializing an array with a string.
769 if (Index < IList->getNumInits()) {
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000770 if (StringLiteral *Str = IsStringInit(IList->getInit(Index), DeclType,
Chris Lattner6c291a82009-02-24 22:36:59 +0000771 SemaRef->Context)) {
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000772 CheckStringLiteralInit(Str, DeclType, *SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +0000773 // We place the string literal directly into the resulting
774 // initializer list. This is the only place where the structure
775 // of the structured initializer list doesn't match exactly,
776 // because doing so would involve allocating one character
777 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000778 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000779 StructuredList->resizeInits(SemaRef->Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000780 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000781 return;
782 }
783 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000784 if (const VariableArrayType *VAT =
785 SemaRef->Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000786 // Check for VLAs; in standard C it would be possible to check this
787 // earlier, but I don't know where clang accepts VLAs (gcc accepts
788 // them in all sorts of strange places).
789 SemaRef->Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000790 diag::err_variable_object_no_init)
791 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000792 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000793 ++Index;
794 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000795 return;
796 }
797
Douglas Gregor05c13a32009-01-22 00:58:24 +0000798 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000799 llvm::APSInt maxElements(elementIndex.getBitWidth(),
800 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000801 bool maxElementsKnown = false;
802 if (const ConstantArrayType *CAT =
803 SemaRef->Context.getAsConstantArrayType(DeclType)) {
804 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000805 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000806 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000807 maxElementsKnown = true;
808 }
809
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000810 QualType elementType = SemaRef->Context.getAsArrayType(DeclType)
811 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000812 while (Index < IList->getNumInits()) {
813 Expr *Init = IList->getInit(Index);
814 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000815 // If we're not the subobject that matches up with the '{' for
816 // the designator, we shouldn't be handling the
817 // designator. Return immediately.
818 if (!SubobjectIsDesignatorContext)
819 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000820
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000821 // Handle this designated initializer. elementIndex will be
822 // updated to be the next array element we'll initialize.
823 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000824 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000825 StructuredList, StructuredIndex, true,
826 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000827 hadError = true;
828 continue;
829 }
830
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000831 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
832 maxElements.extend(elementIndex.getBitWidth());
833 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
834 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000835 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000836
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000837 // If the array is of incomplete type, keep track of the number of
838 // elements in the initializer.
839 if (!maxElementsKnown && elementIndex > maxElements)
840 maxElements = elementIndex;
841
Douglas Gregor05c13a32009-01-22 00:58:24 +0000842 continue;
843 }
844
845 // If we know the maximum number of elements, and we've already
846 // hit it, stop consuming elements in the initializer list.
847 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +0000848 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000849
850 // Check this element.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000851 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000852 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000853 ++elementIndex;
854
855 // If the array is of incomplete type, keep track of the number of
856 // elements in the initializer.
857 if (!maxElementsKnown && elementIndex > maxElements)
858 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +0000859 }
860 if (DeclType->isIncompleteArrayType()) {
861 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000862 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000863 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000864 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000865 // Sizing an array implicitly to zero is not allowed by ISO C,
866 // but is supported by GNU.
Steve Naroff0cca7492008-05-01 22:18:59 +0000867 SemaRef->Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000868 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +0000869 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000870
Douglas Gregor05c13a32009-01-22 00:58:24 +0000871 DeclType = SemaRef->Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000872 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +0000873 }
874}
875
876void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
877 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000878 RecordDecl::field_iterator Field,
879 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000880 unsigned &Index,
881 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000882 unsigned &StructuredIndex,
883 bool TopLevelObject) {
Eli Friedmanb85f7072008-05-19 19:16:24 +0000884 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroff0cca7492008-05-01 22:18:59 +0000885
Eli Friedmanb85f7072008-05-19 19:16:24 +0000886 // If the record is invalid, some of it's members are invalid. To avoid
887 // confusion, we forgo checking the intializer for the entire record.
888 if (structDecl->isInvalidDecl()) {
889 hadError = true;
890 return;
891 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000892
893 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
894 // Value-initialize the first named member of the union.
895 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
896 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
897 Field != FieldEnd; ++Field) {
898 if (Field->getDeclName()) {
899 StructuredList->setInitializedFieldInUnion(*Field);
900 break;
901 }
902 }
903 return;
904 }
905
Douglas Gregor05c13a32009-01-22 00:58:24 +0000906 // If structDecl is a forward declaration, this loop won't do
907 // anything except look at designated initializers; That's okay,
908 // because an error should get printed out elsewhere. It might be
909 // worthwhile to skip over the rest of the initializer, though.
Douglas Gregor44b43212008-12-11 16:49:14 +0000910 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000911 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +0000912 bool InitializedSomething = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000913 while (Index < IList->getNumInits()) {
914 Expr *Init = IList->getInit(Index);
915
916 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-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 Gregor05c13a32009-01-22 00:58:24 +0000922
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000923 // Handle this designated initializer. Field will be updated to
924 // the next field that we'll be initializing.
925 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000926 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000927 StructuredList, StructuredIndex,
928 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000929 hadError = true;
930
Douglas Gregordfb5e592009-02-12 19:00:39 +0000931 InitializedSomething = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000932 continue;
933 }
934
935 if (Field == FieldEnd) {
936 // We've run out of fields. We're done.
937 break;
938 }
939
Douglas Gregordfb5e592009-02-12 19:00:39 +0000940 // We've already initialized a member of a union. We're done.
941 if (InitializedSomething && DeclType->isUnionType())
942 break;
943
Douglas Gregor44b43212008-12-11 16:49:14 +0000944 // If we've hit the flexible array member at the end, we're done.
945 if (Field->getType()->isIncompleteArrayType())
946 break;
947
Douglas Gregor0bb76892009-01-29 16:53:55 +0000948 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000949 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +0000950 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000951 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +0000952 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000953
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000954 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000955 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +0000956 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +0000957
958 if (DeclType->isUnionType()) {
959 // Initialize the first field within the union.
960 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +0000961 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000962
963 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +0000964 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000965
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000966 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
967 Index >= IList->getNumInits() ||
968 !isa<InitListExpr>(IList->getInit(Index)))
969 return;
970
971 // Handle GNU flexible array initializers.
972 if (!TopLevelObject &&
973 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0) {
974 SemaRef->Diag(IList->getInit(Index)->getSourceRange().getBegin(),
975 diag::err_flexible_array_init_nonempty)
976 << IList->getInit(Index)->getSourceRange().getBegin();
977 SemaRef->Diag(Field->getLocation(), diag::note_flexible_array_member)
978 << *Field;
979 hadError = true;
980 }
981
982 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
983 StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000984}
Steve Naroff0cca7492008-05-01 22:18:59 +0000985
Douglas Gregor05c13a32009-01-22 00:58:24 +0000986/// @brief Check the well-formedness of a C99 designated initializer.
987///
988/// Determines whether the designated initializer @p DIE, which
989/// resides at the given @p Index within the initializer list @p
990/// IList, is well-formed for a current object of type @p DeclType
991/// (C99 6.7.8). The actual subobject that this designator refers to
992/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +0000993/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +0000994///
995/// @param IList The initializer list in which this designated
996/// initializer occurs.
997///
998/// @param DIE The designated initializer and its initialization
999/// expression.
1000///
1001/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1002/// into which the designation in @p DIE should refer.
1003///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001004/// @param NextField If non-NULL and the first designator in @p DIE is
1005/// a field, this will be set to the field declaration corresponding
1006/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001007///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001008/// @param NextElementIndex If non-NULL and the first designator in @p
1009/// DIE is an array designator or GNU array-range designator, this
1010/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001011///
1012/// @param Index Index into @p IList where the designated initializer
1013/// @p DIE occurs.
1014///
Douglas Gregor4c678342009-01-28 21:54:33 +00001015/// @param StructuredList The initializer list expression that
1016/// describes all of the subobject initializers in the order they'll
1017/// actually be initialized.
1018///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001019/// @returns true if there was an error, false otherwise.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001020bool
1021InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
1022 DesignatedInitExpr *DIE,
1023 DesignatedInitExpr::designators_iterator D,
1024 QualType &CurrentObjectType,
1025 RecordDecl::field_iterator *NextField,
1026 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001027 unsigned &Index,
1028 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001029 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001030 bool FinishSubobjectInit,
1031 bool TopLevelObject) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001032 if (D == DIE->designators_end()) {
1033 // Check the actual initialization for the designated object type.
1034 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001035
1036 // Temporarily remove the designator expression from the
1037 // initializer list that the child calls see, so that we don't try
1038 // to re-process the designator.
1039 unsigned OldIndex = Index;
1040 IList->setInit(OldIndex, DIE->getInit());
1041
1042 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001043 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001044
1045 // Restore the designated initializer expression in the syntactic
1046 // form of the initializer list.
1047 if (IList->getInit(OldIndex) != DIE->getInit())
1048 DIE->setInit(IList->getInit(OldIndex));
1049 IList->setInit(OldIndex, DIE);
1050
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001051 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001052 }
1053
Douglas Gregor4c678342009-01-28 21:54:33 +00001054 bool IsFirstDesignator = (D == DIE->designators_begin());
1055 assert((IsFirstDesignator || StructuredList) &&
1056 "Need a non-designated initializer list to start from");
1057
1058 // Determine the structural initializer list that corresponds to the
1059 // current subobject.
1060 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1061 : getStructuredSubobjectInit(IList, Index, CurrentObjectType, StructuredList,
1062 StructuredIndex,
1063 SourceRange(D->getStartLocation(),
1064 DIE->getSourceRange().getEnd()));
1065 assert(StructuredList && "Expected a structured initializer list");
1066
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001067 if (D->isFieldDesignator()) {
1068 // C99 6.7.8p7:
1069 //
1070 // If a designator has the form
1071 //
1072 // . identifier
1073 //
1074 // then the current object (defined below) shall have
1075 // structure or union type and the identifier shall be the
1076 // name of a member of that type.
1077 const RecordType *RT = CurrentObjectType->getAsRecordType();
1078 if (!RT) {
1079 SourceLocation Loc = D->getDotLoc();
1080 if (Loc.isInvalid())
1081 Loc = D->getFieldLoc();
1082 SemaRef->Diag(Loc, diag::err_field_designator_non_aggr)
1083 << SemaRef->getLangOptions().CPlusPlus << CurrentObjectType;
1084 ++Index;
1085 return true;
1086 }
1087
Douglas Gregor4c678342009-01-28 21:54:33 +00001088 // Note: we perform a linear search of the fields here, despite
1089 // the fact that we have a faster lookup method, because we always
1090 // need to compute the field's index.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001091 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001092 unsigned FieldIndex = 0;
1093 RecordDecl::field_iterator Field = RT->getDecl()->field_begin(),
1094 FieldEnd = RT->getDecl()->field_end();
1095 for (; Field != FieldEnd; ++Field) {
1096 if (Field->isUnnamedBitfield())
1097 continue;
1098
1099 if (Field->getIdentifier() == FieldName)
1100 break;
1101
1102 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001103 }
1104
Douglas Gregor4c678342009-01-28 21:54:33 +00001105 if (Field == FieldEnd) {
1106 // We did not find the field we're looking for. Produce a
1107 // suitable diagnostic and return a failure.
1108 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
1109 if (Lookup.first == Lookup.second) {
1110 // Name lookup didn't find anything.
1111 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1112 << FieldName << CurrentObjectType;
1113 } else {
1114 // Name lookup found something, but it wasn't a field.
1115 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
1116 << FieldName;
1117 SemaRef->Diag((*Lookup.first)->getLocation(),
1118 diag::note_field_designator_found);
1119 }
1120
1121 ++Index;
1122 return true;
1123 } else if (cast<RecordDecl>((*Field)->getDeclContext())
1124 ->isAnonymousStructOrUnion()) {
1125 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_anon_class)
1126 << FieldName
1127 << (cast<RecordDecl>((*Field)->getDeclContext())->isUnion()? 2 :
1128 (int)SemaRef->getLangOptions().CPlusPlus);
1129 SemaRef->Diag((*Field)->getLocation(), diag::note_field_designator_found);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001130 ++Index;
1131 return true;
1132 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001133
1134 // All of the fields of a union are located at the same place in
1135 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001136 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001137 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001138 StructuredList->setInitializedFieldInUnion(*Field);
1139 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001140
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001141 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001142 D->setField(*Field);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001143
Douglas Gregor4c678342009-01-28 21:54:33 +00001144 // Make sure that our non-designated initializer list has space
1145 // for a subobject corresponding to this field.
1146 if (FieldIndex >= StructuredList->getNumInits())
1147 StructuredList->resizeInits(SemaRef->Context, FieldIndex + 1);
1148
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001149 // This designator names a flexible array member.
1150 if (Field->getType()->isIncompleteArrayType()) {
1151 bool Invalid = false;
1152 DesignatedInitExpr::designators_iterator NextD = D;
1153 ++NextD;
1154 if (NextD != DIE->designators_end()) {
1155 // We can't designate an object within the flexible array
1156 // member (because GCC doesn't allow it).
1157 SemaRef->Diag(NextD->getStartLocation(),
1158 diag::err_designator_into_flexible_array_member)
1159 << SourceRange(NextD->getStartLocation(),
1160 DIE->getSourceRange().getEnd());
1161 SemaRef->Diag(Field->getLocation(), diag::note_flexible_array_member)
1162 << *Field;
1163 Invalid = true;
1164 }
1165
1166 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1167 // The initializer is not an initializer list.
1168 SemaRef->Diag(DIE->getInit()->getSourceRange().getBegin(),
1169 diag::err_flexible_array_init_needs_braces)
1170 << DIE->getInit()->getSourceRange();
1171 SemaRef->Diag(Field->getLocation(), diag::note_flexible_array_member)
1172 << *Field;
1173 Invalid = true;
1174 }
1175
1176 // Handle GNU flexible array initializers.
1177 if (!Invalid && !TopLevelObject &&
1178 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
1179 SemaRef->Diag(DIE->getSourceRange().getBegin(),
1180 diag::err_flexible_array_init_nonempty)
1181 << DIE->getSourceRange().getBegin();
1182 SemaRef->Diag(Field->getLocation(), diag::note_flexible_array_member)
1183 << *Field;
1184 Invalid = true;
1185 }
1186
1187 if (Invalid) {
1188 ++Index;
1189 return true;
1190 }
1191
1192 // Initialize the array.
1193 bool prevHadError = hadError;
1194 unsigned newStructuredIndex = FieldIndex;
1195 unsigned OldIndex = Index;
1196 IList->setInit(Index, DIE->getInit());
1197 CheckSubElementType(IList, Field->getType(), Index,
1198 StructuredList, newStructuredIndex);
1199 IList->setInit(OldIndex, DIE);
1200 if (hadError && !prevHadError) {
1201 ++Field;
1202 ++FieldIndex;
1203 if (NextField)
1204 *NextField = Field;
1205 StructuredIndex = FieldIndex;
1206 return true;
1207 }
1208 } else {
1209 // Recurse to check later designated subobjects.
1210 QualType FieldType = (*Field)->getType();
1211 unsigned newStructuredIndex = FieldIndex;
1212 if (CheckDesignatedInitializer(IList, DIE, ++D, FieldType, 0, 0, Index,
1213 StructuredList, newStructuredIndex,
1214 true, false))
1215 return true;
1216 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001217
1218 // Find the position of the next field to be initialized in this
1219 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001220 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001221 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001222
1223 // If this the first designator, our caller will continue checking
1224 // the rest of this struct/class/union subobject.
1225 if (IsFirstDesignator) {
1226 if (NextField)
1227 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001228 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001229 return false;
1230 }
1231
Douglas Gregor34e79462009-01-28 23:36:17 +00001232 if (!FinishSubobjectInit)
1233 return false;
1234
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001235 // Check the remaining fields within this class/struct/union subobject.
1236 bool prevHadError = hadError;
Douglas Gregor4c678342009-01-28 21:54:33 +00001237 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1238 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001239 return hadError && !prevHadError;
1240 }
1241
1242 // C99 6.7.8p6:
1243 //
1244 // If a designator has the form
1245 //
1246 // [ constant-expression ]
1247 //
1248 // then the current object (defined below) shall have array
1249 // type and the expression shall be an integer constant
1250 // expression. If the array is of unknown size, any
1251 // nonnegative value is valid.
1252 //
1253 // Additionally, cope with the GNU extension that permits
1254 // designators of the form
1255 //
1256 // [ constant-expression ... constant-expression ]
1257 const ArrayType *AT = SemaRef->Context.getAsArrayType(CurrentObjectType);
1258 if (!AT) {
1259 SemaRef->Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1260 << CurrentObjectType;
1261 ++Index;
1262 return true;
1263 }
1264
1265 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001266 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1267 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001268 IndexExpr = DIE->getArrayIndex(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001269
1270 bool ConstExpr
1271 = IndexExpr->isIntegerConstantExpr(DesignatedStartIndex, SemaRef->Context);
1272 assert(ConstExpr && "Expression must be constant"); (void)ConstExpr;
1273
1274 DesignatedEndIndex = DesignatedStartIndex;
1275 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001276 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001277
1278 bool StartConstExpr
1279 = DIE->getArrayRangeStart(*D)->isIntegerConstantExpr(DesignatedStartIndex,
1280 SemaRef->Context);
1281 assert(StartConstExpr && "Expression must be constant"); (void)StartConstExpr;
1282
1283 bool EndConstExpr
1284 = DIE->getArrayRangeEnd(*D)->isIntegerConstantExpr(DesignatedEndIndex,
1285 SemaRef->Context);
1286 assert(EndConstExpr && "Expression must be constant"); (void)EndConstExpr;
1287
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001288 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001289
1290 if (DesignatedStartIndex.getZExtValue() != DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001291 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001292 }
1293
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001294 if (isa<ConstantArrayType>(AT)) {
1295 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001296 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1297 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1298 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1299 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1300 if (DesignatedEndIndex >= MaxElements) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001301 SemaRef->Diag(IndexExpr->getSourceRange().getBegin(),
1302 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001303 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001304 << IndexExpr->getSourceRange();
1305 ++Index;
1306 return true;
1307 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001308 } else {
1309 // Make sure the bit-widths and signedness match.
1310 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1311 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
1312 else if (DesignatedStartIndex.getBitWidth() < DesignatedEndIndex.getBitWidth())
1313 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1314 DesignatedStartIndex.setIsUnsigned(true);
1315 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001316 }
1317
Douglas Gregor4c678342009-01-28 21:54:33 +00001318 // Make sure that our non-designated initializer list has space
1319 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001320 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
1321 StructuredList->resizeInits(SemaRef->Context,
1322 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001323
Douglas Gregor34e79462009-01-28 23:36:17 +00001324 // Repeatedly perform subobject initializations in the range
1325 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001326
Douglas Gregor34e79462009-01-28 23:36:17 +00001327 // Move to the next designator
1328 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1329 unsigned OldIndex = Index;
1330 ++D;
1331 while (DesignatedStartIndex <= DesignatedEndIndex) {
1332 // Recurse to check later designated subobjects.
1333 QualType ElementType = AT->getElementType();
1334 Index = OldIndex;
1335 if (CheckDesignatedInitializer(IList, DIE, D, ElementType, 0, 0, Index,
1336 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001337 (DesignatedStartIndex == DesignatedEndIndex),
1338 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001339 return true;
1340
1341 // Move to the next index in the array that we'll be initializing.
1342 ++DesignatedStartIndex;
1343 ElementIndex = DesignatedStartIndex.getZExtValue();
1344 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001345
1346 // If this the first designator, our caller will continue checking
1347 // the rest of this array subobject.
1348 if (IsFirstDesignator) {
1349 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001350 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001351 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001352 return false;
1353 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001354
1355 if (!FinishSubobjectInit)
1356 return false;
1357
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001358 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001359 bool prevHadError = hadError;
Douglas Gregorfdf55692009-02-09 19:45:19 +00001360 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001361 StructuredList, ElementIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001362 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001363}
1364
Douglas Gregor4c678342009-01-28 21:54:33 +00001365// Get the structured initializer list for a subobject of type
1366// @p CurrentObjectType.
1367InitListExpr *
1368InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1369 QualType CurrentObjectType,
1370 InitListExpr *StructuredList,
1371 unsigned StructuredIndex,
1372 SourceRange InitRange) {
1373 Expr *ExistingInit = 0;
1374 if (!StructuredList)
1375 ExistingInit = SyntacticToSemantic[IList];
1376 else if (StructuredIndex < StructuredList->getNumInits())
1377 ExistingInit = StructuredList->getInit(StructuredIndex);
1378
1379 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1380 return Result;
1381
1382 if (ExistingInit) {
1383 // We are creating an initializer list that initializes the
1384 // subobjects of the current object, but there was already an
1385 // initialization that completely initialized the current
1386 // subobject, e.g., by a compound literal:
1387 //
1388 // struct X { int a, b; };
1389 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1390 //
1391 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1392 // designated initializer re-initializes the whole
1393 // subobject [0], overwriting previous initializers.
1394 SemaRef->Diag(InitRange.getBegin(), diag::warn_subobject_initializer_overrides)
1395 << InitRange;
1396 SemaRef->Diag(ExistingInit->getSourceRange().getBegin(),
1397 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001398 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001399 << ExistingInit->getSourceRange();
1400 }
1401
Douglas Gregor87fd7032009-02-02 17:43:21 +00001402 SourceLocation StartLoc;
1403 if (Index < IList->getNumInits())
1404 StartLoc = IList->getInit(Index)->getSourceRange().getBegin();
Douglas Gregor4c678342009-01-28 21:54:33 +00001405 InitListExpr *Result
Douglas Gregor87fd7032009-02-02 17:43:21 +00001406 = new (SemaRef->Context) InitListExpr(StartLoc, 0, 0,
1407 IList->getSourceRange().getEnd());
Douglas Gregor4c678342009-01-28 21:54:33 +00001408 Result->setType(CurrentObjectType);
1409
1410 // Link this new initializer list into the structured initializer
1411 // lists.
1412 if (StructuredList)
1413 StructuredList->updateInit(StructuredIndex, Result);
1414 else {
1415 Result->setSyntacticForm(IList);
1416 SyntacticToSemantic[IList] = Result;
1417 }
1418
1419 return Result;
1420}
1421
1422/// Update the initializer at index @p StructuredIndex within the
1423/// structured initializer list to the value @p expr.
1424void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1425 unsigned &StructuredIndex,
1426 Expr *expr) {
1427 // No structured initializer list to update
1428 if (!StructuredList)
1429 return;
1430
1431 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1432 // This initializer overwrites a previous initializer. Warn.
1433 SemaRef->Diag(expr->getSourceRange().getBegin(),
1434 diag::warn_initializer_overrides)
1435 << expr->getSourceRange();
1436 SemaRef->Diag(PrevInit->getSourceRange().getBegin(),
1437 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001438 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001439 << PrevInit->getSourceRange();
1440 }
1441
1442 ++StructuredIndex;
1443}
1444
Douglas Gregor05c13a32009-01-22 00:58:24 +00001445/// Check that the given Index expression is a valid array designator
1446/// value. This is essentailly just a wrapper around
1447/// Expr::isIntegerConstantExpr that also checks for negative values
1448/// and produces a reasonable diagnostic if there is a
1449/// failure. Returns true if there was an error, false otherwise. If
1450/// everything went okay, Value will receive the value of the constant
1451/// expression.
1452static bool
1453CheckArrayDesignatorExpr(Sema &Self, Expr *Index, llvm::APSInt &Value) {
1454 SourceLocation Loc = Index->getSourceRange().getBegin();
1455
1456 // Make sure this is an integer constant expression.
1457 if (!Index->isIntegerConstantExpr(Value, Self.Context, &Loc))
1458 return Self.Diag(Loc, diag::err_array_designator_nonconstant)
1459 << Index->getSourceRange();
1460
1461 // Make sure this constant expression is non-negative.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001462 llvm::APSInt Zero(llvm::APSInt::getNullValue(Value.getBitWidth()),
1463 Value.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001464 if (Value < Zero)
1465 return Self.Diag(Loc, diag::err_array_designator_negative)
1466 << Value.toString(10) << Index->getSourceRange();
1467
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001468 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001469 return false;
1470}
1471
1472Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1473 SourceLocation Loc,
1474 bool UsedColonSyntax,
1475 OwningExprResult Init) {
1476 typedef DesignatedInitExpr::Designator ASTDesignator;
1477
1478 bool Invalid = false;
1479 llvm::SmallVector<ASTDesignator, 32> Designators;
1480 llvm::SmallVector<Expr *, 32> InitExpressions;
1481
1482 // Build designators and check array designator expressions.
1483 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1484 const Designator &D = Desig.getDesignator(Idx);
1485 switch (D.getKind()) {
1486 case Designator::FieldDesignator:
1487 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1488 D.getFieldLoc()));
1489 break;
1490
1491 case Designator::ArrayDesignator: {
1492 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1493 llvm::APSInt IndexValue;
1494 if (CheckArrayDesignatorExpr(*this, Index, IndexValue))
1495 Invalid = true;
1496 else {
1497 Designators.push_back(ASTDesignator(InitExpressions.size(),
1498 D.getLBracketLoc(),
1499 D.getRBracketLoc()));
1500 InitExpressions.push_back(Index);
1501 }
1502 break;
1503 }
1504
1505 case Designator::ArrayRangeDesignator: {
1506 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1507 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1508 llvm::APSInt StartValue;
1509 llvm::APSInt EndValue;
1510 if (CheckArrayDesignatorExpr(*this, StartIndex, StartValue) ||
1511 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))
1512 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001513 else {
1514 // Make sure we're comparing values with the same bit width.
1515 if (StartValue.getBitWidth() > EndValue.getBitWidth())
1516 EndValue.extend(StartValue.getBitWidth());
1517 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1518 StartValue.extend(EndValue.getBitWidth());
1519
1520 if (EndValue < StartValue) {
1521 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1522 << StartValue.toString(10) << EndValue.toString(10)
1523 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1524 Invalid = true;
1525 } else {
1526 Designators.push_back(ASTDesignator(InitExpressions.size(),
1527 D.getLBracketLoc(),
1528 D.getEllipsisLoc(),
1529 D.getRBracketLoc()));
1530 InitExpressions.push_back(StartIndex);
1531 InitExpressions.push_back(EndIndex);
1532 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001533 }
1534 break;
1535 }
1536 }
1537 }
1538
1539 if (Invalid || Init.isInvalid())
1540 return ExprError();
1541
1542 // Clear out the expressions within the designation.
1543 Desig.ClearExprs(*this);
1544
1545 DesignatedInitExpr *DIE
1546 = DesignatedInitExpr::Create(Context, &Designators[0], Designators.size(),
1547 &InitExpressions[0], InitExpressions.size(),
1548 Loc, UsedColonSyntax,
1549 static_cast<Expr *>(Init.release()));
1550 return Owned(DIE);
1551}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001552
1553bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
1554 InitListChecker CheckInitList(this, InitList, DeclType);
1555 if (!CheckInitList.HadError())
1556 InitList = CheckInitList.getFullyStructuredList();
1557
1558 return CheckInitList.HadError();
1559}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001560
1561/// \brief Diagnose any semantic errors with value-initialization of
1562/// the given type.
1563///
1564/// Value-initialization effectively zero-initializes any types
1565/// without user-declared constructors, and calls the default
1566/// constructor for a for any type that has a user-declared
1567/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1568/// a type with a user-declared constructor does not have an
1569/// accessible, non-deleted default constructor. In C, everything can
1570/// be value-initialized, which corresponds to C's notion of
1571/// initializing objects with static storage duration when no
1572/// initializer is provided for that object.
1573///
1574/// \returns true if there was an error, false otherwise.
1575bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1576 // C++ [dcl.init]p5:
1577 //
1578 // To value-initialize an object of type T means:
1579
1580 // -- if T is an array type, then each element is value-initialized;
1581 if (const ArrayType *AT = Context.getAsArrayType(Type))
1582 return CheckValueInitialization(AT->getElementType(), Loc);
1583
1584 if (const RecordType *RT = Type->getAsRecordType()) {
1585 if (const CXXRecordType *CXXRec = dyn_cast<CXXRecordType>(RT)) {
1586 // -- if T is a class type (clause 9) with a user-declared
1587 // constructor (12.1), then the default constructor for T is
1588 // called (and the initialization is ill-formed if T has no
1589 // accessible default constructor);
1590 if (CXXRec->getDecl()->hasUserDeclaredConstructor())
1591 // FIXME: Eventually, we'll need to put the constructor decl
1592 // into the AST.
1593 return PerformInitializationByConstructor(Type, 0, 0, Loc,
1594 SourceRange(Loc),
1595 DeclarationName(),
1596 IK_Direct);
1597 }
1598 }
1599
1600 if (Type->isReferenceType()) {
1601 // C++ [dcl.init]p5:
1602 // [...] A program that calls for default-initialization or
1603 // value-initialization of an entity of reference type is
1604 // ill-formed. [...]
Douglas Gregord8635172009-02-02 21:35:47 +00001605 // FIXME: Once we have code that goes through this path, add an
1606 // actual diagnostic :)
Douglas Gregor87fd7032009-02-02 17:43:21 +00001607 }
1608
1609 return false;
1610}