blob: 496dbcdefa480a03a357fffe0d7b45df36244d2c [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//
Douglas Gregor9e80f722009-01-29 01:05:33 +000010// This file implements semantic analysis for initializers. The entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
Steve Naroff0cca7492008-05-01 22:18:59 +000013//
14//===----------------------------------------------------------------------===//
15
16#include "Sema.h"
Douglas Gregor05c13a32009-01-22 00:58:24 +000017#include "clang/Parse/Designator.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000020#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000021using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000022
Douglas Gregor9e80f722009-01-29 01:05:33 +000023/// @brief Semantic checking for initializer lists.
24///
25/// The InitListChecker class contains a set of routines that each
26/// handle the initialization of a certain kind of entity, e.g.,
27/// arrays, vectors, struct/union types, scalars, etc. The
28/// InitListChecker itself performs a recursive walk of the subobject
29/// structure of the type to be initialized, while stepping through
30/// the initializer list one element at a time. The IList and Index
31/// parameters to each of the Check* routines contain the active
32/// (syntactic) initializer list and the index into that initializer
33/// list that represents the current initializer. Each routine is
34/// responsible for moving that Index forward as it consumes elements.
35///
36/// Each Check* routine also has a StructuredList/StructuredIndex
37/// arguments, which contains the current the "structured" (semantic)
38/// initializer list and the index into that initializer list where we
39/// are copying initializers as we map them over to the semantic
40/// list. Once we have completed our recursive walk of the subobject
41/// structure, we will have constructed a full semantic initializer
42/// list.
43///
44/// C99 designators cause changes in the initializer list traversal,
45/// because they make the initialization "jump" into a specific
46/// subobject and then continue the initialization from that
47/// point. CheckDesignatedInitializer() recursively steps into the
48/// designated subobject and manages backing out the recursion to
49/// initialize the subobjects after the one designated.
Chris Lattner68355a52009-01-29 05:10:57 +000050namespace clang {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000051class InitListChecker {
52 Sema *SemaRef;
53 bool hadError;
54 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
55 InitListExpr *FullyStructuredList;
56
57 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +000058 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +000059 unsigned &StructuredIndex,
60 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000061 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +000062 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +000063 unsigned &StructuredIndex,
64 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000065 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
66 bool SubobjectIsDesignatorContext,
67 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +000068 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +000069 unsigned &StructuredIndex,
70 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000071 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
72 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +000073 InitListExpr *StructuredList,
74 unsigned &StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +000075 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000076 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +000077 InitListExpr *StructuredList,
78 unsigned &StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +000079 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
80 unsigned &Index,
81 InitListExpr *StructuredList,
82 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000083 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +000084 InitListExpr *StructuredList,
85 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000086 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
87 RecordDecl::field_iterator Field,
88 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +000089 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +000090 unsigned &StructuredIndex,
91 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000092 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
93 llvm::APSInt elementIndex,
94 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +000095 InitListExpr *StructuredList,
96 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000097 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
98 DesignatedInitExpr::designators_iterator D,
99 QualType &CurrentObjectType,
100 RecordDecl::field_iterator *NextField,
101 llvm::APSInt *NextElementIndex,
102 unsigned &Index,
103 InitListExpr *StructuredList,
104 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000105 bool FinishSubobjectInit,
106 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000107 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
108 QualType CurrentObjectType,
109 InitListExpr *StructuredList,
110 unsigned StructuredIndex,
111 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000112 void UpdateStructuredListElement(InitListExpr *StructuredList,
113 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000114 Expr *expr);
115 int numArrayElements(QualType DeclType);
116 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000117
118 void FillInValueInitializations(InitListExpr *ILE);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000119public:
120 InitListChecker(Sema *S, InitListExpr *IL, QualType &T);
121 bool HadError() { return hadError; }
122
123 // @brief Retrieves the fully-structured initializer list used for
124 // semantic analysis and code generation.
125 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
126};
Chris Lattner68355a52009-01-29 05:10:57 +0000127}
128
Douglas Gregor4c678342009-01-28 21:54:33 +0000129/// Recursively replaces NULL values within the given initializer list
130/// with expressions that perform value-initialization of the
131/// appropriate type.
Douglas Gregor930d8b52009-01-30 22:09:00 +0000132void InitListChecker::FillInValueInitializations(InitListExpr *ILE) {
133 assert((ILE->getType() != SemaRef->Context.VoidTy) &&
134 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000135 SourceLocation Loc = ILE->getSourceRange().getBegin();
136 if (ILE->getSyntacticForm())
137 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
138
Douglas Gregor4c678342009-01-28 21:54:33 +0000139 if (const RecordType *RType = ILE->getType()->getAsRecordType()) {
140 unsigned Init = 0, NumInits = ILE->getNumInits();
141 for (RecordDecl::field_iterator Field = RType->getDecl()->field_begin(),
142 FieldEnd = RType->getDecl()->field_end();
143 Field != FieldEnd; ++Field) {
144 if (Field->isUnnamedBitfield())
145 continue;
146
Douglas Gregor87fd7032009-02-02 17:43:21 +0000147 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000148 if (Field->getType()->isReferenceType()) {
149 // C++ [dcl.init.aggr]p9:
150 // If an incomplete or empty initializer-list leaves a
151 // member of reference type uninitialized, the program is
152 // ill-formed.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000153 SemaRef->Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000154 << Field->getType()
155 << ILE->getSyntacticForm()->getSourceRange();
156 SemaRef->Diag(Field->getLocation(),
157 diag::note_uninit_reference_member);
158 hadError = true;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000159 return;
160 } else if (SemaRef->CheckValueInitialization(Field->getType(), Loc)) {
161 hadError = true;
162 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000163 }
Douglas Gregor87fd7032009-02-02 17:43:21 +0000164
165 // FIXME: If value-initialization involves calling a
166 // constructor, should we make that call explicit in the
167 // representation (even when it means extending the
168 // initializer list)?
169 if (Init < NumInits && !hadError)
170 ILE->setInit(Init,
171 new (SemaRef->Context) ImplicitValueInitExpr(Field->getType()));
172 } else if (InitListExpr *InnerILE
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000173 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000174 FillInValueInitializations(InnerILE);
Douglas Gregor4c678342009-01-28 21:54:33 +0000175 ++Init;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000176
177 // Only look at the first initialization of a union.
178 if (RType->getDecl()->isUnion())
179 break;
Douglas Gregor4c678342009-01-28 21:54:33 +0000180 }
181
182 return;
183 }
184
185 QualType ElementType;
186
Douglas Gregor87fd7032009-02-02 17:43:21 +0000187 unsigned NumInits = ILE->getNumInits();
188 unsigned NumElements = NumInits;
189 if (const ArrayType *AType = SemaRef->Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000190 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000191 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
192 NumElements = CAType->getSize().getZExtValue();
193 } else if (const VectorType *VType = ILE->getType()->getAsVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000194 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000195 NumElements = VType->getNumElements();
196 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000197 ElementType = ILE->getType();
198
Douglas Gregor87fd7032009-02-02 17:43:21 +0000199 for (unsigned Init = 0; Init != NumElements; ++Init) {
200 if (Init >= NumInits || !ILE->getInit(Init)) {
201 if (SemaRef->CheckValueInitialization(ElementType, Loc)) {
202 hadError = true;
203 return;
204 }
205
206 // FIXME: If value-initialization involves calling a
207 // constructor, should we make that call explicit in the
208 // representation (even when it means extending the
209 // initializer list)?
210 if (Init < NumInits && !hadError)
211 ILE->setInit(Init,
212 new (SemaRef->Context) ImplicitValueInitExpr(ElementType));
213 }
Chris Lattner68355a52009-01-29 05:10:57 +0000214 else if (InitListExpr *InnerILE =dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000215 FillInValueInitializations(InnerILE);
Douglas Gregor4c678342009-01-28 21:54:33 +0000216 }
217}
218
Chris Lattner68355a52009-01-29 05:10:57 +0000219
Steve Naroff0cca7492008-05-01 22:18:59 +0000220InitListChecker::InitListChecker(Sema *S, InitListExpr *IL, QualType &T) {
221 hadError = false;
222 SemaRef = S;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000223
Eli Friedmanb85f7072008-05-19 19:16:24 +0000224 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000225 unsigned newStructuredIndex = 0;
226 FullyStructuredList
227 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, SourceRange());
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000228 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
229 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000230
Douglas Gregor930d8b52009-01-30 22:09:00 +0000231 if (!hadError)
232 FillInValueInitializations(FullyStructuredList);
Steve Naroff0cca7492008-05-01 22:18:59 +0000233}
234
235int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000236 // FIXME: use a proper constant
237 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000238 if (const ConstantArrayType *CAT =
239 SemaRef->Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000240 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
241 }
242 return maxElements;
243}
244
245int InitListChecker::numStructUnionElements(QualType DeclType) {
246 RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000247 int InitializableMembers = 0;
248 for (RecordDecl::field_iterator Field = structDecl->field_begin(),
249 FieldEnd = structDecl->field_end();
250 Field != FieldEnd; ++Field) {
251 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
252 ++InitializableMembers;
253 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000254 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000255 return std::min(InitializableMembers, 1);
256 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000257}
258
259void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000260 QualType T, unsigned &Index,
261 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000262 unsigned &StructuredIndex,
263 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000264 int maxElements = 0;
265
266 if (T->isArrayType())
267 maxElements = numArrayElements(T);
268 else if (T->isStructureType() || T->isUnionType())
269 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000270 else if (T->isVectorType())
271 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000272 else
273 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000274
Eli Friedman402256f2008-05-25 13:49:22 +0000275 if (maxElements == 0) {
276 SemaRef->Diag(ParentIList->getInit(Index)->getLocStart(),
277 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000278 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000279 hadError = true;
280 return;
281 }
282
Douglas Gregor4c678342009-01-28 21:54:33 +0000283 // Build a structured initializer list corresponding to this subobject.
284 InitListExpr *StructuredSubobjectInitList
285 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
286 StructuredIndex,
287 ParentIList->getInit(Index)->getSourceRange());
288 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000289
Douglas Gregor4c678342009-01-28 21:54:33 +0000290 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000291 unsigned StartIndex = Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000292 CheckListElementTypes(ParentIList, T, false, Index,
293 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000294 StructuredSubobjectInitIndex,
295 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000296 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
297
298 // Update the structured sub-object initialize so that it's ending
299 // range corresponds with the end of the last initializer it used.
300 if (EndIndex < ParentIList->getNumInits()) {
301 SourceLocation EndLoc
302 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
303 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
304 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000305}
306
Steve Naroffa647caa2008-05-06 00:23:44 +0000307void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000308 unsigned &Index,
309 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000310 unsigned &StructuredIndex,
311 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000312 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000313 SyntacticToSemantic[IList] = StructuredList;
314 StructuredList->setSyntacticForm(IList);
315 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000316 StructuredIndex, TopLevelObject);
Steve Naroffa647caa2008-05-06 00:23:44 +0000317 IList->setType(T);
Douglas Gregor4c678342009-01-28 21:54:33 +0000318 StructuredList->setType(T);
Eli Friedman638e1442008-05-25 13:22:35 +0000319 if (hadError)
320 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000321
Eli Friedman638e1442008-05-25 13:22:35 +0000322 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000323 // We have leftover initializers
324 if (IList->getNumInits() > 0 &&
325 SemaRef->IsStringLiteralInit(IList->getInit(Index), T)) {
Eli Friedmanbb504d32008-05-19 20:12:18 +0000326 // Special-case
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000327 SemaRef->Diag(IList->getInit(Index)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000328 diag::err_excess_initializers_in_char_array_initializer)
329 << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000330 hadError = true;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000331 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000332 // Don't complain for incomplete types, since we'll get an error
333 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000334 QualType CurrentObjectType = StructuredList->getType();
335 int initKind =
336 CurrentObjectType->isArrayType()? 0 :
337 CurrentObjectType->isVectorType()? 1 :
338 CurrentObjectType->isScalarType()? 2 :
339 CurrentObjectType->isUnionType()? 3 :
340 4;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000341 SemaRef->Diag(IList->getInit(Index)->getLocStart(),
Douglas Gregorb574e562009-01-30 22:26:29 +0000342 diag::err_excess_initializers)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000343 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000344 }
345 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000346
Eli Friedman638e1442008-05-25 13:22:35 +0000347 if (T->isScalarType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000348 SemaRef->Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
349 << IList->getSourceRange();
Steve Naroff0cca7492008-05-01 22:18:59 +0000350}
351
Eli Friedmanb85f7072008-05-19 19:16:24 +0000352void InitListChecker::CheckListElementTypes(InitListExpr *IList,
353 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000354 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000355 unsigned &Index,
356 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000357 unsigned &StructuredIndex,
358 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000359 if (DeclType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000360 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000361 } else if (DeclType->isVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000362 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000363 } else if (DeclType->isAggregateType()) {
364 if (DeclType->isRecordType()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000365 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
366 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000367 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000368 StructuredList, StructuredIndex,
369 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000370 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000371 llvm::APSInt Zero(
372 SemaRef->Context.getTypeSize(SemaRef->Context.getSizeType()),
373 false);
Douglas Gregor4c678342009-01-28 21:54:33 +0000374 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
375 StructuredList, StructuredIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000376 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000377 else
Douglas Gregor4c678342009-01-28 21:54:33 +0000378 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000379 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
380 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000381 ++Index;
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000382 SemaRef->Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000383 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000384 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000385 } else if (DeclType->isRecordType()) {
386 // C++ [dcl.init]p14:
387 // [...] If the class is an aggregate (8.5.1), and the initializer
388 // is a brace-enclosed list, see 8.5.1.
389 //
390 // Note: 8.5.1 is handled below; here, we diagnose the case where
391 // we have an initializer list and a destination type that is not
392 // an aggregate.
393 // FIXME: In C++0x, this is yet another form of initialization.
394 SemaRef->Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
395 << DeclType << IList->getSourceRange();
396 hadError = true;
397 } else if (DeclType->isReferenceType()) {
398 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000399 } else {
400 // In C, all types are either scalars or aggregates, but
401 // additional handling is needed here for C++ (and possibly others?).
402 assert(0 && "Unsupported initializer type");
403 }
404}
405
Eli Friedmanb85f7072008-05-19 19:16:24 +0000406void InitListChecker::CheckSubElementType(InitListExpr *IList,
407 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000408 unsigned &Index,
409 InitListExpr *StructuredList,
410 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000411 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000412 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
413 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000414 unsigned newStructuredIndex = 0;
415 InitListExpr *newStructuredList
416 = getStructuredSubobjectInit(IList, Index, ElemType,
417 StructuredList, StructuredIndex,
418 SubInitList->getSourceRange());
419 CheckExplicitInitList(SubInitList, ElemType, newIndex,
420 newStructuredList, newStructuredIndex);
421 ++StructuredIndex;
422 ++Index;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000423 } else if (StringLiteral *lit =
424 SemaRef->IsStringLiteralInit(expr, ElemType)) {
425 SemaRef->CheckStringLiteralInit(lit, ElemType);
Douglas Gregor4c678342009-01-28 21:54:33 +0000426 UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
427 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000428 } else if (ElemType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000429 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000430 } else if (ElemType->isReferenceType()) {
431 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000432 } else {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000433 if (SemaRef->getLangOptions().CPlusPlus) {
434 // C++ [dcl.init.aggr]p12:
435 // All implicit type conversions (clause 4) are considered when
436 // initializing the aggregate member with an ini- tializer from
437 // an initializer-list. If the initializer can initialize a
438 // member, the member is initialized. [...]
439 ImplicitConversionSequence ICS
440 = SemaRef->TryCopyInitialization(expr, ElemType);
441 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
442 if (SemaRef->PerformImplicitConversion(expr, ElemType, ICS,
443 "initializing"))
444 hadError = true;
445 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
446 ++Index;
447 return;
448 }
449
450 // Fall through for subaggregate initialization
451 } else {
452 // C99 6.7.8p13:
453 //
454 // The initializer for a structure or union object that has
455 // automatic storage duration shall be either an initializer
456 // list as described below, or a single expression that has
457 // compatible structure or union type. In the latter case, the
458 // initial value of the object, including unnamed members, is
459 // that of the expression.
460 QualType ExprType = SemaRef->Context.getCanonicalType(expr->getType());
461 QualType ElemTypeCanon = SemaRef->Context.getCanonicalType(ElemType);
462 if (SemaRef->Context.typesAreCompatible(ExprType.getUnqualifiedType(),
463 ElemTypeCanon.getUnqualifiedType())) {
464 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
465 ++Index;
466 return;
467 }
468
469 // Fall through for subaggregate initialization
470 }
471
472 // C++ [dcl.init.aggr]p12:
473 //
474 // [...] Otherwise, if the member is itself a non-empty
475 // subaggregate, brace elision is assumed and the initializer is
476 // considered for the initialization of the first member of
477 // the subaggregate.
478 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
479 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
480 StructuredIndex);
481 ++StructuredIndex;
482 } else {
483 // We cannot initialize this element, so let
484 // PerformCopyInitialization produce the appropriate diagnostic.
485 SemaRef->PerformCopyInitialization(expr, ElemType, "initializing");
486 hadError = true;
487 ++Index;
488 ++StructuredIndex;
489 }
490 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000491}
492
Douglas Gregor930d8b52009-01-30 22:09:00 +0000493void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000494 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000495 InitListExpr *StructuredList,
496 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000497 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000498 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000499 if (isa<InitListExpr>(expr)) {
Eli Friedmanbb504d32008-05-19 20:12:18 +0000500 SemaRef->Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000501 diag::err_many_braces_around_scalar_init)
502 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000503 hadError = true;
504 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000505 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000506 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000507 } else if (isa<DesignatedInitExpr>(expr)) {
508 SemaRef->Diag(expr->getSourceRange().getBegin(),
509 diag::err_designator_for_scalar_init)
510 << DeclType << expr->getSourceRange();
511 hadError = true;
512 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000513 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000514 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000515 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000516
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000517 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000518 if (SemaRef->CheckSingleInitializer(expr, DeclType, false))
Eli Friedmanbb504d32008-05-19 20:12:18 +0000519 hadError = true; // types weren't compatible.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000520 else if (savExpr != expr) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000521 // The type was promoted, update initializer list.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000522 IList->setInit(Index, expr);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000523 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000524 if (hadError)
525 ++StructuredIndex;
526 else
527 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000528 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000529 } else {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000530 SemaRef->Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
531 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000532 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000533 ++Index;
534 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000535 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000536 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000537}
538
Douglas Gregor930d8b52009-01-30 22:09:00 +0000539void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
540 unsigned &Index,
541 InitListExpr *StructuredList,
542 unsigned &StructuredIndex) {
543 if (Index < IList->getNumInits()) {
544 Expr *expr = IList->getInit(Index);
545 if (isa<InitListExpr>(expr)) {
546 SemaRef->Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
547 << DeclType << IList->getSourceRange();
548 hadError = true;
549 ++Index;
550 ++StructuredIndex;
551 return;
552 }
553
554 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
555 if (SemaRef->CheckReferenceInit(expr, DeclType))
556 hadError = true;
557 else if (savExpr != expr) {
558 // The type was promoted, update initializer list.
559 IList->setInit(Index, expr);
560 }
561 if (hadError)
562 ++StructuredIndex;
563 else
564 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
565 ++Index;
566 } else {
567 // FIXME: It would be wonderful if we could point at the actual
568 // member. In general, it would be useful to pass location
569 // information down the stack, so that we know the location (or
570 // decl) of the "current object" being initialized.
571 SemaRef->Diag(IList->getLocStart(),
572 diag::err_init_reference_member_uninitialized)
573 << DeclType
574 << IList->getSourceRange();
575 hadError = true;
576 ++Index;
577 ++StructuredIndex;
578 return;
579 }
580}
581
Steve Naroff0cca7492008-05-01 22:18:59 +0000582void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000583 unsigned &Index,
584 InitListExpr *StructuredList,
585 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000586 if (Index < IList->getNumInits()) {
587 const VectorType *VT = DeclType->getAsVectorType();
588 int maxElements = VT->getNumElements();
589 QualType elementType = VT->getElementType();
590
591 for (int i = 0; i < maxElements; ++i) {
592 // Don't attempt to go past the end of the init list
593 if (Index >= IList->getNumInits())
594 break;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000595 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000596 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000597 }
598 }
599}
600
601void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000602 llvm::APSInt elementIndex,
603 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000604 unsigned &Index,
605 InitListExpr *StructuredList,
606 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000607 // Check for the special-case of initializing an array with a string.
608 if (Index < IList->getNumInits()) {
609 if (StringLiteral *lit =
610 SemaRef->IsStringLiteralInit(IList->getInit(Index), DeclType)) {
611 SemaRef->CheckStringLiteralInit(lit, DeclType);
Douglas Gregor4c678342009-01-28 21:54:33 +0000612 // We place the string literal directly into the resulting
613 // initializer list. This is the only place where the structure
614 // of the structured initializer list doesn't match exactly,
615 // because doing so would involve allocating one character
616 // constant for each string.
617 UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
618 StructuredList->resizeInits(SemaRef->Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000619 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000620 return;
621 }
622 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000623 if (const VariableArrayType *VAT =
624 SemaRef->Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000625 // Check for VLAs; in standard C it would be possible to check this
626 // earlier, but I don't know where clang accepts VLAs (gcc accepts
627 // them in all sorts of strange places).
628 SemaRef->Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000629 diag::err_variable_object_no_init)
630 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000631 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000632 ++Index;
633 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000634 return;
635 }
636
Douglas Gregor05c13a32009-01-22 00:58:24 +0000637 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000638 llvm::APSInt maxElements(elementIndex.getBitWidth(),
639 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000640 bool maxElementsKnown = false;
641 if (const ConstantArrayType *CAT =
642 SemaRef->Context.getAsConstantArrayType(DeclType)) {
643 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000644 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000645 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000646 maxElementsKnown = true;
647 }
648
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000649 QualType elementType = SemaRef->Context.getAsArrayType(DeclType)
650 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000651 while (Index < IList->getNumInits()) {
652 Expr *Init = IList->getInit(Index);
653 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000654 // If we're not the subobject that matches up with the '{' for
655 // the designator, we shouldn't be handling the
656 // designator. Return immediately.
657 if (!SubobjectIsDesignatorContext)
658 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000659
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000660 // Handle this designated initializer. elementIndex will be
661 // updated to be the next array element we'll initialize.
662 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000663 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000664 StructuredList, StructuredIndex, true,
665 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000666 hadError = true;
667 continue;
668 }
669
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000670 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
671 maxElements.extend(elementIndex.getBitWidth());
672 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
673 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000674 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000675
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000676 // If the array is of incomplete type, keep track of the number of
677 // elements in the initializer.
678 if (!maxElementsKnown && elementIndex > maxElements)
679 maxElements = elementIndex;
680
Douglas Gregor05c13a32009-01-22 00:58:24 +0000681 continue;
682 }
683
684 // If we know the maximum number of elements, and we've already
685 // hit it, stop consuming elements in the initializer list.
686 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +0000687 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000688
689 // Check this element.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000690 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000691 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000692 ++elementIndex;
693
694 // If the array is of incomplete type, keep track of the number of
695 // elements in the initializer.
696 if (!maxElementsKnown && elementIndex > maxElements)
697 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +0000698 }
699 if (DeclType->isIncompleteArrayType()) {
700 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000701 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000702 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000703 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000704 // Sizing an array implicitly to zero is not allowed by ISO C,
705 // but is supported by GNU.
Steve Naroff0cca7492008-05-01 22:18:59 +0000706 SemaRef->Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000707 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +0000708 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000709
Douglas Gregor05c13a32009-01-22 00:58:24 +0000710 DeclType = SemaRef->Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000711 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +0000712 }
713}
714
715void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
716 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000717 RecordDecl::field_iterator Field,
718 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000719 unsigned &Index,
720 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000721 unsigned &StructuredIndex,
722 bool TopLevelObject) {
Eli Friedmanb85f7072008-05-19 19:16:24 +0000723 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroff0cca7492008-05-01 22:18:59 +0000724
Eli Friedmanb85f7072008-05-19 19:16:24 +0000725 // If the record is invalid, some of it's members are invalid. To avoid
726 // confusion, we forgo checking the intializer for the entire record.
727 if (structDecl->isInvalidDecl()) {
728 hadError = true;
729 return;
730 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000731
732 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
733 // Value-initialize the first named member of the union.
734 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
735 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
736 Field != FieldEnd; ++Field) {
737 if (Field->getDeclName()) {
738 StructuredList->setInitializedFieldInUnion(*Field);
739 break;
740 }
741 }
742 return;
743 }
744
745
746
Douglas Gregor05c13a32009-01-22 00:58:24 +0000747 // If structDecl is a forward declaration, this loop won't do
748 // anything except look at designated initializers; That's okay,
749 // because an error should get printed out elsewhere. It might be
750 // worthwhile to skip over the rest of the initializer, though.
Douglas Gregor44b43212008-12-11 16:49:14 +0000751 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000752 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000753 while (Index < IList->getNumInits()) {
754 Expr *Init = IList->getInit(Index);
755
756 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000757 // If we're not the subobject that matches up with the '{' for
758 // the designator, we shouldn't be handling the
759 // designator. Return immediately.
760 if (!SubobjectIsDesignatorContext)
761 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000762
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000763 // Handle this designated initializer. Field will be updated to
764 // the next field that we'll be initializing.
765 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000766 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000767 StructuredList, StructuredIndex,
768 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000769 hadError = true;
770
Douglas Gregor0bb76892009-01-29 16:53:55 +0000771 // Abort early for unions: the designator handled the
772 // initialization of the appropriate field.
773 if (DeclType->isUnionType())
774 break;
775
Douglas Gregor05c13a32009-01-22 00:58:24 +0000776 continue;
777 }
778
779 if (Field == FieldEnd) {
780 // We've run out of fields. We're done.
781 break;
782 }
783
Douglas Gregor44b43212008-12-11 16:49:14 +0000784 // If we've hit the flexible array member at the end, we're done.
785 if (Field->getType()->isIncompleteArrayType())
786 break;
787
Douglas Gregor0bb76892009-01-29 16:53:55 +0000788 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000789 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +0000790 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000791 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +0000792 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000793
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000794 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000795 StructuredList, StructuredIndex);
Douglas Gregor0bb76892009-01-29 16:53:55 +0000796
797 if (DeclType->isUnionType()) {
798 // Initialize the first field within the union.
799 StructuredList->setInitializedFieldInUnion(*Field);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000800 break;
Douglas Gregor0bb76892009-01-29 16:53:55 +0000801 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000802
803 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +0000804 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000805
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000806 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
807 Index >= IList->getNumInits() ||
808 !isa<InitListExpr>(IList->getInit(Index)))
809 return;
810
811 // Handle GNU flexible array initializers.
812 if (!TopLevelObject &&
813 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0) {
814 SemaRef->Diag(IList->getInit(Index)->getSourceRange().getBegin(),
815 diag::err_flexible_array_init_nonempty)
816 << IList->getInit(Index)->getSourceRange().getBegin();
817 SemaRef->Diag(Field->getLocation(), diag::note_flexible_array_member)
818 << *Field;
819 hadError = true;
820 }
821
822 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
823 StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000824}
Steve Naroff0cca7492008-05-01 22:18:59 +0000825
Douglas Gregor05c13a32009-01-22 00:58:24 +0000826/// @brief Check the well-formedness of a C99 designated initializer.
827///
828/// Determines whether the designated initializer @p DIE, which
829/// resides at the given @p Index within the initializer list @p
830/// IList, is well-formed for a current object of type @p DeclType
831/// (C99 6.7.8). The actual subobject that this designator refers to
832/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +0000833/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +0000834///
835/// @param IList The initializer list in which this designated
836/// initializer occurs.
837///
838/// @param DIE The designated initializer and its initialization
839/// expression.
840///
841/// @param DeclType The type of the "current object" (C99 6.7.8p17),
842/// into which the designation in @p DIE should refer.
843///
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000844/// @param NextField If non-NULL and the first designator in @p DIE is
845/// a field, this will be set to the field declaration corresponding
846/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000847///
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000848/// @param NextElementIndex If non-NULL and the first designator in @p
849/// DIE is an array designator or GNU array-range designator, this
850/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000851///
852/// @param Index Index into @p IList where the designated initializer
853/// @p DIE occurs.
854///
Douglas Gregor4c678342009-01-28 21:54:33 +0000855/// @param StructuredList The initializer list expression that
856/// describes all of the subobject initializers in the order they'll
857/// actually be initialized.
858///
Douglas Gregor05c13a32009-01-22 00:58:24 +0000859/// @returns true if there was an error, false otherwise.
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000860bool
861InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
862 DesignatedInitExpr *DIE,
863 DesignatedInitExpr::designators_iterator D,
864 QualType &CurrentObjectType,
865 RecordDecl::field_iterator *NextField,
866 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000867 unsigned &Index,
868 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +0000869 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000870 bool FinishSubobjectInit,
871 bool TopLevelObject) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000872 if (D == DIE->designators_end()) {
873 // Check the actual initialization for the designated object type.
874 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000875
876 // Temporarily remove the designator expression from the
877 // initializer list that the child calls see, so that we don't try
878 // to re-process the designator.
879 unsigned OldIndex = Index;
880 IList->setInit(OldIndex, DIE->getInit());
881
882 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000883 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000884
885 // Restore the designated initializer expression in the syntactic
886 // form of the initializer list.
887 if (IList->getInit(OldIndex) != DIE->getInit())
888 DIE->setInit(IList->getInit(OldIndex));
889 IList->setInit(OldIndex, DIE);
890
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000891 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000892 }
893
Douglas Gregor4c678342009-01-28 21:54:33 +0000894 bool IsFirstDesignator = (D == DIE->designators_begin());
895 assert((IsFirstDesignator || StructuredList) &&
896 "Need a non-designated initializer list to start from");
897
898 // Determine the structural initializer list that corresponds to the
899 // current subobject.
900 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
901 : getStructuredSubobjectInit(IList, Index, CurrentObjectType, StructuredList,
902 StructuredIndex,
903 SourceRange(D->getStartLocation(),
904 DIE->getSourceRange().getEnd()));
905 assert(StructuredList && "Expected a structured initializer list");
906
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000907 if (D->isFieldDesignator()) {
908 // C99 6.7.8p7:
909 //
910 // If a designator has the form
911 //
912 // . identifier
913 //
914 // then the current object (defined below) shall have
915 // structure or union type and the identifier shall be the
916 // name of a member of that type.
917 const RecordType *RT = CurrentObjectType->getAsRecordType();
918 if (!RT) {
919 SourceLocation Loc = D->getDotLoc();
920 if (Loc.isInvalid())
921 Loc = D->getFieldLoc();
922 SemaRef->Diag(Loc, diag::err_field_designator_non_aggr)
923 << SemaRef->getLangOptions().CPlusPlus << CurrentObjectType;
924 ++Index;
925 return true;
926 }
927
Douglas Gregor4c678342009-01-28 21:54:33 +0000928 // Note: we perform a linear search of the fields here, despite
929 // the fact that we have a faster lookup method, because we always
930 // need to compute the field's index.
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000931 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +0000932 unsigned FieldIndex = 0;
933 RecordDecl::field_iterator Field = RT->getDecl()->field_begin(),
934 FieldEnd = RT->getDecl()->field_end();
935 for (; Field != FieldEnd; ++Field) {
936 if (Field->isUnnamedBitfield())
937 continue;
938
939 if (Field->getIdentifier() == FieldName)
940 break;
941
942 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000943 }
944
Douglas Gregor4c678342009-01-28 21:54:33 +0000945 if (Field == FieldEnd) {
946 // We did not find the field we're looking for. Produce a
947 // suitable diagnostic and return a failure.
948 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
949 if (Lookup.first == Lookup.second) {
950 // Name lookup didn't find anything.
951 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
952 << FieldName << CurrentObjectType;
953 } else {
954 // Name lookup found something, but it wasn't a field.
955 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
956 << FieldName;
957 SemaRef->Diag((*Lookup.first)->getLocation(),
958 diag::note_field_designator_found);
959 }
960
961 ++Index;
962 return true;
963 } else if (cast<RecordDecl>((*Field)->getDeclContext())
964 ->isAnonymousStructOrUnion()) {
965 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_anon_class)
966 << FieldName
967 << (cast<RecordDecl>((*Field)->getDeclContext())->isUnion()? 2 :
968 (int)SemaRef->getLangOptions().CPlusPlus);
969 SemaRef->Diag((*Field)->getLocation(), diag::note_field_designator_found);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000970 ++Index;
971 return true;
972 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000973
974 // All of the fields of a union are located at the same place in
975 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +0000976 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000977 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +0000978 StructuredList->setInitializedFieldInUnion(*Field);
979 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000980
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000981 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +0000982 D->setField(*Field);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000983
Douglas Gregor4c678342009-01-28 21:54:33 +0000984 // Make sure that our non-designated initializer list has space
985 // for a subobject corresponding to this field.
986 if (FieldIndex >= StructuredList->getNumInits())
987 StructuredList->resizeInits(SemaRef->Context, FieldIndex + 1);
988
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000989 // This designator names a flexible array member.
990 if (Field->getType()->isIncompleteArrayType()) {
991 bool Invalid = false;
992 DesignatedInitExpr::designators_iterator NextD = D;
993 ++NextD;
994 if (NextD != DIE->designators_end()) {
995 // We can't designate an object within the flexible array
996 // member (because GCC doesn't allow it).
997 SemaRef->Diag(NextD->getStartLocation(),
998 diag::err_designator_into_flexible_array_member)
999 << SourceRange(NextD->getStartLocation(),
1000 DIE->getSourceRange().getEnd());
1001 SemaRef->Diag(Field->getLocation(), diag::note_flexible_array_member)
1002 << *Field;
1003 Invalid = true;
1004 }
1005
1006 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1007 // The initializer is not an initializer list.
1008 SemaRef->Diag(DIE->getInit()->getSourceRange().getBegin(),
1009 diag::err_flexible_array_init_needs_braces)
1010 << DIE->getInit()->getSourceRange();
1011 SemaRef->Diag(Field->getLocation(), diag::note_flexible_array_member)
1012 << *Field;
1013 Invalid = true;
1014 }
1015
1016 // Handle GNU flexible array initializers.
1017 if (!Invalid && !TopLevelObject &&
1018 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
1019 SemaRef->Diag(DIE->getSourceRange().getBegin(),
1020 diag::err_flexible_array_init_nonempty)
1021 << DIE->getSourceRange().getBegin();
1022 SemaRef->Diag(Field->getLocation(), diag::note_flexible_array_member)
1023 << *Field;
1024 Invalid = true;
1025 }
1026
1027 if (Invalid) {
1028 ++Index;
1029 return true;
1030 }
1031
1032 // Initialize the array.
1033 bool prevHadError = hadError;
1034 unsigned newStructuredIndex = FieldIndex;
1035 unsigned OldIndex = Index;
1036 IList->setInit(Index, DIE->getInit());
1037 CheckSubElementType(IList, Field->getType(), Index,
1038 StructuredList, newStructuredIndex);
1039 IList->setInit(OldIndex, DIE);
1040 if (hadError && !prevHadError) {
1041 ++Field;
1042 ++FieldIndex;
1043 if (NextField)
1044 *NextField = Field;
1045 StructuredIndex = FieldIndex;
1046 return true;
1047 }
1048 } else {
1049 // Recurse to check later designated subobjects.
1050 QualType FieldType = (*Field)->getType();
1051 unsigned newStructuredIndex = FieldIndex;
1052 if (CheckDesignatedInitializer(IList, DIE, ++D, FieldType, 0, 0, Index,
1053 StructuredList, newStructuredIndex,
1054 true, false))
1055 return true;
1056 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001057
1058 // Find the position of the next field to be initialized in this
1059 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001060 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001061 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001062
1063 // If this the first designator, our caller will continue checking
1064 // the rest of this struct/class/union subobject.
1065 if (IsFirstDesignator) {
1066 if (NextField)
1067 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001068 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001069 return false;
1070 }
1071
Douglas Gregor34e79462009-01-28 23:36:17 +00001072 if (!FinishSubobjectInit)
1073 return false;
1074
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001075 // Check the remaining fields within this class/struct/union subobject.
1076 bool prevHadError = hadError;
Douglas Gregor4c678342009-01-28 21:54:33 +00001077 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1078 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001079 return hadError && !prevHadError;
1080 }
1081
1082 // C99 6.7.8p6:
1083 //
1084 // If a designator has the form
1085 //
1086 // [ constant-expression ]
1087 //
1088 // then the current object (defined below) shall have array
1089 // type and the expression shall be an integer constant
1090 // expression. If the array is of unknown size, any
1091 // nonnegative value is valid.
1092 //
1093 // Additionally, cope with the GNU extension that permits
1094 // designators of the form
1095 //
1096 // [ constant-expression ... constant-expression ]
1097 const ArrayType *AT = SemaRef->Context.getAsArrayType(CurrentObjectType);
1098 if (!AT) {
1099 SemaRef->Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1100 << CurrentObjectType;
1101 ++Index;
1102 return true;
1103 }
1104
1105 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001106 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1107 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001108 IndexExpr = DIE->getArrayIndex(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001109
1110 bool ConstExpr
1111 = IndexExpr->isIntegerConstantExpr(DesignatedStartIndex, SemaRef->Context);
1112 assert(ConstExpr && "Expression must be constant"); (void)ConstExpr;
1113
1114 DesignatedEndIndex = DesignatedStartIndex;
1115 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001116 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001117
1118 bool StartConstExpr
1119 = DIE->getArrayRangeStart(*D)->isIntegerConstantExpr(DesignatedStartIndex,
1120 SemaRef->Context);
1121 assert(StartConstExpr && "Expression must be constant"); (void)StartConstExpr;
1122
1123 bool EndConstExpr
1124 = DIE->getArrayRangeEnd(*D)->isIntegerConstantExpr(DesignatedEndIndex,
1125 SemaRef->Context);
1126 assert(EndConstExpr && "Expression must be constant"); (void)EndConstExpr;
1127
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001128 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001129
1130 if (DesignatedStartIndex.getZExtValue() != DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001131 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001132 }
1133
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001134 if (isa<ConstantArrayType>(AT)) {
1135 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001136 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1137 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1138 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1139 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1140 if (DesignatedEndIndex >= MaxElements) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001141 SemaRef->Diag(IndexExpr->getSourceRange().getBegin(),
1142 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001143 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001144 << IndexExpr->getSourceRange();
1145 ++Index;
1146 return true;
1147 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001148 } else {
1149 // Make sure the bit-widths and signedness match.
1150 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1151 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
1152 else if (DesignatedStartIndex.getBitWidth() < DesignatedEndIndex.getBitWidth())
1153 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1154 DesignatedStartIndex.setIsUnsigned(true);
1155 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001156 }
1157
Douglas Gregor4c678342009-01-28 21:54:33 +00001158 // Make sure that our non-designated initializer list has space
1159 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001160 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
1161 StructuredList->resizeInits(SemaRef->Context,
1162 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001163
Douglas Gregor34e79462009-01-28 23:36:17 +00001164 // Repeatedly perform subobject initializations in the range
1165 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001166
Douglas Gregor34e79462009-01-28 23:36:17 +00001167 // Move to the next designator
1168 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1169 unsigned OldIndex = Index;
1170 ++D;
1171 while (DesignatedStartIndex <= DesignatedEndIndex) {
1172 // Recurse to check later designated subobjects.
1173 QualType ElementType = AT->getElementType();
1174 Index = OldIndex;
1175 if (CheckDesignatedInitializer(IList, DIE, D, ElementType, 0, 0, Index,
1176 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001177 (DesignatedStartIndex == DesignatedEndIndex),
1178 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001179 return true;
1180
1181 // Move to the next index in the array that we'll be initializing.
1182 ++DesignatedStartIndex;
1183 ElementIndex = DesignatedStartIndex.getZExtValue();
1184 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001185
1186 // If this the first designator, our caller will continue checking
1187 // the rest of this array subobject.
1188 if (IsFirstDesignator) {
1189 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001190 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001191 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001192 return false;
1193 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001194
1195 if (!FinishSubobjectInit)
1196 return false;
1197
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001198 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001199 bool prevHadError = hadError;
Douglas Gregor34e79462009-01-28 23:36:17 +00001200 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, true, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001201 StructuredList, ElementIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001202 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001203}
1204
Douglas Gregor4c678342009-01-28 21:54:33 +00001205// Get the structured initializer list for a subobject of type
1206// @p CurrentObjectType.
1207InitListExpr *
1208InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1209 QualType CurrentObjectType,
1210 InitListExpr *StructuredList,
1211 unsigned StructuredIndex,
1212 SourceRange InitRange) {
1213 Expr *ExistingInit = 0;
1214 if (!StructuredList)
1215 ExistingInit = SyntacticToSemantic[IList];
1216 else if (StructuredIndex < StructuredList->getNumInits())
1217 ExistingInit = StructuredList->getInit(StructuredIndex);
1218
1219 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1220 return Result;
1221
1222 if (ExistingInit) {
1223 // We are creating an initializer list that initializes the
1224 // subobjects of the current object, but there was already an
1225 // initialization that completely initialized the current
1226 // subobject, e.g., by a compound literal:
1227 //
1228 // struct X { int a, b; };
1229 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1230 //
1231 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1232 // designated initializer re-initializes the whole
1233 // subobject [0], overwriting previous initializers.
1234 SemaRef->Diag(InitRange.getBegin(), diag::warn_subobject_initializer_overrides)
1235 << InitRange;
1236 SemaRef->Diag(ExistingInit->getSourceRange().getBegin(),
1237 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001238 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001239 << ExistingInit->getSourceRange();
1240 }
1241
Douglas Gregor87fd7032009-02-02 17:43:21 +00001242 SourceLocation StartLoc;
1243 if (Index < IList->getNumInits())
1244 StartLoc = IList->getInit(Index)->getSourceRange().getBegin();
Douglas Gregor4c678342009-01-28 21:54:33 +00001245 InitListExpr *Result
Douglas Gregor87fd7032009-02-02 17:43:21 +00001246 = new (SemaRef->Context) InitListExpr(StartLoc, 0, 0,
1247 IList->getSourceRange().getEnd());
Douglas Gregor4c678342009-01-28 21:54:33 +00001248 Result->setType(CurrentObjectType);
1249
1250 // Link this new initializer list into the structured initializer
1251 // lists.
1252 if (StructuredList)
1253 StructuredList->updateInit(StructuredIndex, Result);
1254 else {
1255 Result->setSyntacticForm(IList);
1256 SyntacticToSemantic[IList] = Result;
1257 }
1258
1259 return Result;
1260}
1261
1262/// Update the initializer at index @p StructuredIndex within the
1263/// structured initializer list to the value @p expr.
1264void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1265 unsigned &StructuredIndex,
1266 Expr *expr) {
1267 // No structured initializer list to update
1268 if (!StructuredList)
1269 return;
1270
1271 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1272 // This initializer overwrites a previous initializer. Warn.
1273 SemaRef->Diag(expr->getSourceRange().getBegin(),
1274 diag::warn_initializer_overrides)
1275 << expr->getSourceRange();
1276 SemaRef->Diag(PrevInit->getSourceRange().getBegin(),
1277 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001278 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001279 << PrevInit->getSourceRange();
1280 }
1281
1282 ++StructuredIndex;
1283}
1284
Douglas Gregor05c13a32009-01-22 00:58:24 +00001285/// Check that the given Index expression is a valid array designator
1286/// value. This is essentailly just a wrapper around
1287/// Expr::isIntegerConstantExpr that also checks for negative values
1288/// and produces a reasonable diagnostic if there is a
1289/// failure. Returns true if there was an error, false otherwise. If
1290/// everything went okay, Value will receive the value of the constant
1291/// expression.
1292static bool
1293CheckArrayDesignatorExpr(Sema &Self, Expr *Index, llvm::APSInt &Value) {
1294 SourceLocation Loc = Index->getSourceRange().getBegin();
1295
1296 // Make sure this is an integer constant expression.
1297 if (!Index->isIntegerConstantExpr(Value, Self.Context, &Loc))
1298 return Self.Diag(Loc, diag::err_array_designator_nonconstant)
1299 << Index->getSourceRange();
1300
1301 // Make sure this constant expression is non-negative.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001302 llvm::APSInt Zero(llvm::APSInt::getNullValue(Value.getBitWidth()),
1303 Value.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001304 if (Value < Zero)
1305 return Self.Diag(Loc, diag::err_array_designator_negative)
1306 << Value.toString(10) << Index->getSourceRange();
1307
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001308 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001309 return false;
1310}
1311
1312Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1313 SourceLocation Loc,
1314 bool UsedColonSyntax,
1315 OwningExprResult Init) {
1316 typedef DesignatedInitExpr::Designator ASTDesignator;
1317
1318 bool Invalid = false;
1319 llvm::SmallVector<ASTDesignator, 32> Designators;
1320 llvm::SmallVector<Expr *, 32> InitExpressions;
1321
1322 // Build designators and check array designator expressions.
1323 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1324 const Designator &D = Desig.getDesignator(Idx);
1325 switch (D.getKind()) {
1326 case Designator::FieldDesignator:
1327 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1328 D.getFieldLoc()));
1329 break;
1330
1331 case Designator::ArrayDesignator: {
1332 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1333 llvm::APSInt IndexValue;
1334 if (CheckArrayDesignatorExpr(*this, Index, IndexValue))
1335 Invalid = true;
1336 else {
1337 Designators.push_back(ASTDesignator(InitExpressions.size(),
1338 D.getLBracketLoc(),
1339 D.getRBracketLoc()));
1340 InitExpressions.push_back(Index);
1341 }
1342 break;
1343 }
1344
1345 case Designator::ArrayRangeDesignator: {
1346 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1347 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1348 llvm::APSInt StartValue;
1349 llvm::APSInt EndValue;
1350 if (CheckArrayDesignatorExpr(*this, StartIndex, StartValue) ||
1351 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))
1352 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001353 else {
1354 // Make sure we're comparing values with the same bit width.
1355 if (StartValue.getBitWidth() > EndValue.getBitWidth())
1356 EndValue.extend(StartValue.getBitWidth());
1357 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1358 StartValue.extend(EndValue.getBitWidth());
1359
1360 if (EndValue < StartValue) {
1361 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1362 << StartValue.toString(10) << EndValue.toString(10)
1363 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1364 Invalid = true;
1365 } else {
1366 Designators.push_back(ASTDesignator(InitExpressions.size(),
1367 D.getLBracketLoc(),
1368 D.getEllipsisLoc(),
1369 D.getRBracketLoc()));
1370 InitExpressions.push_back(StartIndex);
1371 InitExpressions.push_back(EndIndex);
1372 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001373 }
1374 break;
1375 }
1376 }
1377 }
1378
1379 if (Invalid || Init.isInvalid())
1380 return ExprError();
1381
1382 // Clear out the expressions within the designation.
1383 Desig.ClearExprs(*this);
1384
1385 DesignatedInitExpr *DIE
1386 = DesignatedInitExpr::Create(Context, &Designators[0], Designators.size(),
1387 &InitExpressions[0], InitExpressions.size(),
1388 Loc, UsedColonSyntax,
1389 static_cast<Expr *>(Init.release()));
1390 return Owned(DIE);
1391}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001392
1393bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
1394 InitListChecker CheckInitList(this, InitList, DeclType);
1395 if (!CheckInitList.HadError())
1396 InitList = CheckInitList.getFullyStructuredList();
1397
1398 return CheckInitList.HadError();
1399}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001400
1401/// \brief Diagnose any semantic errors with value-initialization of
1402/// the given type.
1403///
1404/// Value-initialization effectively zero-initializes any types
1405/// without user-declared constructors, and calls the default
1406/// constructor for a for any type that has a user-declared
1407/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1408/// a type with a user-declared constructor does not have an
1409/// accessible, non-deleted default constructor. In C, everything can
1410/// be value-initialized, which corresponds to C's notion of
1411/// initializing objects with static storage duration when no
1412/// initializer is provided for that object.
1413///
1414/// \returns true if there was an error, false otherwise.
1415bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1416 // C++ [dcl.init]p5:
1417 //
1418 // To value-initialize an object of type T means:
1419
1420 // -- if T is an array type, then each element is value-initialized;
1421 if (const ArrayType *AT = Context.getAsArrayType(Type))
1422 return CheckValueInitialization(AT->getElementType(), Loc);
1423
1424 if (const RecordType *RT = Type->getAsRecordType()) {
1425 if (const CXXRecordType *CXXRec = dyn_cast<CXXRecordType>(RT)) {
1426 // -- if T is a class type (clause 9) with a user-declared
1427 // constructor (12.1), then the default constructor for T is
1428 // called (and the initialization is ill-formed if T has no
1429 // accessible default constructor);
1430 if (CXXRec->getDecl()->hasUserDeclaredConstructor())
1431 // FIXME: Eventually, we'll need to put the constructor decl
1432 // into the AST.
1433 return PerformInitializationByConstructor(Type, 0, 0, Loc,
1434 SourceRange(Loc),
1435 DeclarationName(),
1436 IK_Direct);
1437 }
1438 }
1439
1440 if (Type->isReferenceType()) {
1441 // C++ [dcl.init]p5:
1442 // [...] A program that calls for default-initialization or
1443 // value-initialization of an entity of reference type is
1444 // ill-formed. [...]
Douglas Gregord8635172009-02-02 21:35:47 +00001445 // FIXME: Once we have code that goes through this path, add an
1446 // actual diagnostic :)
Douglas Gregor87fd7032009-02-02 17:43:21 +00001447 }
1448
1449 return false;
1450}