blob: 38ab5c520da418f1fcd557f36330ae4f0d3caff4 [file] [log] [blame]
Steve Naroffc4d4a482008-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 Gregoraaa20962009-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 Naroffc4d4a482008-05-01 22:18:59 +000013//
14//===----------------------------------------------------------------------===//
15
16#include "Sema.h"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +000017#include "clang/Parse/Designator.h"
Steve Naroffc4d4a482008-05-01 22:18:59 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
Douglas Gregor849afc32009-01-29 00:45:39 +000020#include <map>
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +000021using namespace clang;
Steve Naroffc4d4a482008-05-01 22:18:59 +000022
Douglas Gregoraaa20962009-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 Lattner1aa25a72009-01-29 05:10:57 +000050namespace clang {
Douglas Gregor849afc32009-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 Gregoraaa20962009-01-29 01:05:33 +000058 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +000059 unsigned &StructuredIndex,
60 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +000061 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregoraaa20962009-01-29 01:05:33 +000062 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +000063 unsigned &StructuredIndex,
64 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +000065 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
66 bool SubobjectIsDesignatorContext,
67 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +000068 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +000069 unsigned &StructuredIndex,
70 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +000071 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
72 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +000073 InitListExpr *StructuredList,
74 unsigned &StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +000075 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor849afc32009-01-29 00:45:39 +000076 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +000077 InitListExpr *StructuredList,
78 unsigned &StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +000079 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
80 unsigned &Index,
81 InitListExpr *StructuredList,
82 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000083 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +000084 InitListExpr *StructuredList,
85 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000086 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
87 RecordDecl::field_iterator Field,
88 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +000089 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +000090 unsigned &StructuredIndex,
91 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +000092 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
93 llvm::APSInt elementIndex,
94 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +000095 InitListExpr *StructuredList,
96 unsigned &StructuredIndex);
Douglas Gregor849afc32009-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 Gregorbe69b162009-02-04 22:46:25 +0000105 bool FinishSubobjectInit,
106 bool TopLevelObject);
Douglas Gregor849afc32009-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 Gregoraaa20962009-01-29 01:05:33 +0000112 void UpdateStructuredListElement(InitListExpr *StructuredList,
113 unsigned &StructuredIndex,
Douglas Gregor849afc32009-01-29 00:45:39 +0000114 Expr *expr);
115 int numArrayElements(QualType DeclType);
116 int numStructUnionElements(QualType DeclType);
Douglas Gregord45210d2009-01-30 22:09:00 +0000117
118 void FillInValueInitializations(InitListExpr *ILE);
Douglas Gregor849afc32009-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 Lattner1aa25a72009-01-29 05:10:57 +0000127}
128
Douglas Gregorf603b472009-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 Gregord45210d2009-01-30 22:09:00 +0000132void InitListChecker::FillInValueInitializations(InitListExpr *ILE) {
133 assert((ILE->getType() != SemaRef->Context.VoidTy) &&
134 "Should not have void type");
Douglas Gregor538a4c22009-02-02 17:43:21 +0000135 SourceLocation Loc = ILE->getSourceRange().getBegin();
136 if (ILE->getSyntacticForm())
137 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
138
Douglas Gregorf603b472009-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 Gregor538a4c22009-02-02 17:43:21 +0000147 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregord45210d2009-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 Gregor538a4c22009-02-02 17:43:21 +0000153 SemaRef->Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregord45210d2009-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 Gregor538a4c22009-02-02 17:43:21 +0000159 return;
160 } else if (SemaRef->CheckValueInitialization(Field->getType(), Loc)) {
161 hadError = true;
162 return;
Douglas Gregord45210d2009-01-30 22:09:00 +0000163 }
Douglas Gregor538a4c22009-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 Gregorc9e012a2009-01-29 17:44:32 +0000173 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregord45210d2009-01-30 22:09:00 +0000174 FillInValueInitializations(InnerILE);
Douglas Gregorf603b472009-01-28 21:54:33 +0000175 ++Init;
Douglas Gregord45210d2009-01-30 22:09:00 +0000176
177 // Only look at the first initialization of a union.
178 if (RType->getDecl()->isUnion())
179 break;
Douglas Gregorf603b472009-01-28 21:54:33 +0000180 }
181
182 return;
183 }
184
185 QualType ElementType;
186
Douglas Gregor538a4c22009-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 Gregorf603b472009-01-28 21:54:33 +0000190 ElementType = AType->getElementType();
Douglas Gregor538a4c22009-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 Gregorf603b472009-01-28 21:54:33 +0000194 ElementType = VType->getElementType();
Douglas Gregor538a4c22009-02-02 17:43:21 +0000195 NumElements = VType->getNumElements();
196 } else
Douglas Gregorf603b472009-01-28 21:54:33 +0000197 ElementType = ILE->getType();
198
Douglas Gregor538a4c22009-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 Lattner1aa25a72009-01-29 05:10:57 +0000214 else if (InitListExpr *InnerILE =dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregord45210d2009-01-30 22:09:00 +0000215 FillInValueInitializations(InnerILE);
Douglas Gregorf603b472009-01-28 21:54:33 +0000216 }
217}
218
Chris Lattner1aa25a72009-01-29 05:10:57 +0000219
Steve Naroffc4d4a482008-05-01 22:18:59 +0000220InitListChecker::InitListChecker(Sema *S, InitListExpr *IL, QualType &T) {
221 hadError = false;
222 SemaRef = S;
Eli Friedmand8535af2008-05-19 20:00:43 +0000223
Eli Friedman683cedf2008-05-19 19:16:24 +0000224 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000225 unsigned newStructuredIndex = 0;
226 FullyStructuredList
227 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, SourceRange());
Douglas Gregorbe69b162009-02-04 22:46:25 +0000228 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
229 /*TopLevelObject=*/true);
Eli Friedmand8535af2008-05-19 20:00:43 +0000230
Douglas Gregord45210d2009-01-30 22:09:00 +0000231 if (!hadError)
232 FillInValueInitializations(FullyStructuredList);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000233}
234
235int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman46f81662008-05-25 13:22:35 +0000236 // FIXME: use a proper constant
237 int maxElements = 0x7FFFFFFF;
Chris Lattnera1923f62008-08-04 07:31:14 +0000238 if (const ConstantArrayType *CAT =
239 SemaRef->Context.getAsConstantArrayType(DeclType)) {
Steve Naroffc4d4a482008-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 Gregorf603b472009-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 }
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000254 if (structDecl->isUnion())
Eli Friedman9f5250b2008-05-25 14:03:31 +0000255 return std::min(InitializableMembers, 1);
256 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000257}
258
259void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregorf603b472009-01-28 21:54:33 +0000260 QualType T, unsigned &Index,
261 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000262 unsigned &StructuredIndex,
263 bool TopLevelObject) {
Steve Naroffc4d4a482008-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 Friedman683cedf2008-05-19 19:16:24 +0000270 else if (T->isVectorType())
271 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000272 else
273 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman683cedf2008-05-19 19:16:24 +0000274
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000275 if (maxElements == 0) {
276 SemaRef->Diag(ParentIList->getInit(Index)->getLocStart(),
277 diag::err_implicit_empty_initializer);
Douglas Gregorf603b472009-01-28 21:54:33 +0000278 ++Index;
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000279 hadError = true;
280 return;
281 }
282
Douglas Gregorf603b472009-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 Friedman683cedf2008-05-19 19:16:24 +0000289
Douglas Gregorf603b472009-01-28 21:54:33 +0000290 // Check the element types and build the structural subobject.
Douglas Gregor538a4c22009-02-02 17:43:21 +0000291 unsigned StartIndex = Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000292 CheckListElementTypes(ParentIList, T, false, Index,
293 StructuredSubobjectInitList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000294 StructuredSubobjectInitIndex,
295 TopLevelObject);
Douglas Gregor538a4c22009-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 Naroffc4d4a482008-05-01 22:18:59 +0000305}
306
Steve Naroff56099522008-05-06 00:23:44 +0000307void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregorf603b472009-01-28 21:54:33 +0000308 unsigned &Index,
309 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000310 unsigned &StructuredIndex,
311 bool TopLevelObject) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000312 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregorf603b472009-01-28 21:54:33 +0000313 SyntacticToSemantic[IList] = StructuredList;
314 StructuredList->setSyntacticForm(IList);
315 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000316 StructuredIndex, TopLevelObject);
Steve Naroff56099522008-05-06 00:23:44 +0000317 IList->setType(T);
Douglas Gregorf603b472009-01-28 21:54:33 +0000318 StructuredList->setType(T);
Eli Friedman46f81662008-05-25 13:22:35 +0000319 if (hadError)
320 return;
Eli Friedmand8535af2008-05-19 20:00:43 +0000321
Eli Friedman46f81662008-05-25 13:22:35 +0000322 if (Index < IList->getNumInits()) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000323 // We have leftover initializers
324 if (IList->getNumInits() > 0 &&
325 SemaRef->IsStringLiteralInit(IList->getInit(Index), T)) {
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000326 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
327 if (SemaRef->getLangOptions().CPlusPlus)
328 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000329 // Special-case
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000330 SemaRef->Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattner9d2cf082008-11-19 05:27:50 +0000331 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000332 hadError = true;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000333 } else if (!T->isIncompleteType()) {
Douglas Gregor09f078c2009-01-30 22:26:29 +0000334 // Don't complain for incomplete types, since we'll get an error
335 // elsewhere
Douglas Gregorbe69b162009-02-04 22:46:25 +0000336 QualType CurrentObjectType = StructuredList->getType();
337 int initKind =
338 CurrentObjectType->isArrayType()? 0 :
339 CurrentObjectType->isVectorType()? 1 :
340 CurrentObjectType->isScalarType()? 2 :
341 CurrentObjectType->isUnionType()? 3 :
342 4;
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000343
344 unsigned DK = diag::warn_excess_initializers;
345 if (SemaRef->getLangOptions().CPlusPlus)
346 DK = diag::err_excess_initializers;
347
348 SemaRef->Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorbe69b162009-02-04 22:46:25 +0000349 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000350 }
351 }
Eli Friedman455f7622008-05-19 20:20:43 +0000352
Eli Friedman46f81662008-05-25 13:22:35 +0000353 if (T->isScalarType())
Chris Lattner9d2cf082008-11-19 05:27:50 +0000354 SemaRef->Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
355 << IList->getSourceRange();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000356}
357
Eli Friedman683cedf2008-05-19 19:16:24 +0000358void InitListChecker::CheckListElementTypes(InitListExpr *IList,
359 QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000360 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000361 unsigned &Index,
362 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000363 unsigned &StructuredIndex,
364 bool TopLevelObject) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000365 if (DeclType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000366 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000367 } else if (DeclType->isVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000368 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregore7ef5002009-01-30 17:31:00 +0000369 } else if (DeclType->isAggregateType()) {
370 if (DeclType->isRecordType()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000371 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
372 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000373 SubobjectIsDesignatorContext, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000374 StructuredList, StructuredIndex,
375 TopLevelObject);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000376 } else if (DeclType->isArrayType()) {
Douglas Gregor5a203a62009-01-23 16:54:12 +0000377 llvm::APSInt Zero(
378 SemaRef->Context.getTypeSize(SemaRef->Context.getSizeType()),
379 false);
Douglas Gregorf603b472009-01-28 21:54:33 +0000380 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
381 StructuredList, StructuredIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000382 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000383 else
Douglas Gregorf603b472009-01-28 21:54:33 +0000384 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffff5b3a82008-08-10 16:05:48 +0000385 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
386 // This type is invalid, issue a diagnostic.
Douglas Gregorf603b472009-01-28 21:54:33 +0000387 ++Index;
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000388 SemaRef->Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000389 << DeclType;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000390 hadError = true;
Douglas Gregord45210d2009-01-30 22:09:00 +0000391 } else if (DeclType->isRecordType()) {
392 // C++ [dcl.init]p14:
393 // [...] If the class is an aggregate (8.5.1), and the initializer
394 // is a brace-enclosed list, see 8.5.1.
395 //
396 // Note: 8.5.1 is handled below; here, we diagnose the case where
397 // we have an initializer list and a destination type that is not
398 // an aggregate.
399 // FIXME: In C++0x, this is yet another form of initialization.
400 SemaRef->Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
401 << DeclType << IList->getSourceRange();
402 hadError = true;
403 } else if (DeclType->isReferenceType()) {
404 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000405 } else {
406 // In C, all types are either scalars or aggregates, but
407 // additional handling is needed here for C++ (and possibly others?).
408 assert(0 && "Unsupported initializer type");
409 }
410}
411
Eli Friedman683cedf2008-05-19 19:16:24 +0000412void InitListChecker::CheckSubElementType(InitListExpr *IList,
413 QualType ElemType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000414 unsigned &Index,
415 InitListExpr *StructuredList,
416 unsigned &StructuredIndex) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000417 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000418 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
419 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000420 unsigned newStructuredIndex = 0;
421 InitListExpr *newStructuredList
422 = getStructuredSubobjectInit(IList, Index, ElemType,
423 StructuredList, StructuredIndex,
424 SubInitList->getSourceRange());
425 CheckExplicitInitList(SubInitList, ElemType, newIndex,
426 newStructuredList, newStructuredIndex);
427 ++StructuredIndex;
428 ++Index;
Eli Friedman683cedf2008-05-19 19:16:24 +0000429 } else if (StringLiteral *lit =
430 SemaRef->IsStringLiteralInit(expr, ElemType)) {
431 SemaRef->CheckStringLiteralInit(lit, ElemType);
Douglas Gregorf603b472009-01-28 21:54:33 +0000432 UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
433 ++Index;
Eli Friedmand8535af2008-05-19 20:00:43 +0000434 } else if (ElemType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000435 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000436 } else if (ElemType->isReferenceType()) {
437 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedman683cedf2008-05-19 19:16:24 +0000438 } else {
Douglas Gregord45210d2009-01-30 22:09:00 +0000439 if (SemaRef->getLangOptions().CPlusPlus) {
440 // C++ [dcl.init.aggr]p12:
441 // All implicit type conversions (clause 4) are considered when
442 // initializing the aggregate member with an ini- tializer from
443 // an initializer-list. If the initializer can initialize a
444 // member, the member is initialized. [...]
445 ImplicitConversionSequence ICS
446 = SemaRef->TryCopyInitialization(expr, ElemType);
447 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
448 if (SemaRef->PerformImplicitConversion(expr, ElemType, ICS,
449 "initializing"))
450 hadError = true;
451 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
452 ++Index;
453 return;
454 }
455
456 // Fall through for subaggregate initialization
457 } else {
458 // C99 6.7.8p13:
459 //
460 // The initializer for a structure or union object that has
461 // automatic storage duration shall be either an initializer
462 // list as described below, or a single expression that has
463 // compatible structure or union type. In the latter case, the
464 // initial value of the object, including unnamed members, is
465 // that of the expression.
466 QualType ExprType = SemaRef->Context.getCanonicalType(expr->getType());
467 QualType ElemTypeCanon = SemaRef->Context.getCanonicalType(ElemType);
468 if (SemaRef->Context.typesAreCompatible(ExprType.getUnqualifiedType(),
469 ElemTypeCanon.getUnqualifiedType())) {
470 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
471 ++Index;
472 return;
473 }
474
475 // Fall through for subaggregate initialization
476 }
477
478 // C++ [dcl.init.aggr]p12:
479 //
480 // [...] Otherwise, if the member is itself a non-empty
481 // subaggregate, brace elision is assumed and the initializer is
482 // considered for the initialization of the first member of
483 // the subaggregate.
484 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
485 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
486 StructuredIndex);
487 ++StructuredIndex;
488 } else {
489 // We cannot initialize this element, so let
490 // PerformCopyInitialization produce the appropriate diagnostic.
491 SemaRef->PerformCopyInitialization(expr, ElemType, "initializing");
492 hadError = true;
493 ++Index;
494 ++StructuredIndex;
495 }
496 }
Eli Friedman683cedf2008-05-19 19:16:24 +0000497}
498
Douglas Gregord45210d2009-01-30 22:09:00 +0000499void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor36859eb2009-01-29 00:39:20 +0000500 unsigned &Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000501 InitListExpr *StructuredList,
502 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000503 if (Index < IList->getNumInits()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000504 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000505 if (isa<InitListExpr>(expr)) {
Eli Friedman71de9eb2008-05-19 20:12:18 +0000506 SemaRef->Diag(IList->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000507 diag::err_many_braces_around_scalar_init)
508 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000509 hadError = true;
510 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000511 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000512 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000513 } else if (isa<DesignatedInitExpr>(expr)) {
514 SemaRef->Diag(expr->getSourceRange().getBegin(),
515 diag::err_designator_for_scalar_init)
516 << DeclType << expr->getSourceRange();
517 hadError = true;
518 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000519 ++StructuredIndex;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000520 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000521 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000522
Eli Friedmand8535af2008-05-19 20:00:43 +0000523 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000524 if (SemaRef->CheckSingleInitializer(expr, DeclType, false))
Eli Friedman71de9eb2008-05-19 20:12:18 +0000525 hadError = true; // types weren't compatible.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000526 else if (savExpr != expr) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000527 // The type was promoted, update initializer list.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000528 IList->setInit(Index, expr);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000529 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000530 if (hadError)
531 ++StructuredIndex;
532 else
533 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000534 ++Index;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000535 } else {
Chris Lattner9d2cf082008-11-19 05:27:50 +0000536 SemaRef->Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
537 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000538 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000539 ++Index;
540 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000541 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000542 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000543}
544
Douglas Gregord45210d2009-01-30 22:09:00 +0000545void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
546 unsigned &Index,
547 InitListExpr *StructuredList,
548 unsigned &StructuredIndex) {
549 if (Index < IList->getNumInits()) {
550 Expr *expr = IList->getInit(Index);
551 if (isa<InitListExpr>(expr)) {
552 SemaRef->Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
553 << DeclType << IList->getSourceRange();
554 hadError = true;
555 ++Index;
556 ++StructuredIndex;
557 return;
558 }
559
560 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
561 if (SemaRef->CheckReferenceInit(expr, DeclType))
562 hadError = true;
563 else if (savExpr != expr) {
564 // The type was promoted, update initializer list.
565 IList->setInit(Index, expr);
566 }
567 if (hadError)
568 ++StructuredIndex;
569 else
570 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
571 ++Index;
572 } else {
573 // FIXME: It would be wonderful if we could point at the actual
574 // member. In general, it would be useful to pass location
575 // information down the stack, so that we know the location (or
576 // decl) of the "current object" being initialized.
577 SemaRef->Diag(IList->getLocStart(),
578 diag::err_init_reference_member_uninitialized)
579 << DeclType
580 << IList->getSourceRange();
581 hadError = true;
582 ++Index;
583 ++StructuredIndex;
584 return;
585 }
586}
587
Steve Naroffc4d4a482008-05-01 22:18:59 +0000588void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000589 unsigned &Index,
590 InitListExpr *StructuredList,
591 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000592 if (Index < IList->getNumInits()) {
593 const VectorType *VT = DeclType->getAsVectorType();
594 int maxElements = VT->getNumElements();
595 QualType elementType = VT->getElementType();
596
597 for (int i = 0; i < maxElements; ++i) {
598 // Don't attempt to go past the end of the init list
599 if (Index >= IList->getNumInits())
600 break;
Douglas Gregor36859eb2009-01-29 00:39:20 +0000601 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000602 StructuredList, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000603 }
604 }
605}
606
607void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000608 llvm::APSInt elementIndex,
609 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000610 unsigned &Index,
611 InitListExpr *StructuredList,
612 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000613 // Check for the special-case of initializing an array with a string.
614 if (Index < IList->getNumInits()) {
615 if (StringLiteral *lit =
616 SemaRef->IsStringLiteralInit(IList->getInit(Index), DeclType)) {
617 SemaRef->CheckStringLiteralInit(lit, DeclType);
Douglas Gregorf603b472009-01-28 21:54:33 +0000618 // We place the string literal directly into the resulting
619 // initializer list. This is the only place where the structure
620 // of the structured initializer list doesn't match exactly,
621 // because doing so would involve allocating one character
622 // constant for each string.
623 UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
624 StructuredList->resizeInits(SemaRef->Context, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000625 ++Index;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000626 return;
627 }
628 }
Chris Lattnera1923f62008-08-04 07:31:14 +0000629 if (const VariableArrayType *VAT =
630 SemaRef->Context.getAsVariableArrayType(DeclType)) {
Eli Friedman46f81662008-05-25 13:22:35 +0000631 // Check for VLAs; in standard C it would be possible to check this
632 // earlier, but I don't know where clang accepts VLAs (gcc accepts
633 // them in all sorts of strange places).
634 SemaRef->Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000635 diag::err_variable_object_no_init)
636 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman46f81662008-05-25 13:22:35 +0000637 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000638 ++Index;
639 ++StructuredIndex;
Eli Friedman46f81662008-05-25 13:22:35 +0000640 return;
641 }
642
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000643 // We might know the maximum number of elements in advance.
Douglas Gregorf603b472009-01-28 21:54:33 +0000644 llvm::APSInt maxElements(elementIndex.getBitWidth(),
645 elementIndex.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000646 bool maxElementsKnown = false;
647 if (const ConstantArrayType *CAT =
648 SemaRef->Context.getAsConstantArrayType(DeclType)) {
649 maxElements = CAT->getSize();
Douglas Gregor5a203a62009-01-23 16:54:12 +0000650 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000651 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000652 maxElementsKnown = true;
653 }
654
Chris Lattnera1923f62008-08-04 07:31:14 +0000655 QualType elementType = SemaRef->Context.getAsArrayType(DeclType)
656 ->getElementType();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000657 while (Index < IList->getNumInits()) {
658 Expr *Init = IList->getInit(Index);
659 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000660 // If we're not the subobject that matches up with the '{' for
661 // the designator, we shouldn't be handling the
662 // designator. Return immediately.
663 if (!SubobjectIsDesignatorContext)
664 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000665
Douglas Gregor710f6d42009-01-22 23:26:18 +0000666 // Handle this designated initializer. elementIndex will be
667 // updated to be the next array element we'll initialize.
668 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000669 DeclType, 0, &elementIndex, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000670 StructuredList, StructuredIndex, true,
671 false)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000672 hadError = true;
673 continue;
674 }
675
Douglas Gregor5a203a62009-01-23 16:54:12 +0000676 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
677 maxElements.extend(elementIndex.getBitWidth());
678 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
679 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000680 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor5a203a62009-01-23 16:54:12 +0000681
Douglas Gregor710f6d42009-01-22 23:26:18 +0000682 // If the array is of incomplete type, keep track of the number of
683 // elements in the initializer.
684 if (!maxElementsKnown && elementIndex > maxElements)
685 maxElements = elementIndex;
686
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000687 continue;
688 }
689
690 // If we know the maximum number of elements, and we've already
691 // hit it, stop consuming elements in the initializer list.
692 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000693 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000694
695 // Check this element.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000696 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000697 StructuredList, StructuredIndex);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000698 ++elementIndex;
699
700 // If the array is of incomplete type, keep track of the number of
701 // elements in the initializer.
702 if (!maxElementsKnown && elementIndex > maxElements)
703 maxElements = elementIndex;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000704 }
705 if (DeclType->isIncompleteArrayType()) {
706 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000707 // be calculated here.
Douglas Gregor69722702009-01-23 18:58:42 +0000708 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000709 if (maxElements == Zero) {
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000710 // Sizing an array implicitly to zero is not allowed by ISO C,
711 // but is supported by GNU.
Steve Naroffc4d4a482008-05-01 22:18:59 +0000712 SemaRef->Diag(IList->getLocStart(),
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000713 diag::ext_typecheck_zero_array_size);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000714 }
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000715
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000716 DeclType = SemaRef->Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000717 ArrayType::Normal, 0);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000718 }
719}
720
721void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
722 QualType DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000723 RecordDecl::field_iterator Field,
724 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000725 unsigned &Index,
726 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000727 unsigned &StructuredIndex,
728 bool TopLevelObject) {
Eli Friedman683cedf2008-05-19 19:16:24 +0000729 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000730
Eli Friedman683cedf2008-05-19 19:16:24 +0000731 // If the record is invalid, some of it's members are invalid. To avoid
732 // confusion, we forgo checking the intializer for the entire record.
733 if (structDecl->isInvalidDecl()) {
734 hadError = true;
735 return;
736 }
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000737
738 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
739 // Value-initialize the first named member of the union.
740 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
741 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
742 Field != FieldEnd; ++Field) {
743 if (Field->getDeclName()) {
744 StructuredList->setInitializedFieldInUnion(*Field);
745 break;
746 }
747 }
748 return;
749 }
750
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000751 // If structDecl is a forward declaration, this loop won't do
752 // anything except look at designated initializers; That's okay,
753 // because an error should get printed out elsewhere. It might be
754 // worthwhile to skip over the rest of the initializer, though.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000755 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor710f6d42009-01-22 23:26:18 +0000756 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0ecc9e92009-02-12 19:00:39 +0000757 bool InitializedSomething = false;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000758 while (Index < IList->getNumInits()) {
759 Expr *Init = IList->getInit(Index);
760
761 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000762 // If we're not the subobject that matches up with the '{' for
763 // the designator, we shouldn't be handling the
764 // designator. Return immediately.
765 if (!SubobjectIsDesignatorContext)
766 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000767
Douglas Gregor710f6d42009-01-22 23:26:18 +0000768 // Handle this designated initializer. Field will be updated to
769 // the next field that we'll be initializing.
770 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000771 DeclType, &Field, 0, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000772 StructuredList, StructuredIndex,
773 true, TopLevelObject))
Douglas Gregor710f6d42009-01-22 23:26:18 +0000774 hadError = true;
775
Douglas Gregor0ecc9e92009-02-12 19:00:39 +0000776 InitializedSomething = true;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000777 continue;
778 }
779
780 if (Field == FieldEnd) {
781 // We've run out of fields. We're done.
782 break;
783 }
784
Douglas Gregor0ecc9e92009-02-12 19:00:39 +0000785 // We've already initialized a member of a union. We're done.
786 if (InitializedSomething && DeclType->isUnionType())
787 break;
788
Douglas Gregor8acb7272008-12-11 16:49:14 +0000789 // If we've hit the flexible array member at the end, we're done.
790 if (Field->getType()->isIncompleteArrayType())
791 break;
792
Douglas Gregor82462762009-01-29 16:53:55 +0000793 if (Field->isUnnamedBitfield()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000794 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000795 ++Field;
Eli Friedman683cedf2008-05-19 19:16:24 +0000796 continue;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000797 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000798
Douglas Gregor36859eb2009-01-29 00:39:20 +0000799 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000800 StructuredList, StructuredIndex);
Douglas Gregor0ecc9e92009-02-12 19:00:39 +0000801 InitializedSomething = true;
Douglas Gregor82462762009-01-29 16:53:55 +0000802
803 if (DeclType->isUnionType()) {
804 // Initialize the first field within the union.
805 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor82462762009-01-29 16:53:55 +0000806 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000807
808 ++Field;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000809 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000810
Douglas Gregorbe69b162009-02-04 22:46:25 +0000811 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
812 Index >= IList->getNumInits() ||
813 !isa<InitListExpr>(IList->getInit(Index)))
814 return;
815
816 // Handle GNU flexible array initializers.
817 if (!TopLevelObject &&
818 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0) {
819 SemaRef->Diag(IList->getInit(Index)->getSourceRange().getBegin(),
820 diag::err_flexible_array_init_nonempty)
821 << IList->getInit(Index)->getSourceRange().getBegin();
822 SemaRef->Diag(Field->getLocation(), diag::note_flexible_array_member)
823 << *Field;
824 hadError = true;
825 }
826
827 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
828 StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000829}
Steve Naroffc4d4a482008-05-01 22:18:59 +0000830
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000831/// @brief Check the well-formedness of a C99 designated initializer.
832///
833/// Determines whether the designated initializer @p DIE, which
834/// resides at the given @p Index within the initializer list @p
835/// IList, is well-formed for a current object of type @p DeclType
836/// (C99 6.7.8). The actual subobject that this designator refers to
837/// within the current subobject is returned in either
Douglas Gregorf603b472009-01-28 21:54:33 +0000838/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000839///
840/// @param IList The initializer list in which this designated
841/// initializer occurs.
842///
843/// @param DIE The designated initializer and its initialization
844/// expression.
845///
846/// @param DeclType The type of the "current object" (C99 6.7.8p17),
847/// into which the designation in @p DIE should refer.
848///
Douglas Gregor710f6d42009-01-22 23:26:18 +0000849/// @param NextField If non-NULL and the first designator in @p DIE is
850/// a field, this will be set to the field declaration corresponding
851/// to the field named by the designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000852///
Douglas Gregor710f6d42009-01-22 23:26:18 +0000853/// @param NextElementIndex If non-NULL and the first designator in @p
854/// DIE is an array designator or GNU array-range designator, this
855/// will be set to the last index initialized by this designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000856///
857/// @param Index Index into @p IList where the designated initializer
858/// @p DIE occurs.
859///
Douglas Gregorf603b472009-01-28 21:54:33 +0000860/// @param StructuredList The initializer list expression that
861/// describes all of the subobject initializers in the order they'll
862/// actually be initialized.
863///
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000864/// @returns true if there was an error, false otherwise.
Douglas Gregor710f6d42009-01-22 23:26:18 +0000865bool
866InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
867 DesignatedInitExpr *DIE,
868 DesignatedInitExpr::designators_iterator D,
869 QualType &CurrentObjectType,
870 RecordDecl::field_iterator *NextField,
871 llvm::APSInt *NextElementIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +0000872 unsigned &Index,
873 InitListExpr *StructuredList,
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000874 unsigned &StructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000875 bool FinishSubobjectInit,
876 bool TopLevelObject) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000877 if (D == DIE->designators_end()) {
878 // Check the actual initialization for the designated object type.
879 bool prevHadError = hadError;
Douglas Gregor36859eb2009-01-29 00:39:20 +0000880
881 // Temporarily remove the designator expression from the
882 // initializer list that the child calls see, so that we don't try
883 // to re-process the designator.
884 unsigned OldIndex = Index;
885 IList->setInit(OldIndex, DIE->getInit());
886
887 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000888 StructuredList, StructuredIndex);
Douglas Gregor36859eb2009-01-29 00:39:20 +0000889
890 // Restore the designated initializer expression in the syntactic
891 // form of the initializer list.
892 if (IList->getInit(OldIndex) != DIE->getInit())
893 DIE->setInit(IList->getInit(OldIndex));
894 IList->setInit(OldIndex, DIE);
895
Douglas Gregor710f6d42009-01-22 23:26:18 +0000896 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000897 }
898
Douglas Gregorf603b472009-01-28 21:54:33 +0000899 bool IsFirstDesignator = (D == DIE->designators_begin());
900 assert((IsFirstDesignator || StructuredList) &&
901 "Need a non-designated initializer list to start from");
902
903 // Determine the structural initializer list that corresponds to the
904 // current subobject.
905 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
906 : getStructuredSubobjectInit(IList, Index, CurrentObjectType, StructuredList,
907 StructuredIndex,
908 SourceRange(D->getStartLocation(),
909 DIE->getSourceRange().getEnd()));
910 assert(StructuredList && "Expected a structured initializer list");
911
Douglas Gregor710f6d42009-01-22 23:26:18 +0000912 if (D->isFieldDesignator()) {
913 // C99 6.7.8p7:
914 //
915 // If a designator has the form
916 //
917 // . identifier
918 //
919 // then the current object (defined below) shall have
920 // structure or union type and the identifier shall be the
921 // name of a member of that type.
922 const RecordType *RT = CurrentObjectType->getAsRecordType();
923 if (!RT) {
924 SourceLocation Loc = D->getDotLoc();
925 if (Loc.isInvalid())
926 Loc = D->getFieldLoc();
927 SemaRef->Diag(Loc, diag::err_field_designator_non_aggr)
928 << SemaRef->getLangOptions().CPlusPlus << CurrentObjectType;
929 ++Index;
930 return true;
931 }
932
Douglas Gregorf603b472009-01-28 21:54:33 +0000933 // Note: we perform a linear search of the fields here, despite
934 // the fact that we have a faster lookup method, because we always
935 // need to compute the field's index.
Douglas Gregor710f6d42009-01-22 23:26:18 +0000936 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregorf603b472009-01-28 21:54:33 +0000937 unsigned FieldIndex = 0;
938 RecordDecl::field_iterator Field = RT->getDecl()->field_begin(),
939 FieldEnd = RT->getDecl()->field_end();
940 for (; Field != FieldEnd; ++Field) {
941 if (Field->isUnnamedBitfield())
942 continue;
943
944 if (Field->getIdentifier() == FieldName)
945 break;
946
947 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000948 }
949
Douglas Gregorf603b472009-01-28 21:54:33 +0000950 if (Field == FieldEnd) {
951 // We did not find the field we're looking for. Produce a
952 // suitable diagnostic and return a failure.
953 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
954 if (Lookup.first == Lookup.second) {
955 // Name lookup didn't find anything.
956 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
957 << FieldName << CurrentObjectType;
958 } else {
959 // Name lookup found something, but it wasn't a field.
960 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
961 << FieldName;
962 SemaRef->Diag((*Lookup.first)->getLocation(),
963 diag::note_field_designator_found);
964 }
965
966 ++Index;
967 return true;
968 } else if (cast<RecordDecl>((*Field)->getDeclContext())
969 ->isAnonymousStructOrUnion()) {
970 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_anon_class)
971 << FieldName
972 << (cast<RecordDecl>((*Field)->getDeclContext())->isUnion()? 2 :
973 (int)SemaRef->getLangOptions().CPlusPlus);
974 SemaRef->Diag((*Field)->getLocation(), diag::note_field_designator_found);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000975 ++Index;
976 return true;
977 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000978
979 // All of the fields of a union are located at the same place in
980 // the initializer list.
Douglas Gregor82462762009-01-29 16:53:55 +0000981 if (RT->getDecl()->isUnion()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000982 FieldIndex = 0;
Douglas Gregor82462762009-01-29 16:53:55 +0000983 StructuredList->setInitializedFieldInUnion(*Field);
984 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000985
Douglas Gregor710f6d42009-01-22 23:26:18 +0000986 // Update the designator with the field declaration.
Douglas Gregorf603b472009-01-28 21:54:33 +0000987 D->setField(*Field);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000988
Douglas Gregorf603b472009-01-28 21:54:33 +0000989 // Make sure that our non-designated initializer list has space
990 // for a subobject corresponding to this field.
991 if (FieldIndex >= StructuredList->getNumInits())
992 StructuredList->resizeInits(SemaRef->Context, FieldIndex + 1);
993
Douglas Gregorbe69b162009-02-04 22:46:25 +0000994 // This designator names a flexible array member.
995 if (Field->getType()->isIncompleteArrayType()) {
996 bool Invalid = false;
997 DesignatedInitExpr::designators_iterator NextD = D;
998 ++NextD;
999 if (NextD != DIE->designators_end()) {
1000 // We can't designate an object within the flexible array
1001 // member (because GCC doesn't allow it).
1002 SemaRef->Diag(NextD->getStartLocation(),
1003 diag::err_designator_into_flexible_array_member)
1004 << SourceRange(NextD->getStartLocation(),
1005 DIE->getSourceRange().getEnd());
1006 SemaRef->Diag(Field->getLocation(), diag::note_flexible_array_member)
1007 << *Field;
1008 Invalid = true;
1009 }
1010
1011 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1012 // The initializer is not an initializer list.
1013 SemaRef->Diag(DIE->getInit()->getSourceRange().getBegin(),
1014 diag::err_flexible_array_init_needs_braces)
1015 << DIE->getInit()->getSourceRange();
1016 SemaRef->Diag(Field->getLocation(), diag::note_flexible_array_member)
1017 << *Field;
1018 Invalid = true;
1019 }
1020
1021 // Handle GNU flexible array initializers.
1022 if (!Invalid && !TopLevelObject &&
1023 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
1024 SemaRef->Diag(DIE->getSourceRange().getBegin(),
1025 diag::err_flexible_array_init_nonempty)
1026 << DIE->getSourceRange().getBegin();
1027 SemaRef->Diag(Field->getLocation(), diag::note_flexible_array_member)
1028 << *Field;
1029 Invalid = true;
1030 }
1031
1032 if (Invalid) {
1033 ++Index;
1034 return true;
1035 }
1036
1037 // Initialize the array.
1038 bool prevHadError = hadError;
1039 unsigned newStructuredIndex = FieldIndex;
1040 unsigned OldIndex = Index;
1041 IList->setInit(Index, DIE->getInit());
1042 CheckSubElementType(IList, Field->getType(), Index,
1043 StructuredList, newStructuredIndex);
1044 IList->setInit(OldIndex, DIE);
1045 if (hadError && !prevHadError) {
1046 ++Field;
1047 ++FieldIndex;
1048 if (NextField)
1049 *NextField = Field;
1050 StructuredIndex = FieldIndex;
1051 return true;
1052 }
1053 } else {
1054 // Recurse to check later designated subobjects.
1055 QualType FieldType = (*Field)->getType();
1056 unsigned newStructuredIndex = FieldIndex;
1057 if (CheckDesignatedInitializer(IList, DIE, ++D, FieldType, 0, 0, Index,
1058 StructuredList, newStructuredIndex,
1059 true, false))
1060 return true;
1061 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001062
1063 // Find the position of the next field to be initialized in this
1064 // subobject.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001065 ++Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001066 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001067
1068 // If this the first designator, our caller will continue checking
1069 // the rest of this struct/class/union subobject.
1070 if (IsFirstDesignator) {
1071 if (NextField)
1072 *NextField = Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001073 StructuredIndex = FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001074 return false;
1075 }
1076
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001077 if (!FinishSubobjectInit)
1078 return false;
1079
Douglas Gregor710f6d42009-01-22 23:26:18 +00001080 // Check the remaining fields within this class/struct/union subobject.
1081 bool prevHadError = hadError;
Douglas Gregorf603b472009-01-28 21:54:33 +00001082 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1083 StructuredList, FieldIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001084 return hadError && !prevHadError;
1085 }
1086
1087 // C99 6.7.8p6:
1088 //
1089 // If a designator has the form
1090 //
1091 // [ constant-expression ]
1092 //
1093 // then the current object (defined below) shall have array
1094 // type and the expression shall be an integer constant
1095 // expression. If the array is of unknown size, any
1096 // nonnegative value is valid.
1097 //
1098 // Additionally, cope with the GNU extension that permits
1099 // designators of the form
1100 //
1101 // [ constant-expression ... constant-expression ]
1102 const ArrayType *AT = SemaRef->Context.getAsArrayType(CurrentObjectType);
1103 if (!AT) {
1104 SemaRef->Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1105 << CurrentObjectType;
1106 ++Index;
1107 return true;
1108 }
1109
1110 Expr *IndexExpr = 0;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001111 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1112 if (D->isArrayDesignator()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001113 IndexExpr = DIE->getArrayIndex(*D);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001114
1115 bool ConstExpr
1116 = IndexExpr->isIntegerConstantExpr(DesignatedStartIndex, SemaRef->Context);
1117 assert(ConstExpr && "Expression must be constant"); (void)ConstExpr;
1118
1119 DesignatedEndIndex = DesignatedStartIndex;
1120 } else {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001121 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001122
1123 bool StartConstExpr
1124 = DIE->getArrayRangeStart(*D)->isIntegerConstantExpr(DesignatedStartIndex,
1125 SemaRef->Context);
1126 assert(StartConstExpr && "Expression must be constant"); (void)StartConstExpr;
1127
1128 bool EndConstExpr
1129 = DIE->getArrayRangeEnd(*D)->isIntegerConstantExpr(DesignatedEndIndex,
1130 SemaRef->Context);
1131 assert(EndConstExpr && "Expression must be constant"); (void)EndConstExpr;
1132
Douglas Gregor710f6d42009-01-22 23:26:18 +00001133 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001134
1135 if (DesignatedStartIndex.getZExtValue() != DesignatedEndIndex.getZExtValue())
Douglas Gregor9fddded2009-01-29 19:42:23 +00001136 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001137 }
1138
Douglas Gregor710f6d42009-01-22 23:26:18 +00001139 if (isa<ConstantArrayType>(AT)) {
1140 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001141 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1142 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1143 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1144 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1145 if (DesignatedEndIndex >= MaxElements) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001146 SemaRef->Diag(IndexExpr->getSourceRange().getBegin(),
1147 diag::err_array_designator_too_large)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001148 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor710f6d42009-01-22 23:26:18 +00001149 << IndexExpr->getSourceRange();
1150 ++Index;
1151 return true;
1152 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001153 } else {
1154 // Make sure the bit-widths and signedness match.
1155 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1156 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
1157 else if (DesignatedStartIndex.getBitWidth() < DesignatedEndIndex.getBitWidth())
1158 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1159 DesignatedStartIndex.setIsUnsigned(true);
1160 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001161 }
1162
Douglas Gregorf603b472009-01-28 21:54:33 +00001163 // Make sure that our non-designated initializer list has space
1164 // for a subobject corresponding to this array element.
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001165 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
1166 StructuredList->resizeInits(SemaRef->Context,
1167 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +00001168
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001169 // Repeatedly perform subobject initializations in the range
1170 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor710f6d42009-01-22 23:26:18 +00001171
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001172 // Move to the next designator
1173 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1174 unsigned OldIndex = Index;
1175 ++D;
1176 while (DesignatedStartIndex <= DesignatedEndIndex) {
1177 // Recurse to check later designated subobjects.
1178 QualType ElementType = AT->getElementType();
1179 Index = OldIndex;
1180 if (CheckDesignatedInitializer(IList, DIE, D, ElementType, 0, 0, Index,
1181 StructuredList, ElementIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001182 (DesignatedStartIndex == DesignatedEndIndex),
1183 false))
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001184 return true;
1185
1186 // Move to the next index in the array that we'll be initializing.
1187 ++DesignatedStartIndex;
1188 ElementIndex = DesignatedStartIndex.getZExtValue();
1189 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001190
1191 // If this the first designator, our caller will continue checking
1192 // the rest of this array subobject.
1193 if (IsFirstDesignator) {
1194 if (NextElementIndex)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001195 *NextElementIndex = DesignatedStartIndex;
Douglas Gregorf603b472009-01-28 21:54:33 +00001196 StructuredIndex = ElementIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001197 return false;
1198 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001199
1200 if (!FinishSubobjectInit)
1201 return false;
1202
Douglas Gregor710f6d42009-01-22 23:26:18 +00001203 // Check the remaining elements within this array subobject.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001204 bool prevHadError = hadError;
Douglas Gregord7e76c52009-02-09 19:45:19 +00001205 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001206 StructuredList, ElementIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001207 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001208}
1209
Douglas Gregorf603b472009-01-28 21:54:33 +00001210// Get the structured initializer list for a subobject of type
1211// @p CurrentObjectType.
1212InitListExpr *
1213InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1214 QualType CurrentObjectType,
1215 InitListExpr *StructuredList,
1216 unsigned StructuredIndex,
1217 SourceRange InitRange) {
1218 Expr *ExistingInit = 0;
1219 if (!StructuredList)
1220 ExistingInit = SyntacticToSemantic[IList];
1221 else if (StructuredIndex < StructuredList->getNumInits())
1222 ExistingInit = StructuredList->getInit(StructuredIndex);
1223
1224 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1225 return Result;
1226
1227 if (ExistingInit) {
1228 // We are creating an initializer list that initializes the
1229 // subobjects of the current object, but there was already an
1230 // initialization that completely initialized the current
1231 // subobject, e.g., by a compound literal:
1232 //
1233 // struct X { int a, b; };
1234 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1235 //
1236 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1237 // designated initializer re-initializes the whole
1238 // subobject [0], overwriting previous initializers.
1239 SemaRef->Diag(InitRange.getBegin(), diag::warn_subobject_initializer_overrides)
1240 << InitRange;
1241 SemaRef->Diag(ExistingInit->getSourceRange().getBegin(),
1242 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001243 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001244 << ExistingInit->getSourceRange();
1245 }
1246
Douglas Gregor538a4c22009-02-02 17:43:21 +00001247 SourceLocation StartLoc;
1248 if (Index < IList->getNumInits())
1249 StartLoc = IList->getInit(Index)->getSourceRange().getBegin();
Douglas Gregorf603b472009-01-28 21:54:33 +00001250 InitListExpr *Result
Douglas Gregor538a4c22009-02-02 17:43:21 +00001251 = new (SemaRef->Context) InitListExpr(StartLoc, 0, 0,
1252 IList->getSourceRange().getEnd());
Douglas Gregorf603b472009-01-28 21:54:33 +00001253 Result->setType(CurrentObjectType);
1254
1255 // Link this new initializer list into the structured initializer
1256 // lists.
1257 if (StructuredList)
1258 StructuredList->updateInit(StructuredIndex, Result);
1259 else {
1260 Result->setSyntacticForm(IList);
1261 SyntacticToSemantic[IList] = Result;
1262 }
1263
1264 return Result;
1265}
1266
1267/// Update the initializer at index @p StructuredIndex within the
1268/// structured initializer list to the value @p expr.
1269void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1270 unsigned &StructuredIndex,
1271 Expr *expr) {
1272 // No structured initializer list to update
1273 if (!StructuredList)
1274 return;
1275
1276 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1277 // This initializer overwrites a previous initializer. Warn.
1278 SemaRef->Diag(expr->getSourceRange().getBegin(),
1279 diag::warn_initializer_overrides)
1280 << expr->getSourceRange();
1281 SemaRef->Diag(PrevInit->getSourceRange().getBegin(),
1282 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001283 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001284 << PrevInit->getSourceRange();
1285 }
1286
1287 ++StructuredIndex;
1288}
1289
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001290/// Check that the given Index expression is a valid array designator
1291/// value. This is essentailly just a wrapper around
1292/// Expr::isIntegerConstantExpr that also checks for negative values
1293/// and produces a reasonable diagnostic if there is a
1294/// failure. Returns true if there was an error, false otherwise. If
1295/// everything went okay, Value will receive the value of the constant
1296/// expression.
1297static bool
1298CheckArrayDesignatorExpr(Sema &Self, Expr *Index, llvm::APSInt &Value) {
1299 SourceLocation Loc = Index->getSourceRange().getBegin();
1300
1301 // Make sure this is an integer constant expression.
1302 if (!Index->isIntegerConstantExpr(Value, Self.Context, &Loc))
1303 return Self.Diag(Loc, diag::err_array_designator_nonconstant)
1304 << Index->getSourceRange();
1305
1306 // Make sure this constant expression is non-negative.
Douglas Gregor69722702009-01-23 18:58:42 +00001307 llvm::APSInt Zero(llvm::APSInt::getNullValue(Value.getBitWidth()),
1308 Value.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001309 if (Value < Zero)
1310 return Self.Diag(Loc, diag::err_array_designator_negative)
1311 << Value.toString(10) << Index->getSourceRange();
1312
Douglas Gregore498e372009-01-23 21:04:18 +00001313 Value.setIsUnsigned(true);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001314 return false;
1315}
1316
1317Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1318 SourceLocation Loc,
1319 bool UsedColonSyntax,
1320 OwningExprResult Init) {
1321 typedef DesignatedInitExpr::Designator ASTDesignator;
1322
1323 bool Invalid = false;
1324 llvm::SmallVector<ASTDesignator, 32> Designators;
1325 llvm::SmallVector<Expr *, 32> InitExpressions;
1326
1327 // Build designators and check array designator expressions.
1328 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1329 const Designator &D = Desig.getDesignator(Idx);
1330 switch (D.getKind()) {
1331 case Designator::FieldDesignator:
1332 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1333 D.getFieldLoc()));
1334 break;
1335
1336 case Designator::ArrayDesignator: {
1337 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1338 llvm::APSInt IndexValue;
1339 if (CheckArrayDesignatorExpr(*this, Index, IndexValue))
1340 Invalid = true;
1341 else {
1342 Designators.push_back(ASTDesignator(InitExpressions.size(),
1343 D.getLBracketLoc(),
1344 D.getRBracketLoc()));
1345 InitExpressions.push_back(Index);
1346 }
1347 break;
1348 }
1349
1350 case Designator::ArrayRangeDesignator: {
1351 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1352 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1353 llvm::APSInt StartValue;
1354 llvm::APSInt EndValue;
1355 if (CheckArrayDesignatorExpr(*this, StartIndex, StartValue) ||
1356 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))
1357 Invalid = true;
Douglas Gregorea0528d2009-01-23 22:22:29 +00001358 else {
1359 // Make sure we're comparing values with the same bit width.
1360 if (StartValue.getBitWidth() > EndValue.getBitWidth())
1361 EndValue.extend(StartValue.getBitWidth());
1362 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1363 StartValue.extend(EndValue.getBitWidth());
1364
1365 if (EndValue < StartValue) {
1366 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1367 << StartValue.toString(10) << EndValue.toString(10)
1368 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1369 Invalid = true;
1370 } else {
1371 Designators.push_back(ASTDesignator(InitExpressions.size(),
1372 D.getLBracketLoc(),
1373 D.getEllipsisLoc(),
1374 D.getRBracketLoc()));
1375 InitExpressions.push_back(StartIndex);
1376 InitExpressions.push_back(EndIndex);
1377 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001378 }
1379 break;
1380 }
1381 }
1382 }
1383
1384 if (Invalid || Init.isInvalid())
1385 return ExprError();
1386
1387 // Clear out the expressions within the designation.
1388 Desig.ClearExprs(*this);
1389
1390 DesignatedInitExpr *DIE
1391 = DesignatedInitExpr::Create(Context, &Designators[0], Designators.size(),
1392 &InitExpressions[0], InitExpressions.size(),
1393 Loc, UsedColonSyntax,
1394 static_cast<Expr *>(Init.release()));
1395 return Owned(DIE);
1396}
Douglas Gregor849afc32009-01-29 00:45:39 +00001397
1398bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
1399 InitListChecker CheckInitList(this, InitList, DeclType);
1400 if (!CheckInitList.HadError())
1401 InitList = CheckInitList.getFullyStructuredList();
1402
1403 return CheckInitList.HadError();
1404}
Douglas Gregor538a4c22009-02-02 17:43:21 +00001405
1406/// \brief Diagnose any semantic errors with value-initialization of
1407/// the given type.
1408///
1409/// Value-initialization effectively zero-initializes any types
1410/// without user-declared constructors, and calls the default
1411/// constructor for a for any type that has a user-declared
1412/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1413/// a type with a user-declared constructor does not have an
1414/// accessible, non-deleted default constructor. In C, everything can
1415/// be value-initialized, which corresponds to C's notion of
1416/// initializing objects with static storage duration when no
1417/// initializer is provided for that object.
1418///
1419/// \returns true if there was an error, false otherwise.
1420bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1421 // C++ [dcl.init]p5:
1422 //
1423 // To value-initialize an object of type T means:
1424
1425 // -- if T is an array type, then each element is value-initialized;
1426 if (const ArrayType *AT = Context.getAsArrayType(Type))
1427 return CheckValueInitialization(AT->getElementType(), Loc);
1428
1429 if (const RecordType *RT = Type->getAsRecordType()) {
1430 if (const CXXRecordType *CXXRec = dyn_cast<CXXRecordType>(RT)) {
1431 // -- if T is a class type (clause 9) with a user-declared
1432 // constructor (12.1), then the default constructor for T is
1433 // called (and the initialization is ill-formed if T has no
1434 // accessible default constructor);
1435 if (CXXRec->getDecl()->hasUserDeclaredConstructor())
1436 // FIXME: Eventually, we'll need to put the constructor decl
1437 // into the AST.
1438 return PerformInitializationByConstructor(Type, 0, 0, Loc,
1439 SourceRange(Loc),
1440 DeclarationName(),
1441 IK_Direct);
1442 }
1443 }
1444
1445 if (Type->isReferenceType()) {
1446 // C++ [dcl.init]p5:
1447 // [...] A program that calls for default-initialization or
1448 // value-initialization of an entity of reference type is
1449 // ill-formed. [...]
Douglas Gregorbd4b0852009-02-02 21:35:47 +00001450 // FIXME: Once we have code that goes through this path, add an
1451 // actual diagnostic :)
Douglas Gregor538a4c22009-02-02 17:43:21 +00001452 }
1453
1454 return false;
1455}