blob: e3235ac401ef40ce46c850e282cd5d8464ee9827 [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
30StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
31 if (const ArrayType *AT = Context.getAsArrayType(DeclType))
32 if (AT->getElementType()->isCharType())
33 return dyn_cast<StringLiteral>(Init->IgnoreParens());
34 return 0;
35}
36
37bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType,
38 bool DirectInit) {
39 // Get the type before calling CheckSingleAssignmentConstraints(), since
40 // it can promote the expression.
41 QualType InitType = Init->getType();
42
43 if (getLangOptions().CPlusPlus) {
44 // FIXME: I dislike this error message. A lot.
45 if (PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
46 return Diag(Init->getSourceRange().getBegin(),
47 diag::err_typecheck_convert_incompatible)
48 << DeclType << Init->getType() << "initializing"
49 << Init->getSourceRange();
50
51 return false;
52 }
53
54 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
55 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
56 InitType, Init, "initializing");
57}
58
59bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
60 const ArrayType *AT = Context.getAsArrayType(DeclT);
61
62 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
63 // C99 6.7.8p14. We have an array of character type with unknown size
64 // being initialized to a string literal.
65 llvm::APSInt ConstVal(32);
66 ConstVal = strLiteral->getByteLength() + 1;
67 // Return a new array type (C99 6.7.8p22).
68 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
69 ArrayType::Normal, 0);
70 } else {
71 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
72 // C99 6.7.8p14. We have an array of character type with known size.
73 // FIXME: Avoid truncation for 64-bit length strings.
74 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
75 Diag(strLiteral->getSourceRange().getBegin(),
76 diag::warn_initializer_string_for_char_array_too_long)
77 << strLiteral->getSourceRange();
78 }
79 // Set type from "char *" to "constant array of char".
80 strLiteral->setType(DeclT);
81 // For now, we always return false (meaning success).
82 return false;
83}
84
85bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
86 SourceLocation InitLoc,
87 DeclarationName InitEntity,
88 bool DirectInit) {
89 if (DeclType->isDependentType() || Init->isTypeDependent())
90 return false;
91
92 // C++ [dcl.init.ref]p1:
93 // A variable declared to be a T&, that is "reference to type T"
94 // (8.3.2), shall be initialized by an object, or function, of
95 // type T or by an object that can be converted into a T.
96 if (DeclType->isReferenceType())
97 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
98
99 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
100 // of unknown size ("[]") or an object type that is not a variable array type.
101 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
102 return Diag(InitLoc, diag::err_variable_object_no_init)
103 << VAT->getSizeExpr()->getSourceRange();
104
105 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
106 if (!InitList) {
107 // FIXME: Handle wide strings
108 if (StringLiteral *StrLiteral = IsStringLiteralInit(Init, DeclType))
109 return CheckStringLiteralInit(StrLiteral, DeclType);
110
111 // C++ [dcl.init]p14:
112 // -- If the destination type is a (possibly cv-qualified) class
113 // type:
114 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
115 QualType DeclTypeC = Context.getCanonicalType(DeclType);
116 QualType InitTypeC = Context.getCanonicalType(Init->getType());
117
118 // -- If the initialization is direct-initialization, or if it is
119 // copy-initialization where the cv-unqualified version of the
120 // source type is the same class as, or a derived class of, the
121 // class of the destination, constructors are considered.
122 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
123 IsDerivedFrom(InitTypeC, DeclTypeC)) {
124 CXXConstructorDecl *Constructor
125 = PerformInitializationByConstructor(DeclType, &Init, 1,
126 InitLoc, Init->getSourceRange(),
127 InitEntity,
128 DirectInit? IK_Direct : IK_Copy);
129 return Constructor == 0;
130 }
131
132 // -- Otherwise (i.e., for the remaining copy-initialization
133 // cases), user-defined conversion sequences that can
134 // convert from the source type to the destination type or
135 // (when a conversion function is used) to a derived class
136 // thereof are enumerated as described in 13.3.1.4, and the
137 // best one is chosen through overload resolution
138 // (13.3). If the conversion cannot be done or is
139 // ambiguous, the initialization is ill-formed. The
140 // function selected is called with the initializer
141 // expression as its argument; if the function is a
142 // constructor, the call initializes a temporary of the
143 // destination type.
144 // FIXME: We're pretending to do copy elision here; return to
145 // this when we have ASTs for such things.
146 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
147 return false;
148
149 if (InitEntity)
150 return Diag(InitLoc, diag::err_cannot_initialize_decl)
151 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
152 << Init->getType() << Init->getSourceRange();
153 else
154 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
155 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
156 << Init->getType() << Init->getSourceRange();
157 }
158
159 // C99 6.7.8p16.
160 if (DeclType->isArrayType())
161 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
162 << Init->getSourceRange();
163
164 return CheckSingleInitializer(Init, DeclType, DirectInit);
165 }
166
167 bool hadError = CheckInitList(InitList, DeclType);
168 Init = InitList;
169 return hadError;
170}
171
172//===----------------------------------------------------------------------===//
173// Semantic checking for initializer lists.
174//===----------------------------------------------------------------------===//
175
Douglas Gregor9e80f722009-01-29 01:05:33 +0000176/// @brief Semantic checking for initializer lists.
177///
178/// The InitListChecker class contains a set of routines that each
179/// handle the initialization of a certain kind of entity, e.g.,
180/// arrays, vectors, struct/union types, scalars, etc. The
181/// InitListChecker itself performs a recursive walk of the subobject
182/// structure of the type to be initialized, while stepping through
183/// the initializer list one element at a time. The IList and Index
184/// parameters to each of the Check* routines contain the active
185/// (syntactic) initializer list and the index into that initializer
186/// list that represents the current initializer. Each routine is
187/// responsible for moving that Index forward as it consumes elements.
188///
189/// Each Check* routine also has a StructuredList/StructuredIndex
190/// arguments, which contains the current the "structured" (semantic)
191/// initializer list and the index into that initializer list where we
192/// are copying initializers as we map them over to the semantic
193/// list. Once we have completed our recursive walk of the subobject
194/// structure, we will have constructed a full semantic initializer
195/// list.
196///
197/// C99 designators cause changes in the initializer list traversal,
198/// because they make the initialization "jump" into a specific
199/// subobject and then continue the initialization from that
200/// point. CheckDesignatedInitializer() recursively steps into the
201/// designated subobject and manages backing out the recursion to
202/// initialize the subobjects after the one designated.
Chris Lattner68355a52009-01-29 05:10:57 +0000203namespace clang {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000204class InitListChecker {
205 Sema *SemaRef;
206 bool hadError;
207 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
208 InitListExpr *FullyStructuredList;
209
210 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000211 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000212 unsigned &StructuredIndex,
213 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000214 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000215 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000216 unsigned &StructuredIndex,
217 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000218 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
219 bool SubobjectIsDesignatorContext,
220 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000221 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000222 unsigned &StructuredIndex,
223 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000224 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
225 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000226 InitListExpr *StructuredList,
227 unsigned &StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000228 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000229 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000230 InitListExpr *StructuredList,
231 unsigned &StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000232 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
233 unsigned &Index,
234 InitListExpr *StructuredList,
235 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000236 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000237 InitListExpr *StructuredList,
238 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000239 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
240 RecordDecl::field_iterator Field,
241 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000242 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000243 unsigned &StructuredIndex,
244 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000245 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
246 llvm::APSInt elementIndex,
247 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000248 InitListExpr *StructuredList,
249 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000250 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
251 DesignatedInitExpr::designators_iterator D,
252 QualType &CurrentObjectType,
253 RecordDecl::field_iterator *NextField,
254 llvm::APSInt *NextElementIndex,
255 unsigned &Index,
256 InitListExpr *StructuredList,
257 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000258 bool FinishSubobjectInit,
259 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000260 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
261 QualType CurrentObjectType,
262 InitListExpr *StructuredList,
263 unsigned StructuredIndex,
264 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000265 void UpdateStructuredListElement(InitListExpr *StructuredList,
266 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000267 Expr *expr);
268 int numArrayElements(QualType DeclType);
269 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000270
271 void FillInValueInitializations(InitListExpr *ILE);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000272public:
273 InitListChecker(Sema *S, InitListExpr *IL, QualType &T);
274 bool HadError() { return hadError; }
275
276 // @brief Retrieves the fully-structured initializer list used for
277 // semantic analysis and code generation.
278 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
279};
Chris Lattner68355a52009-01-29 05:10:57 +0000280}
281
Douglas Gregor4c678342009-01-28 21:54:33 +0000282/// Recursively replaces NULL values within the given initializer list
283/// with expressions that perform value-initialization of the
284/// appropriate type.
Douglas Gregor930d8b52009-01-30 22:09:00 +0000285void InitListChecker::FillInValueInitializations(InitListExpr *ILE) {
286 assert((ILE->getType() != SemaRef->Context.VoidTy) &&
287 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000288 SourceLocation Loc = ILE->getSourceRange().getBegin();
289 if (ILE->getSyntacticForm())
290 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
291
Douglas Gregor4c678342009-01-28 21:54:33 +0000292 if (const RecordType *RType = ILE->getType()->getAsRecordType()) {
293 unsigned Init = 0, NumInits = ILE->getNumInits();
294 for (RecordDecl::field_iterator Field = RType->getDecl()->field_begin(),
295 FieldEnd = RType->getDecl()->field_end();
296 Field != FieldEnd; ++Field) {
297 if (Field->isUnnamedBitfield())
298 continue;
299
Douglas Gregor87fd7032009-02-02 17:43:21 +0000300 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000301 if (Field->getType()->isReferenceType()) {
302 // C++ [dcl.init.aggr]p9:
303 // If an incomplete or empty initializer-list leaves a
304 // member of reference type uninitialized, the program is
305 // ill-formed.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000306 SemaRef->Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000307 << Field->getType()
308 << ILE->getSyntacticForm()->getSourceRange();
309 SemaRef->Diag(Field->getLocation(),
310 diag::note_uninit_reference_member);
311 hadError = true;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000312 return;
313 } else if (SemaRef->CheckValueInitialization(Field->getType(), Loc)) {
314 hadError = true;
315 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000316 }
Douglas Gregor87fd7032009-02-02 17:43:21 +0000317
318 // FIXME: If value-initialization involves calling a
319 // constructor, should we make that call explicit in the
320 // representation (even when it means extending the
321 // initializer list)?
322 if (Init < NumInits && !hadError)
323 ILE->setInit(Init,
324 new (SemaRef->Context) ImplicitValueInitExpr(Field->getType()));
325 } else if (InitListExpr *InnerILE
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000326 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000327 FillInValueInitializations(InnerILE);
Douglas Gregor4c678342009-01-28 21:54:33 +0000328 ++Init;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000329
330 // Only look at the first initialization of a union.
331 if (RType->getDecl()->isUnion())
332 break;
Douglas Gregor4c678342009-01-28 21:54:33 +0000333 }
334
335 return;
336 }
337
338 QualType ElementType;
339
Douglas Gregor87fd7032009-02-02 17:43:21 +0000340 unsigned NumInits = ILE->getNumInits();
341 unsigned NumElements = NumInits;
342 if (const ArrayType *AType = SemaRef->Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000343 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000344 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
345 NumElements = CAType->getSize().getZExtValue();
346 } else if (const VectorType *VType = ILE->getType()->getAsVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000347 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000348 NumElements = VType->getNumElements();
349 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000350 ElementType = ILE->getType();
351
Douglas Gregor87fd7032009-02-02 17:43:21 +0000352 for (unsigned Init = 0; Init != NumElements; ++Init) {
353 if (Init >= NumInits || !ILE->getInit(Init)) {
354 if (SemaRef->CheckValueInitialization(ElementType, Loc)) {
355 hadError = true;
356 return;
357 }
358
359 // FIXME: If value-initialization involves calling a
360 // constructor, should we make that call explicit in the
361 // representation (even when it means extending the
362 // initializer list)?
363 if (Init < NumInits && !hadError)
364 ILE->setInit(Init,
365 new (SemaRef->Context) ImplicitValueInitExpr(ElementType));
366 }
Chris Lattner68355a52009-01-29 05:10:57 +0000367 else if (InitListExpr *InnerILE =dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000368 FillInValueInitializations(InnerILE);
Douglas Gregor4c678342009-01-28 21:54:33 +0000369 }
370}
371
Chris Lattner68355a52009-01-29 05:10:57 +0000372
Steve Naroff0cca7492008-05-01 22:18:59 +0000373InitListChecker::InitListChecker(Sema *S, InitListExpr *IL, QualType &T) {
374 hadError = false;
375 SemaRef = S;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000376
Eli Friedmanb85f7072008-05-19 19:16:24 +0000377 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000378 unsigned newStructuredIndex = 0;
379 FullyStructuredList
380 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, SourceRange());
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000381 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
382 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000383
Douglas Gregor930d8b52009-01-30 22:09:00 +0000384 if (!hadError)
385 FillInValueInitializations(FullyStructuredList);
Steve Naroff0cca7492008-05-01 22:18:59 +0000386}
387
388int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000389 // FIXME: use a proper constant
390 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000391 if (const ConstantArrayType *CAT =
392 SemaRef->Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000393 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
394 }
395 return maxElements;
396}
397
398int InitListChecker::numStructUnionElements(QualType DeclType) {
399 RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000400 int InitializableMembers = 0;
401 for (RecordDecl::field_iterator Field = structDecl->field_begin(),
402 FieldEnd = structDecl->field_end();
403 Field != FieldEnd; ++Field) {
404 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
405 ++InitializableMembers;
406 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000407 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000408 return std::min(InitializableMembers, 1);
409 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000410}
411
412void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000413 QualType T, unsigned &Index,
414 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000415 unsigned &StructuredIndex,
416 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000417 int maxElements = 0;
418
419 if (T->isArrayType())
420 maxElements = numArrayElements(T);
421 else if (T->isStructureType() || T->isUnionType())
422 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000423 else if (T->isVectorType())
424 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000425 else
426 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000427
Eli Friedman402256f2008-05-25 13:49:22 +0000428 if (maxElements == 0) {
429 SemaRef->Diag(ParentIList->getInit(Index)->getLocStart(),
430 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000431 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000432 hadError = true;
433 return;
434 }
435
Douglas Gregor4c678342009-01-28 21:54:33 +0000436 // Build a structured initializer list corresponding to this subobject.
437 InitListExpr *StructuredSubobjectInitList
438 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
439 StructuredIndex,
440 ParentIList->getInit(Index)->getSourceRange());
441 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000442
Douglas Gregor4c678342009-01-28 21:54:33 +0000443 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000444 unsigned StartIndex = Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000445 CheckListElementTypes(ParentIList, T, false, Index,
446 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000447 StructuredSubobjectInitIndex,
448 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000449 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
450
451 // Update the structured sub-object initialize so that it's ending
452 // range corresponds with the end of the last initializer it used.
453 if (EndIndex < ParentIList->getNumInits()) {
454 SourceLocation EndLoc
455 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
456 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
457 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000458}
459
Steve Naroffa647caa2008-05-06 00:23:44 +0000460void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000461 unsigned &Index,
462 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000463 unsigned &StructuredIndex,
464 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000465 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000466 SyntacticToSemantic[IList] = StructuredList;
467 StructuredList->setSyntacticForm(IList);
468 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000469 StructuredIndex, TopLevelObject);
Steve Naroffa647caa2008-05-06 00:23:44 +0000470 IList->setType(T);
Douglas Gregor4c678342009-01-28 21:54:33 +0000471 StructuredList->setType(T);
Eli Friedman638e1442008-05-25 13:22:35 +0000472 if (hadError)
473 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000474
Eli Friedman638e1442008-05-25 13:22:35 +0000475 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000476 // We have leftover initializers
477 if (IList->getNumInits() > 0 &&
478 SemaRef->IsStringLiteralInit(IList->getInit(Index), T)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000479 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
480 if (SemaRef->getLangOptions().CPlusPlus)
481 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000482 // Special-case
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000483 SemaRef->Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000484 << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000485 hadError = true;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000486 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000487 // Don't complain for incomplete types, since we'll get an error
488 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000489 QualType CurrentObjectType = StructuredList->getType();
490 int initKind =
491 CurrentObjectType->isArrayType()? 0 :
492 CurrentObjectType->isVectorType()? 1 :
493 CurrentObjectType->isScalarType()? 2 :
494 CurrentObjectType->isUnionType()? 3 :
495 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000496
497 unsigned DK = diag::warn_excess_initializers;
498 if (SemaRef->getLangOptions().CPlusPlus)
499 DK = diag::err_excess_initializers;
500
501 SemaRef->Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000502 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000503 }
504 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000505
Eli Friedman638e1442008-05-25 13:22:35 +0000506 if (T->isScalarType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000507 SemaRef->Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
508 << IList->getSourceRange();
Steve Naroff0cca7492008-05-01 22:18:59 +0000509}
510
Eli Friedmanb85f7072008-05-19 19:16:24 +0000511void InitListChecker::CheckListElementTypes(InitListExpr *IList,
512 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000513 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000514 unsigned &Index,
515 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000516 unsigned &StructuredIndex,
517 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000518 if (DeclType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000519 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000520 } else if (DeclType->isVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000521 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000522 } else if (DeclType->isAggregateType()) {
523 if (DeclType->isRecordType()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000524 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
525 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000526 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000527 StructuredList, StructuredIndex,
528 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000529 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000530 llvm::APSInt Zero(
531 SemaRef->Context.getTypeSize(SemaRef->Context.getSizeType()),
532 false);
Douglas Gregor4c678342009-01-28 21:54:33 +0000533 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
534 StructuredList, StructuredIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000535 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000536 else
Douglas Gregor4c678342009-01-28 21:54:33 +0000537 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000538 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
539 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000540 ++Index;
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000541 SemaRef->Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000542 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000543 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000544 } else if (DeclType->isRecordType()) {
545 // C++ [dcl.init]p14:
546 // [...] If the class is an aggregate (8.5.1), and the initializer
547 // is a brace-enclosed list, see 8.5.1.
548 //
549 // Note: 8.5.1 is handled below; here, we diagnose the case where
550 // we have an initializer list and a destination type that is not
551 // an aggregate.
552 // FIXME: In C++0x, this is yet another form of initialization.
553 SemaRef->Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
554 << DeclType << IList->getSourceRange();
555 hadError = true;
556 } else if (DeclType->isReferenceType()) {
557 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000558 } else {
559 // In C, all types are either scalars or aggregates, but
560 // additional handling is needed here for C++ (and possibly others?).
561 assert(0 && "Unsupported initializer type");
562 }
563}
564
Eli Friedmanb85f7072008-05-19 19:16:24 +0000565void InitListChecker::CheckSubElementType(InitListExpr *IList,
566 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000567 unsigned &Index,
568 InitListExpr *StructuredList,
569 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000570 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000571 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
572 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000573 unsigned newStructuredIndex = 0;
574 InitListExpr *newStructuredList
575 = getStructuredSubobjectInit(IList, Index, ElemType,
576 StructuredList, StructuredIndex,
577 SubInitList->getSourceRange());
578 CheckExplicitInitList(SubInitList, ElemType, newIndex,
579 newStructuredList, newStructuredIndex);
580 ++StructuredIndex;
581 ++Index;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000582 } else if (StringLiteral *lit =
583 SemaRef->IsStringLiteralInit(expr, ElemType)) {
584 SemaRef->CheckStringLiteralInit(lit, ElemType);
Douglas Gregor4c678342009-01-28 21:54:33 +0000585 UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
586 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000587 } else if (ElemType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000588 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000589 } else if (ElemType->isReferenceType()) {
590 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000591 } else {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000592 if (SemaRef->getLangOptions().CPlusPlus) {
593 // C++ [dcl.init.aggr]p12:
594 // All implicit type conversions (clause 4) are considered when
595 // initializing the aggregate member with an ini- tializer from
596 // an initializer-list. If the initializer can initialize a
597 // member, the member is initialized. [...]
598 ImplicitConversionSequence ICS
599 = SemaRef->TryCopyInitialization(expr, ElemType);
600 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
601 if (SemaRef->PerformImplicitConversion(expr, ElemType, ICS,
602 "initializing"))
603 hadError = true;
604 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
605 ++Index;
606 return;
607 }
608
609 // Fall through for subaggregate initialization
610 } else {
611 // C99 6.7.8p13:
612 //
613 // The initializer for a structure or union object that has
614 // automatic storage duration shall be either an initializer
615 // list as described below, or a single expression that has
616 // compatible structure or union type. In the latter case, the
617 // initial value of the object, including unnamed members, is
618 // that of the expression.
619 QualType ExprType = SemaRef->Context.getCanonicalType(expr->getType());
620 QualType ElemTypeCanon = SemaRef->Context.getCanonicalType(ElemType);
621 if (SemaRef->Context.typesAreCompatible(ExprType.getUnqualifiedType(),
622 ElemTypeCanon.getUnqualifiedType())) {
623 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
624 ++Index;
625 return;
626 }
627
628 // Fall through for subaggregate initialization
629 }
630
631 // C++ [dcl.init.aggr]p12:
632 //
633 // [...] Otherwise, if the member is itself a non-empty
634 // subaggregate, brace elision is assumed and the initializer is
635 // considered for the initialization of the first member of
636 // the subaggregate.
637 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
638 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
639 StructuredIndex);
640 ++StructuredIndex;
641 } else {
642 // We cannot initialize this element, so let
643 // PerformCopyInitialization produce the appropriate diagnostic.
644 SemaRef->PerformCopyInitialization(expr, ElemType, "initializing");
645 hadError = true;
646 ++Index;
647 ++StructuredIndex;
648 }
649 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000650}
651
Douglas Gregor930d8b52009-01-30 22:09:00 +0000652void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000653 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000654 InitListExpr *StructuredList,
655 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000656 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000657 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000658 if (isa<InitListExpr>(expr)) {
Eli Friedmanbb504d32008-05-19 20:12:18 +0000659 SemaRef->Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000660 diag::err_many_braces_around_scalar_init)
661 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000662 hadError = true;
663 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000664 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000665 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000666 } else if (isa<DesignatedInitExpr>(expr)) {
667 SemaRef->Diag(expr->getSourceRange().getBegin(),
668 diag::err_designator_for_scalar_init)
669 << DeclType << expr->getSourceRange();
670 hadError = true;
671 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000672 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000673 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000674 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000675
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000676 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000677 if (SemaRef->CheckSingleInitializer(expr, DeclType, false))
Eli Friedmanbb504d32008-05-19 20:12:18 +0000678 hadError = true; // types weren't compatible.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000679 else if (savExpr != expr) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000680 // The type was promoted, update initializer list.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000681 IList->setInit(Index, expr);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000682 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000683 if (hadError)
684 ++StructuredIndex;
685 else
686 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000687 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000688 } else {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000689 SemaRef->Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
690 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000691 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000692 ++Index;
693 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000694 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000695 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000696}
697
Douglas Gregor930d8b52009-01-30 22:09:00 +0000698void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
699 unsigned &Index,
700 InitListExpr *StructuredList,
701 unsigned &StructuredIndex) {
702 if (Index < IList->getNumInits()) {
703 Expr *expr = IList->getInit(Index);
704 if (isa<InitListExpr>(expr)) {
705 SemaRef->Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
706 << DeclType << IList->getSourceRange();
707 hadError = true;
708 ++Index;
709 ++StructuredIndex;
710 return;
711 }
712
713 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
714 if (SemaRef->CheckReferenceInit(expr, DeclType))
715 hadError = true;
716 else if (savExpr != expr) {
717 // The type was promoted, update initializer list.
718 IList->setInit(Index, expr);
719 }
720 if (hadError)
721 ++StructuredIndex;
722 else
723 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
724 ++Index;
725 } else {
726 // FIXME: It would be wonderful if we could point at the actual
727 // member. In general, it would be useful to pass location
728 // information down the stack, so that we know the location (or
729 // decl) of the "current object" being initialized.
730 SemaRef->Diag(IList->getLocStart(),
731 diag::err_init_reference_member_uninitialized)
732 << DeclType
733 << IList->getSourceRange();
734 hadError = true;
735 ++Index;
736 ++StructuredIndex;
737 return;
738 }
739}
740
Steve Naroff0cca7492008-05-01 22:18:59 +0000741void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000742 unsigned &Index,
743 InitListExpr *StructuredList,
744 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000745 if (Index < IList->getNumInits()) {
746 const VectorType *VT = DeclType->getAsVectorType();
747 int maxElements = VT->getNumElements();
748 QualType elementType = VT->getElementType();
749
750 for (int i = 0; i < maxElements; ++i) {
751 // Don't attempt to go past the end of the init list
752 if (Index >= IList->getNumInits())
753 break;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000754 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000755 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000756 }
757 }
758}
759
760void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000761 llvm::APSInt elementIndex,
762 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000763 unsigned &Index,
764 InitListExpr *StructuredList,
765 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000766 // Check for the special-case of initializing an array with a string.
767 if (Index < IList->getNumInits()) {
768 if (StringLiteral *lit =
769 SemaRef->IsStringLiteralInit(IList->getInit(Index), DeclType)) {
770 SemaRef->CheckStringLiteralInit(lit, DeclType);
Douglas Gregor4c678342009-01-28 21:54:33 +0000771 // We place the string literal directly into the resulting
772 // initializer list. This is the only place where the structure
773 // of the structured initializer list doesn't match exactly,
774 // because doing so would involve allocating one character
775 // constant for each string.
776 UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
777 StructuredList->resizeInits(SemaRef->Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000778 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000779 return;
780 }
781 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000782 if (const VariableArrayType *VAT =
783 SemaRef->Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000784 // Check for VLAs; in standard C it would be possible to check this
785 // earlier, but I don't know where clang accepts VLAs (gcc accepts
786 // them in all sorts of strange places).
787 SemaRef->Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000788 diag::err_variable_object_no_init)
789 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000790 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000791 ++Index;
792 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000793 return;
794 }
795
Douglas Gregor05c13a32009-01-22 00:58:24 +0000796 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000797 llvm::APSInt maxElements(elementIndex.getBitWidth(),
798 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000799 bool maxElementsKnown = false;
800 if (const ConstantArrayType *CAT =
801 SemaRef->Context.getAsConstantArrayType(DeclType)) {
802 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000803 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000804 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000805 maxElementsKnown = true;
806 }
807
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000808 QualType elementType = SemaRef->Context.getAsArrayType(DeclType)
809 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000810 while (Index < IList->getNumInits()) {
811 Expr *Init = IList->getInit(Index);
812 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000813 // If we're not the subobject that matches up with the '{' for
814 // the designator, we shouldn't be handling the
815 // designator. Return immediately.
816 if (!SubobjectIsDesignatorContext)
817 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000818
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000819 // Handle this designated initializer. elementIndex will be
820 // updated to be the next array element we'll initialize.
821 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000822 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000823 StructuredList, StructuredIndex, true,
824 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000825 hadError = true;
826 continue;
827 }
828
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000829 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
830 maxElements.extend(elementIndex.getBitWidth());
831 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
832 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000833 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000834
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000835 // If the array is of incomplete type, keep track of the number of
836 // elements in the initializer.
837 if (!maxElementsKnown && elementIndex > maxElements)
838 maxElements = elementIndex;
839
Douglas Gregor05c13a32009-01-22 00:58:24 +0000840 continue;
841 }
842
843 // If we know the maximum number of elements, and we've already
844 // hit it, stop consuming elements in the initializer list.
845 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +0000846 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000847
848 // Check this element.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000849 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000850 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000851 ++elementIndex;
852
853 // If the array is of incomplete type, keep track of the number of
854 // elements in the initializer.
855 if (!maxElementsKnown && elementIndex > maxElements)
856 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +0000857 }
858 if (DeclType->isIncompleteArrayType()) {
859 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000860 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000861 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000862 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000863 // Sizing an array implicitly to zero is not allowed by ISO C,
864 // but is supported by GNU.
Steve Naroff0cca7492008-05-01 22:18:59 +0000865 SemaRef->Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000866 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +0000867 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000868
Douglas Gregor05c13a32009-01-22 00:58:24 +0000869 DeclType = SemaRef->Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000870 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +0000871 }
872}
873
874void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
875 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000876 RecordDecl::field_iterator Field,
877 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000878 unsigned &Index,
879 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000880 unsigned &StructuredIndex,
881 bool TopLevelObject) {
Eli Friedmanb85f7072008-05-19 19:16:24 +0000882 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroff0cca7492008-05-01 22:18:59 +0000883
Eli Friedmanb85f7072008-05-19 19:16:24 +0000884 // If the record is invalid, some of it's members are invalid. To avoid
885 // confusion, we forgo checking the intializer for the entire record.
886 if (structDecl->isInvalidDecl()) {
887 hadError = true;
888 return;
889 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000890
891 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
892 // Value-initialize the first named member of the union.
893 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
894 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
895 Field != FieldEnd; ++Field) {
896 if (Field->getDeclName()) {
897 StructuredList->setInitializedFieldInUnion(*Field);
898 break;
899 }
900 }
901 return;
902 }
903
Douglas Gregor05c13a32009-01-22 00:58:24 +0000904 // If structDecl is a forward declaration, this loop won't do
905 // anything except look at designated initializers; That's okay,
906 // because an error should get printed out elsewhere. It might be
907 // worthwhile to skip over the rest of the initializer, though.
Douglas Gregor44b43212008-12-11 16:49:14 +0000908 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000909 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +0000910 bool InitializedSomething = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000911 while (Index < IList->getNumInits()) {
912 Expr *Init = IList->getInit(Index);
913
914 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000915 // If we're not the subobject that matches up with the '{' for
916 // the designator, we shouldn't be handling the
917 // designator. Return immediately.
918 if (!SubobjectIsDesignatorContext)
919 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000920
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000921 // Handle this designated initializer. Field will be updated to
922 // the next field that we'll be initializing.
923 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000924 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000925 StructuredList, StructuredIndex,
926 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000927 hadError = true;
928
Douglas Gregordfb5e592009-02-12 19:00:39 +0000929 InitializedSomething = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000930 continue;
931 }
932
933 if (Field == FieldEnd) {
934 // We've run out of fields. We're done.
935 break;
936 }
937
Douglas Gregordfb5e592009-02-12 19:00:39 +0000938 // We've already initialized a member of a union. We're done.
939 if (InitializedSomething && DeclType->isUnionType())
940 break;
941
Douglas Gregor44b43212008-12-11 16:49:14 +0000942 // If we've hit the flexible array member at the end, we're done.
943 if (Field->getType()->isIncompleteArrayType())
944 break;
945
Douglas Gregor0bb76892009-01-29 16:53:55 +0000946 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000947 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +0000948 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000949 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +0000950 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000951
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000952 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000953 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +0000954 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +0000955
956 if (DeclType->isUnionType()) {
957 // Initialize the first field within the union.
958 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +0000959 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000960
961 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +0000962 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000963
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000964 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
965 Index >= IList->getNumInits() ||
966 !isa<InitListExpr>(IList->getInit(Index)))
967 return;
968
969 // Handle GNU flexible array initializers.
970 if (!TopLevelObject &&
971 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0) {
972 SemaRef->Diag(IList->getInit(Index)->getSourceRange().getBegin(),
973 diag::err_flexible_array_init_nonempty)
974 << IList->getInit(Index)->getSourceRange().getBegin();
975 SemaRef->Diag(Field->getLocation(), diag::note_flexible_array_member)
976 << *Field;
977 hadError = true;
978 }
979
980 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
981 StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000982}
Steve Naroff0cca7492008-05-01 22:18:59 +0000983
Douglas Gregor05c13a32009-01-22 00:58:24 +0000984/// @brief Check the well-formedness of a C99 designated initializer.
985///
986/// Determines whether the designated initializer @p DIE, which
987/// resides at the given @p Index within the initializer list @p
988/// IList, is well-formed for a current object of type @p DeclType
989/// (C99 6.7.8). The actual subobject that this designator refers to
990/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +0000991/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +0000992///
993/// @param IList The initializer list in which this designated
994/// initializer occurs.
995///
996/// @param DIE The designated initializer and its initialization
997/// expression.
998///
999/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1000/// into which the designation in @p DIE should refer.
1001///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001002/// @param NextField If non-NULL and the first designator in @p DIE is
1003/// a field, this will be set to the field declaration corresponding
1004/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001005///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001006/// @param NextElementIndex If non-NULL and the first designator in @p
1007/// DIE is an array designator or GNU array-range designator, this
1008/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001009///
1010/// @param Index Index into @p IList where the designated initializer
1011/// @p DIE occurs.
1012///
Douglas Gregor4c678342009-01-28 21:54:33 +00001013/// @param StructuredList The initializer list expression that
1014/// describes all of the subobject initializers in the order they'll
1015/// actually be initialized.
1016///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001017/// @returns true if there was an error, false otherwise.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001018bool
1019InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
1020 DesignatedInitExpr *DIE,
1021 DesignatedInitExpr::designators_iterator D,
1022 QualType &CurrentObjectType,
1023 RecordDecl::field_iterator *NextField,
1024 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001025 unsigned &Index,
1026 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001027 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001028 bool FinishSubobjectInit,
1029 bool TopLevelObject) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001030 if (D == DIE->designators_end()) {
1031 // Check the actual initialization for the designated object type.
1032 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001033
1034 // Temporarily remove the designator expression from the
1035 // initializer list that the child calls see, so that we don't try
1036 // to re-process the designator.
1037 unsigned OldIndex = Index;
1038 IList->setInit(OldIndex, DIE->getInit());
1039
1040 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001041 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001042
1043 // Restore the designated initializer expression in the syntactic
1044 // form of the initializer list.
1045 if (IList->getInit(OldIndex) != DIE->getInit())
1046 DIE->setInit(IList->getInit(OldIndex));
1047 IList->setInit(OldIndex, DIE);
1048
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001049 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001050 }
1051
Douglas Gregor4c678342009-01-28 21:54:33 +00001052 bool IsFirstDesignator = (D == DIE->designators_begin());
1053 assert((IsFirstDesignator || StructuredList) &&
1054 "Need a non-designated initializer list to start from");
1055
1056 // Determine the structural initializer list that corresponds to the
1057 // current subobject.
1058 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1059 : getStructuredSubobjectInit(IList, Index, CurrentObjectType, StructuredList,
1060 StructuredIndex,
1061 SourceRange(D->getStartLocation(),
1062 DIE->getSourceRange().getEnd()));
1063 assert(StructuredList && "Expected a structured initializer list");
1064
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001065 if (D->isFieldDesignator()) {
1066 // C99 6.7.8p7:
1067 //
1068 // If a designator has the form
1069 //
1070 // . identifier
1071 //
1072 // then the current object (defined below) shall have
1073 // structure or union type and the identifier shall be the
1074 // name of a member of that type.
1075 const RecordType *RT = CurrentObjectType->getAsRecordType();
1076 if (!RT) {
1077 SourceLocation Loc = D->getDotLoc();
1078 if (Loc.isInvalid())
1079 Loc = D->getFieldLoc();
1080 SemaRef->Diag(Loc, diag::err_field_designator_non_aggr)
1081 << SemaRef->getLangOptions().CPlusPlus << CurrentObjectType;
1082 ++Index;
1083 return true;
1084 }
1085
Douglas Gregor4c678342009-01-28 21:54:33 +00001086 // Note: we perform a linear search of the fields here, despite
1087 // the fact that we have a faster lookup method, because we always
1088 // need to compute the field's index.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001089 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001090 unsigned FieldIndex = 0;
1091 RecordDecl::field_iterator Field = RT->getDecl()->field_begin(),
1092 FieldEnd = RT->getDecl()->field_end();
1093 for (; Field != FieldEnd; ++Field) {
1094 if (Field->isUnnamedBitfield())
1095 continue;
1096
1097 if (Field->getIdentifier() == FieldName)
1098 break;
1099
1100 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001101 }
1102
Douglas Gregor4c678342009-01-28 21:54:33 +00001103 if (Field == FieldEnd) {
1104 // We did not find the field we're looking for. Produce a
1105 // suitable diagnostic and return a failure.
1106 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
1107 if (Lookup.first == Lookup.second) {
1108 // Name lookup didn't find anything.
1109 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1110 << FieldName << CurrentObjectType;
1111 } else {
1112 // Name lookup found something, but it wasn't a field.
1113 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
1114 << FieldName;
1115 SemaRef->Diag((*Lookup.first)->getLocation(),
1116 diag::note_field_designator_found);
1117 }
1118
1119 ++Index;
1120 return true;
1121 } else if (cast<RecordDecl>((*Field)->getDeclContext())
1122 ->isAnonymousStructOrUnion()) {
1123 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_anon_class)
1124 << FieldName
1125 << (cast<RecordDecl>((*Field)->getDeclContext())->isUnion()? 2 :
1126 (int)SemaRef->getLangOptions().CPlusPlus);
1127 SemaRef->Diag((*Field)->getLocation(), diag::note_field_designator_found);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001128 ++Index;
1129 return true;
1130 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001131
1132 // All of the fields of a union are located at the same place in
1133 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001134 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001135 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001136 StructuredList->setInitializedFieldInUnion(*Field);
1137 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001138
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001139 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001140 D->setField(*Field);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001141
Douglas Gregor4c678342009-01-28 21:54:33 +00001142 // Make sure that our non-designated initializer list has space
1143 // for a subobject corresponding to this field.
1144 if (FieldIndex >= StructuredList->getNumInits())
1145 StructuredList->resizeInits(SemaRef->Context, FieldIndex + 1);
1146
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001147 // This designator names a flexible array member.
1148 if (Field->getType()->isIncompleteArrayType()) {
1149 bool Invalid = false;
1150 DesignatedInitExpr::designators_iterator NextD = D;
1151 ++NextD;
1152 if (NextD != DIE->designators_end()) {
1153 // We can't designate an object within the flexible array
1154 // member (because GCC doesn't allow it).
1155 SemaRef->Diag(NextD->getStartLocation(),
1156 diag::err_designator_into_flexible_array_member)
1157 << SourceRange(NextD->getStartLocation(),
1158 DIE->getSourceRange().getEnd());
1159 SemaRef->Diag(Field->getLocation(), diag::note_flexible_array_member)
1160 << *Field;
1161 Invalid = true;
1162 }
1163
1164 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1165 // The initializer is not an initializer list.
1166 SemaRef->Diag(DIE->getInit()->getSourceRange().getBegin(),
1167 diag::err_flexible_array_init_needs_braces)
1168 << DIE->getInit()->getSourceRange();
1169 SemaRef->Diag(Field->getLocation(), diag::note_flexible_array_member)
1170 << *Field;
1171 Invalid = true;
1172 }
1173
1174 // Handle GNU flexible array initializers.
1175 if (!Invalid && !TopLevelObject &&
1176 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
1177 SemaRef->Diag(DIE->getSourceRange().getBegin(),
1178 diag::err_flexible_array_init_nonempty)
1179 << DIE->getSourceRange().getBegin();
1180 SemaRef->Diag(Field->getLocation(), diag::note_flexible_array_member)
1181 << *Field;
1182 Invalid = true;
1183 }
1184
1185 if (Invalid) {
1186 ++Index;
1187 return true;
1188 }
1189
1190 // Initialize the array.
1191 bool prevHadError = hadError;
1192 unsigned newStructuredIndex = FieldIndex;
1193 unsigned OldIndex = Index;
1194 IList->setInit(Index, DIE->getInit());
1195 CheckSubElementType(IList, Field->getType(), Index,
1196 StructuredList, newStructuredIndex);
1197 IList->setInit(OldIndex, DIE);
1198 if (hadError && !prevHadError) {
1199 ++Field;
1200 ++FieldIndex;
1201 if (NextField)
1202 *NextField = Field;
1203 StructuredIndex = FieldIndex;
1204 return true;
1205 }
1206 } else {
1207 // Recurse to check later designated subobjects.
1208 QualType FieldType = (*Field)->getType();
1209 unsigned newStructuredIndex = FieldIndex;
1210 if (CheckDesignatedInitializer(IList, DIE, ++D, FieldType, 0, 0, Index,
1211 StructuredList, newStructuredIndex,
1212 true, false))
1213 return true;
1214 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001215
1216 // Find the position of the next field to be initialized in this
1217 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001218 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001219 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001220
1221 // If this the first designator, our caller will continue checking
1222 // the rest of this struct/class/union subobject.
1223 if (IsFirstDesignator) {
1224 if (NextField)
1225 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001226 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001227 return false;
1228 }
1229
Douglas Gregor34e79462009-01-28 23:36:17 +00001230 if (!FinishSubobjectInit)
1231 return false;
1232
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001233 // Check the remaining fields within this class/struct/union subobject.
1234 bool prevHadError = hadError;
Douglas Gregor4c678342009-01-28 21:54:33 +00001235 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1236 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001237 return hadError && !prevHadError;
1238 }
1239
1240 // C99 6.7.8p6:
1241 //
1242 // If a designator has the form
1243 //
1244 // [ constant-expression ]
1245 //
1246 // then the current object (defined below) shall have array
1247 // type and the expression shall be an integer constant
1248 // expression. If the array is of unknown size, any
1249 // nonnegative value is valid.
1250 //
1251 // Additionally, cope with the GNU extension that permits
1252 // designators of the form
1253 //
1254 // [ constant-expression ... constant-expression ]
1255 const ArrayType *AT = SemaRef->Context.getAsArrayType(CurrentObjectType);
1256 if (!AT) {
1257 SemaRef->Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1258 << CurrentObjectType;
1259 ++Index;
1260 return true;
1261 }
1262
1263 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001264 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1265 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001266 IndexExpr = DIE->getArrayIndex(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001267
1268 bool ConstExpr
1269 = IndexExpr->isIntegerConstantExpr(DesignatedStartIndex, SemaRef->Context);
1270 assert(ConstExpr && "Expression must be constant"); (void)ConstExpr;
1271
1272 DesignatedEndIndex = DesignatedStartIndex;
1273 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001274 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001275
1276 bool StartConstExpr
1277 = DIE->getArrayRangeStart(*D)->isIntegerConstantExpr(DesignatedStartIndex,
1278 SemaRef->Context);
1279 assert(StartConstExpr && "Expression must be constant"); (void)StartConstExpr;
1280
1281 bool EndConstExpr
1282 = DIE->getArrayRangeEnd(*D)->isIntegerConstantExpr(DesignatedEndIndex,
1283 SemaRef->Context);
1284 assert(EndConstExpr && "Expression must be constant"); (void)EndConstExpr;
1285
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001286 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001287
1288 if (DesignatedStartIndex.getZExtValue() != DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001289 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001290 }
1291
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001292 if (isa<ConstantArrayType>(AT)) {
1293 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001294 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1295 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1296 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1297 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1298 if (DesignatedEndIndex >= MaxElements) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001299 SemaRef->Diag(IndexExpr->getSourceRange().getBegin(),
1300 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001301 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001302 << IndexExpr->getSourceRange();
1303 ++Index;
1304 return true;
1305 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001306 } else {
1307 // Make sure the bit-widths and signedness match.
1308 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1309 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
1310 else if (DesignatedStartIndex.getBitWidth() < DesignatedEndIndex.getBitWidth())
1311 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1312 DesignatedStartIndex.setIsUnsigned(true);
1313 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001314 }
1315
Douglas Gregor4c678342009-01-28 21:54:33 +00001316 // Make sure that our non-designated initializer list has space
1317 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001318 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
1319 StructuredList->resizeInits(SemaRef->Context,
1320 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001321
Douglas Gregor34e79462009-01-28 23:36:17 +00001322 // Repeatedly perform subobject initializations in the range
1323 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001324
Douglas Gregor34e79462009-01-28 23:36:17 +00001325 // Move to the next designator
1326 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1327 unsigned OldIndex = Index;
1328 ++D;
1329 while (DesignatedStartIndex <= DesignatedEndIndex) {
1330 // Recurse to check later designated subobjects.
1331 QualType ElementType = AT->getElementType();
1332 Index = OldIndex;
1333 if (CheckDesignatedInitializer(IList, DIE, D, ElementType, 0, 0, Index,
1334 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001335 (DesignatedStartIndex == DesignatedEndIndex),
1336 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001337 return true;
1338
1339 // Move to the next index in the array that we'll be initializing.
1340 ++DesignatedStartIndex;
1341 ElementIndex = DesignatedStartIndex.getZExtValue();
1342 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001343
1344 // If this the first designator, our caller will continue checking
1345 // the rest of this array subobject.
1346 if (IsFirstDesignator) {
1347 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001348 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001349 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001350 return false;
1351 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001352
1353 if (!FinishSubobjectInit)
1354 return false;
1355
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001356 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001357 bool prevHadError = hadError;
Douglas Gregorfdf55692009-02-09 19:45:19 +00001358 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001359 StructuredList, ElementIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001360 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001361}
1362
Douglas Gregor4c678342009-01-28 21:54:33 +00001363// Get the structured initializer list for a subobject of type
1364// @p CurrentObjectType.
1365InitListExpr *
1366InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1367 QualType CurrentObjectType,
1368 InitListExpr *StructuredList,
1369 unsigned StructuredIndex,
1370 SourceRange InitRange) {
1371 Expr *ExistingInit = 0;
1372 if (!StructuredList)
1373 ExistingInit = SyntacticToSemantic[IList];
1374 else if (StructuredIndex < StructuredList->getNumInits())
1375 ExistingInit = StructuredList->getInit(StructuredIndex);
1376
1377 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1378 return Result;
1379
1380 if (ExistingInit) {
1381 // We are creating an initializer list that initializes the
1382 // subobjects of the current object, but there was already an
1383 // initialization that completely initialized the current
1384 // subobject, e.g., by a compound literal:
1385 //
1386 // struct X { int a, b; };
1387 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1388 //
1389 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1390 // designated initializer re-initializes the whole
1391 // subobject [0], overwriting previous initializers.
1392 SemaRef->Diag(InitRange.getBegin(), diag::warn_subobject_initializer_overrides)
1393 << InitRange;
1394 SemaRef->Diag(ExistingInit->getSourceRange().getBegin(),
1395 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001396 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001397 << ExistingInit->getSourceRange();
1398 }
1399
Douglas Gregor87fd7032009-02-02 17:43:21 +00001400 SourceLocation StartLoc;
1401 if (Index < IList->getNumInits())
1402 StartLoc = IList->getInit(Index)->getSourceRange().getBegin();
Douglas Gregor4c678342009-01-28 21:54:33 +00001403 InitListExpr *Result
Douglas Gregor87fd7032009-02-02 17:43:21 +00001404 = new (SemaRef->Context) InitListExpr(StartLoc, 0, 0,
1405 IList->getSourceRange().getEnd());
Douglas Gregor4c678342009-01-28 21:54:33 +00001406 Result->setType(CurrentObjectType);
1407
1408 // Link this new initializer list into the structured initializer
1409 // lists.
1410 if (StructuredList)
1411 StructuredList->updateInit(StructuredIndex, Result);
1412 else {
1413 Result->setSyntacticForm(IList);
1414 SyntacticToSemantic[IList] = Result;
1415 }
1416
1417 return Result;
1418}
1419
1420/// Update the initializer at index @p StructuredIndex within the
1421/// structured initializer list to the value @p expr.
1422void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1423 unsigned &StructuredIndex,
1424 Expr *expr) {
1425 // No structured initializer list to update
1426 if (!StructuredList)
1427 return;
1428
1429 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1430 // This initializer overwrites a previous initializer. Warn.
1431 SemaRef->Diag(expr->getSourceRange().getBegin(),
1432 diag::warn_initializer_overrides)
1433 << expr->getSourceRange();
1434 SemaRef->Diag(PrevInit->getSourceRange().getBegin(),
1435 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001436 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001437 << PrevInit->getSourceRange();
1438 }
1439
1440 ++StructuredIndex;
1441}
1442
Douglas Gregor05c13a32009-01-22 00:58:24 +00001443/// Check that the given Index expression is a valid array designator
1444/// value. This is essentailly just a wrapper around
1445/// Expr::isIntegerConstantExpr that also checks for negative values
1446/// and produces a reasonable diagnostic if there is a
1447/// failure. Returns true if there was an error, false otherwise. If
1448/// everything went okay, Value will receive the value of the constant
1449/// expression.
1450static bool
1451CheckArrayDesignatorExpr(Sema &Self, Expr *Index, llvm::APSInt &Value) {
1452 SourceLocation Loc = Index->getSourceRange().getBegin();
1453
1454 // Make sure this is an integer constant expression.
1455 if (!Index->isIntegerConstantExpr(Value, Self.Context, &Loc))
1456 return Self.Diag(Loc, diag::err_array_designator_nonconstant)
1457 << Index->getSourceRange();
1458
1459 // Make sure this constant expression is non-negative.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001460 llvm::APSInt Zero(llvm::APSInt::getNullValue(Value.getBitWidth()),
1461 Value.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001462 if (Value < Zero)
1463 return Self.Diag(Loc, diag::err_array_designator_negative)
1464 << Value.toString(10) << Index->getSourceRange();
1465
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001466 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001467 return false;
1468}
1469
1470Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1471 SourceLocation Loc,
1472 bool UsedColonSyntax,
1473 OwningExprResult Init) {
1474 typedef DesignatedInitExpr::Designator ASTDesignator;
1475
1476 bool Invalid = false;
1477 llvm::SmallVector<ASTDesignator, 32> Designators;
1478 llvm::SmallVector<Expr *, 32> InitExpressions;
1479
1480 // Build designators and check array designator expressions.
1481 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1482 const Designator &D = Desig.getDesignator(Idx);
1483 switch (D.getKind()) {
1484 case Designator::FieldDesignator:
1485 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1486 D.getFieldLoc()));
1487 break;
1488
1489 case Designator::ArrayDesignator: {
1490 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1491 llvm::APSInt IndexValue;
1492 if (CheckArrayDesignatorExpr(*this, Index, IndexValue))
1493 Invalid = true;
1494 else {
1495 Designators.push_back(ASTDesignator(InitExpressions.size(),
1496 D.getLBracketLoc(),
1497 D.getRBracketLoc()));
1498 InitExpressions.push_back(Index);
1499 }
1500 break;
1501 }
1502
1503 case Designator::ArrayRangeDesignator: {
1504 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1505 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1506 llvm::APSInt StartValue;
1507 llvm::APSInt EndValue;
1508 if (CheckArrayDesignatorExpr(*this, StartIndex, StartValue) ||
1509 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))
1510 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001511 else {
1512 // Make sure we're comparing values with the same bit width.
1513 if (StartValue.getBitWidth() > EndValue.getBitWidth())
1514 EndValue.extend(StartValue.getBitWidth());
1515 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1516 StartValue.extend(EndValue.getBitWidth());
1517
1518 if (EndValue < StartValue) {
1519 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1520 << StartValue.toString(10) << EndValue.toString(10)
1521 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1522 Invalid = true;
1523 } else {
1524 Designators.push_back(ASTDesignator(InitExpressions.size(),
1525 D.getLBracketLoc(),
1526 D.getEllipsisLoc(),
1527 D.getRBracketLoc()));
1528 InitExpressions.push_back(StartIndex);
1529 InitExpressions.push_back(EndIndex);
1530 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001531 }
1532 break;
1533 }
1534 }
1535 }
1536
1537 if (Invalid || Init.isInvalid())
1538 return ExprError();
1539
1540 // Clear out the expressions within the designation.
1541 Desig.ClearExprs(*this);
1542
1543 DesignatedInitExpr *DIE
1544 = DesignatedInitExpr::Create(Context, &Designators[0], Designators.size(),
1545 &InitExpressions[0], InitExpressions.size(),
1546 Loc, UsedColonSyntax,
1547 static_cast<Expr *>(Init.release()));
1548 return Owned(DIE);
1549}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001550
1551bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
1552 InitListChecker CheckInitList(this, InitList, DeclType);
1553 if (!CheckInitList.HadError())
1554 InitList = CheckInitList.getFullyStructuredList();
1555
1556 return CheckInitList.HadError();
1557}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001558
1559/// \brief Diagnose any semantic errors with value-initialization of
1560/// the given type.
1561///
1562/// Value-initialization effectively zero-initializes any types
1563/// without user-declared constructors, and calls the default
1564/// constructor for a for any type that has a user-declared
1565/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1566/// a type with a user-declared constructor does not have an
1567/// accessible, non-deleted default constructor. In C, everything can
1568/// be value-initialized, which corresponds to C's notion of
1569/// initializing objects with static storage duration when no
1570/// initializer is provided for that object.
1571///
1572/// \returns true if there was an error, false otherwise.
1573bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1574 // C++ [dcl.init]p5:
1575 //
1576 // To value-initialize an object of type T means:
1577
1578 // -- if T is an array type, then each element is value-initialized;
1579 if (const ArrayType *AT = Context.getAsArrayType(Type))
1580 return CheckValueInitialization(AT->getElementType(), Loc);
1581
1582 if (const RecordType *RT = Type->getAsRecordType()) {
1583 if (const CXXRecordType *CXXRec = dyn_cast<CXXRecordType>(RT)) {
1584 // -- if T is a class type (clause 9) with a user-declared
1585 // constructor (12.1), then the default constructor for T is
1586 // called (and the initialization is ill-formed if T has no
1587 // accessible default constructor);
1588 if (CXXRec->getDecl()->hasUserDeclaredConstructor())
1589 // FIXME: Eventually, we'll need to put the constructor decl
1590 // into the AST.
1591 return PerformInitializationByConstructor(Type, 0, 0, Loc,
1592 SourceRange(Loc),
1593 DeclarationName(),
1594 IK_Direct);
1595 }
1596 }
1597
1598 if (Type->isReferenceType()) {
1599 // C++ [dcl.init]p5:
1600 // [...] A program that calls for default-initialization or
1601 // value-initialization of an entity of reference type is
1602 // ill-formed. [...]
Douglas Gregord8635172009-02-02 21:35:47 +00001603 // FIXME: Once we have code that goes through this path, add an
1604 // actual diagnostic :)
Douglas Gregor87fd7032009-02-02 17:43:21 +00001605 }
1606
1607 return false;
1608}