blob: bb523e179b8ac6198722badcbeb6db8d97544473 [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 Gregorf603b472009-01-28 21:54:33 +000020#include "clang/AST/ExprCXX.h"
Chris Lattner52a425b2009-01-27 18:30:58 +000021#include "clang/Basic/DiagnosticSema.h"
Douglas Gregor849afc32009-01-29 00:45:39 +000022#include <map>
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +000023using namespace clang;
Steve Naroffc4d4a482008-05-01 22:18:59 +000024
Douglas Gregoraaa20962009-01-29 01:05:33 +000025/// @brief Semantic checking for initializer lists.
26///
27/// The InitListChecker class contains a set of routines that each
28/// handle the initialization of a certain kind of entity, e.g.,
29/// arrays, vectors, struct/union types, scalars, etc. The
30/// InitListChecker itself performs a recursive walk of the subobject
31/// structure of the type to be initialized, while stepping through
32/// the initializer list one element at a time. The IList and Index
33/// parameters to each of the Check* routines contain the active
34/// (syntactic) initializer list and the index into that initializer
35/// list that represents the current initializer. Each routine is
36/// responsible for moving that Index forward as it consumes elements.
37///
38/// Each Check* routine also has a StructuredList/StructuredIndex
39/// arguments, which contains the current the "structured" (semantic)
40/// initializer list and the index into that initializer list where we
41/// are copying initializers as we map them over to the semantic
42/// list. Once we have completed our recursive walk of the subobject
43/// structure, we will have constructed a full semantic initializer
44/// list.
45///
46/// C99 designators cause changes in the initializer list traversal,
47/// because they make the initialization "jump" into a specific
48/// subobject and then continue the initialization from that
49/// point. CheckDesignatedInitializer() recursively steps into the
50/// designated subobject and manages backing out the recursion to
51/// initialize the subobjects after the one designated.
Chris Lattner1aa25a72009-01-29 05:10:57 +000052namespace clang {
Douglas Gregor849afc32009-01-29 00:45:39 +000053class InitListChecker {
54 Sema *SemaRef;
55 bool hadError;
56 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
57 InitListExpr *FullyStructuredList;
58
59 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregoraaa20962009-01-29 01:05:33 +000060 unsigned &Index, InitListExpr *StructuredList,
61 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000062 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregoraaa20962009-01-29 01:05:33 +000063 unsigned &Index, InitListExpr *StructuredList,
64 unsigned &StructuredIndex);
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,
69 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000070 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
71 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +000072 InitListExpr *StructuredList,
73 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000074 // FIXME: Does DeclType need to be a reference type?
75 void CheckScalarType(InitListExpr *IList, QualType &DeclType,
76 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +000077 InitListExpr *StructuredList,
78 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000079 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +000080 InitListExpr *StructuredList,
81 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000082 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
83 RecordDecl::field_iterator Field,
84 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +000085 InitListExpr *StructuredList,
86 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000087 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
88 llvm::APSInt elementIndex,
89 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +000090 InitListExpr *StructuredList,
91 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000092 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
93 DesignatedInitExpr::designators_iterator D,
94 QualType &CurrentObjectType,
95 RecordDecl::field_iterator *NextField,
96 llvm::APSInt *NextElementIndex,
97 unsigned &Index,
98 InitListExpr *StructuredList,
99 unsigned &StructuredIndex,
100 bool FinishSubobjectInit = true);
101 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
102 QualType CurrentObjectType,
103 InitListExpr *StructuredList,
104 unsigned StructuredIndex,
105 SourceRange InitRange);
Douglas Gregoraaa20962009-01-29 01:05:33 +0000106 void UpdateStructuredListElement(InitListExpr *StructuredList,
107 unsigned &StructuredIndex,
Douglas Gregor849afc32009-01-29 00:45:39 +0000108 Expr *expr);
109 int numArrayElements(QualType DeclType);
110 int numStructUnionElements(QualType DeclType);
111public:
112 InitListChecker(Sema *S, InitListExpr *IL, QualType &T);
113 bool HadError() { return hadError; }
114
115 // @brief Retrieves the fully-structured initializer list used for
116 // semantic analysis and code generation.
117 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
118};
Chris Lattner1aa25a72009-01-29 05:10:57 +0000119}
120
Douglas Gregor849afc32009-01-29 00:45:39 +0000121
Douglas Gregorf603b472009-01-28 21:54:33 +0000122/// Recursively replaces NULL values within the given initializer list
123/// with expressions that perform value-initialization of the
124/// appropriate type.
125static void fillInValueInitializations(ASTContext &Context, InitListExpr *ILE) {
126 assert((ILE->getType() != Context.VoidTy) && "Should not have void type");
127 if (const RecordType *RType = ILE->getType()->getAsRecordType()) {
128 unsigned Init = 0, NumInits = ILE->getNumInits();
129 for (RecordDecl::field_iterator Field = RType->getDecl()->field_begin(),
130 FieldEnd = RType->getDecl()->field_end();
131 Field != FieldEnd; ++Field) {
132 if (Field->isUnnamedBitfield())
133 continue;
134
135 if (Init >= NumInits)
136 break;
137
138 // FIXME: Check for fields with reference type in C++?
139 if (!ILE->getInit(Init))
140 ILE->setInit(Init,
141 new (Context) CXXZeroInitValueExpr(Field->getType(),
142 SourceLocation(),
143 SourceLocation()));
144 else if (InitListExpr *InnerILE = dyn_cast<InitListExpr>(ILE->getInit(Init)))
145 fillInValueInitializations(Context, InnerILE);
146 ++Init;
147 }
148
149 return;
150 }
151
152 QualType ElementType;
153
154 if (const ArrayType *AType = Context.getAsArrayType(ILE->getType()))
155 ElementType = AType->getElementType();
156 else if (const VectorType *VType = ILE->getType()->getAsVectorType())
157 ElementType = VType->getElementType();
158 else
159 ElementType = ILE->getType();
160
161 for (unsigned Init = 0, NumInits = ILE->getNumInits(); Init != NumInits;
162 ++Init) {
163 if (!ILE->getInit(Init))
164 ILE->setInit(Init, new (Context) CXXZeroInitValueExpr(ElementType,
165 SourceLocation(),
166 SourceLocation()));
Chris Lattner1aa25a72009-01-29 05:10:57 +0000167 else if (InitListExpr *InnerILE =dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregorf603b472009-01-28 21:54:33 +0000168 fillInValueInitializations(Context, InnerILE);
169 }
170}
171
Chris Lattner1aa25a72009-01-29 05:10:57 +0000172
Steve Naroffc4d4a482008-05-01 22:18:59 +0000173InitListChecker::InitListChecker(Sema *S, InitListExpr *IL, QualType &T) {
174 hadError = false;
175 SemaRef = S;
Eli Friedmand8535af2008-05-19 20:00:43 +0000176
Eli Friedman683cedf2008-05-19 19:16:24 +0000177 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000178 unsigned newStructuredIndex = 0;
179 FullyStructuredList
180 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, SourceRange());
181 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000182
Douglas Gregorf603b472009-01-28 21:54:33 +0000183 if (!hadError) {
184 fillInValueInitializations(SemaRef->Context, FullyStructuredList);
185 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000186}
187
188int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman46f81662008-05-25 13:22:35 +0000189 // FIXME: use a proper constant
190 int maxElements = 0x7FFFFFFF;
Chris Lattnera1923f62008-08-04 07:31:14 +0000191 if (const ConstantArrayType *CAT =
192 SemaRef->Context.getAsConstantArrayType(DeclType)) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000193 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
194 }
195 return maxElements;
196}
197
198int InitListChecker::numStructUnionElements(QualType DeclType) {
199 RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl();
Douglas Gregorf603b472009-01-28 21:54:33 +0000200 int InitializableMembers = 0;
201 for (RecordDecl::field_iterator Field = structDecl->field_begin(),
202 FieldEnd = structDecl->field_end();
203 Field != FieldEnd; ++Field) {
204 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
205 ++InitializableMembers;
206 }
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000207 if (structDecl->isUnion())
Eli Friedman9f5250b2008-05-25 14:03:31 +0000208 return std::min(InitializableMembers, 1);
209 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000210}
211
212void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregorf603b472009-01-28 21:54:33 +0000213 QualType T, unsigned &Index,
214 InitListExpr *StructuredList,
215 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000216 int maxElements = 0;
217
218 if (T->isArrayType())
219 maxElements = numArrayElements(T);
220 else if (T->isStructureType() || T->isUnionType())
221 maxElements = numStructUnionElements(T);
Eli Friedman683cedf2008-05-19 19:16:24 +0000222 else if (T->isVectorType())
223 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000224 else
225 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman683cedf2008-05-19 19:16:24 +0000226
Douglas Gregorf603b472009-01-28 21:54:33 +0000227 // FIXME: Perhaps we should move this warning elsewhere?
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000228 if (maxElements == 0) {
229 SemaRef->Diag(ParentIList->getInit(Index)->getLocStart(),
230 diag::err_implicit_empty_initializer);
Douglas Gregorf603b472009-01-28 21:54:33 +0000231 ++Index;
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000232 hadError = true;
233 return;
234 }
235
Douglas Gregorf603b472009-01-28 21:54:33 +0000236 // Build a structured initializer list corresponding to this subobject.
237 InitListExpr *StructuredSubobjectInitList
238 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
239 StructuredIndex,
240 ParentIList->getInit(Index)->getSourceRange());
241 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman683cedf2008-05-19 19:16:24 +0000242
Douglas Gregorf603b472009-01-28 21:54:33 +0000243 // Check the element types and build the structural subobject.
244 CheckListElementTypes(ParentIList, T, false, Index,
245 StructuredSubobjectInitList,
246 StructuredSubobjectInitIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000247}
248
Steve Naroff56099522008-05-06 00:23:44 +0000249void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregorf603b472009-01-28 21:54:33 +0000250 unsigned &Index,
251 InitListExpr *StructuredList,
252 unsigned &StructuredIndex) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000253 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregorf603b472009-01-28 21:54:33 +0000254 SyntacticToSemantic[IList] = StructuredList;
255 StructuredList->setSyntacticForm(IList);
256 CheckListElementTypes(IList, T, true, Index, StructuredList,
257 StructuredIndex);
Steve Naroff56099522008-05-06 00:23:44 +0000258 IList->setType(T);
Douglas Gregorf603b472009-01-28 21:54:33 +0000259 StructuredList->setType(T);
Eli Friedman46f81662008-05-25 13:22:35 +0000260 if (hadError)
261 return;
Eli Friedmand8535af2008-05-19 20:00:43 +0000262
Eli Friedman46f81662008-05-25 13:22:35 +0000263 if (Index < IList->getNumInits()) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000264 // We have leftover initializers
265 if (IList->getNumInits() > 0 &&
266 SemaRef->IsStringLiteralInit(IList->getInit(Index), T)) {
Eli Friedman71de9eb2008-05-19 20:12:18 +0000267 // Special-case
Eli Friedmand8535af2008-05-19 20:00:43 +0000268 SemaRef->Diag(IList->getInit(Index)->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000269 diag::err_excess_initializers_in_char_array_initializer)
270 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000271 hadError = true;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000272 } else if (!T->isIncompleteType()) {
273 // Don't warn for incomplete types, since we'll get an error elsewhere
Eli Friedmand8535af2008-05-19 20:00:43 +0000274 SemaRef->Diag(IList->getInit(Index)->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000275 diag::warn_excess_initializers)
276 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000277 }
278 }
Eli Friedman455f7622008-05-19 20:20:43 +0000279
Eli Friedman46f81662008-05-25 13:22:35 +0000280 if (T->isScalarType())
Chris Lattner9d2cf082008-11-19 05:27:50 +0000281 SemaRef->Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
282 << IList->getSourceRange();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000283}
284
Eli Friedman683cedf2008-05-19 19:16:24 +0000285void InitListChecker::CheckListElementTypes(InitListExpr *IList,
286 QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000287 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000288 unsigned &Index,
289 InitListExpr *StructuredList,
290 unsigned &StructuredIndex) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000291 if (DeclType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000292 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000293 } else if (DeclType->isVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000294 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000295 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000296 if (DeclType->isStructureType() || DeclType->isUnionType()) {
297 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
298 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000299 SubobjectIsDesignatorContext, Index,
300 StructuredList, StructuredIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000301 } else if (DeclType->isArrayType()) {
Douglas Gregor5a203a62009-01-23 16:54:12 +0000302 llvm::APSInt Zero(
303 SemaRef->Context.getTypeSize(SemaRef->Context.getSizeType()),
304 false);
Douglas Gregorf603b472009-01-28 21:54:33 +0000305 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
306 StructuredList, StructuredIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000307 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000308 else
Douglas Gregorf603b472009-01-28 21:54:33 +0000309 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffff5b3a82008-08-10 16:05:48 +0000310 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
311 // This type is invalid, issue a diagnostic.
Douglas Gregorf603b472009-01-28 21:54:33 +0000312 ++Index;
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000313 SemaRef->Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000314 << DeclType;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000315 hadError = true;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000316 } else {
317 // In C, all types are either scalars or aggregates, but
318 // additional handling is needed here for C++ (and possibly others?).
319 assert(0 && "Unsupported initializer type");
320 }
321}
322
Eli Friedman683cedf2008-05-19 19:16:24 +0000323void InitListChecker::CheckSubElementType(InitListExpr *IList,
324 QualType ElemType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000325 unsigned &Index,
326 InitListExpr *StructuredList,
327 unsigned &StructuredIndex) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000328 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000329 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
330 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000331 unsigned newStructuredIndex = 0;
332 InitListExpr *newStructuredList
333 = getStructuredSubobjectInit(IList, Index, ElemType,
334 StructuredList, StructuredIndex,
335 SubInitList->getSourceRange());
336 CheckExplicitInitList(SubInitList, ElemType, newIndex,
337 newStructuredList, newStructuredIndex);
338 ++StructuredIndex;
339 ++Index;
Eli Friedman683cedf2008-05-19 19:16:24 +0000340 } else if (StringLiteral *lit =
341 SemaRef->IsStringLiteralInit(expr, ElemType)) {
342 SemaRef->CheckStringLiteralInit(lit, ElemType);
Douglas Gregorf603b472009-01-28 21:54:33 +0000343 UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
344 ++Index;
Eli Friedmand8535af2008-05-19 20:00:43 +0000345 } else if (ElemType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000346 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedman683cedf2008-05-19 19:16:24 +0000347 } else if (expr->getType()->getAsRecordType() &&
Eli Friedman2ccfb512008-06-09 03:52:40 +0000348 SemaRef->Context.typesAreCompatible(
349 expr->getType().getUnqualifiedType(),
350 ElemType.getUnqualifiedType())) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000351 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
352 ++Index;
Eli Friedman683cedf2008-05-19 19:16:24 +0000353 // FIXME: Add checking
354 } else {
Douglas Gregorf603b472009-01-28 21:54:33 +0000355 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
356 StructuredIndex);
357 ++StructuredIndex;
358 }
Eli Friedman683cedf2008-05-19 19:16:24 +0000359}
360
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000361void InitListChecker::CheckScalarType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor36859eb2009-01-29 00:39:20 +0000362 unsigned &Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000363 InitListExpr *StructuredList,
364 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000365 if (Index < IList->getNumInits()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000366 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000367 if (isa<InitListExpr>(expr)) {
Eli Friedman71de9eb2008-05-19 20:12:18 +0000368 SemaRef->Diag(IList->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000369 diag::err_many_braces_around_scalar_init)
370 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000371 hadError = true;
372 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000373 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000374 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000375 } else if (isa<DesignatedInitExpr>(expr)) {
376 SemaRef->Diag(expr->getSourceRange().getBegin(),
377 diag::err_designator_for_scalar_init)
378 << DeclType << expr->getSourceRange();
379 hadError = true;
380 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000381 ++StructuredIndex;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000382 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000383 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000384
Eli Friedmand8535af2008-05-19 20:00:43 +0000385 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000386 if (SemaRef->CheckSingleInitializer(expr, DeclType, false))
Eli Friedman71de9eb2008-05-19 20:12:18 +0000387 hadError = true; // types weren't compatible.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000388 else if (savExpr != expr) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000389 // The type was promoted, update initializer list.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000390 IList->setInit(Index, expr);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000391 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000392 if (hadError)
393 ++StructuredIndex;
394 else
395 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000396 ++Index;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000397 } else {
Chris Lattner9d2cf082008-11-19 05:27:50 +0000398 SemaRef->Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
399 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000400 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000401 ++Index;
402 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000403 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000404 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000405}
406
407void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000408 unsigned &Index,
409 InitListExpr *StructuredList,
410 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000411 if (Index < IList->getNumInits()) {
412 const VectorType *VT = DeclType->getAsVectorType();
413 int maxElements = VT->getNumElements();
414 QualType elementType = VT->getElementType();
415
416 for (int i = 0; i < maxElements; ++i) {
417 // Don't attempt to go past the end of the init list
418 if (Index >= IList->getNumInits())
419 break;
Douglas Gregor36859eb2009-01-29 00:39:20 +0000420 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000421 StructuredList, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000422 }
423 }
424}
425
426void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000427 llvm::APSInt elementIndex,
428 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000429 unsigned &Index,
430 InitListExpr *StructuredList,
431 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000432 // Check for the special-case of initializing an array with a string.
433 if (Index < IList->getNumInits()) {
434 if (StringLiteral *lit =
435 SemaRef->IsStringLiteralInit(IList->getInit(Index), DeclType)) {
436 SemaRef->CheckStringLiteralInit(lit, DeclType);
Douglas Gregorf603b472009-01-28 21:54:33 +0000437 // We place the string literal directly into the resulting
438 // initializer list. This is the only place where the structure
439 // of the structured initializer list doesn't match exactly,
440 // because doing so would involve allocating one character
441 // constant for each string.
442 UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
443 StructuredList->resizeInits(SemaRef->Context, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000444 ++Index;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000445 return;
446 }
447 }
Chris Lattnera1923f62008-08-04 07:31:14 +0000448 if (const VariableArrayType *VAT =
449 SemaRef->Context.getAsVariableArrayType(DeclType)) {
Eli Friedman46f81662008-05-25 13:22:35 +0000450 // Check for VLAs; in standard C it would be possible to check this
451 // earlier, but I don't know where clang accepts VLAs (gcc accepts
452 // them in all sorts of strange places).
453 SemaRef->Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000454 diag::err_variable_object_no_init)
455 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman46f81662008-05-25 13:22:35 +0000456 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000457 ++Index;
458 ++StructuredIndex;
Eli Friedman46f81662008-05-25 13:22:35 +0000459 return;
460 }
461
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000462 // We might know the maximum number of elements in advance.
Douglas Gregorf603b472009-01-28 21:54:33 +0000463 llvm::APSInt maxElements(elementIndex.getBitWidth(),
464 elementIndex.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000465 bool maxElementsKnown = false;
466 if (const ConstantArrayType *CAT =
467 SemaRef->Context.getAsConstantArrayType(DeclType)) {
468 maxElements = CAT->getSize();
Douglas Gregor5a203a62009-01-23 16:54:12 +0000469 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000470 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000471 maxElementsKnown = true;
472 }
473
Chris Lattnera1923f62008-08-04 07:31:14 +0000474 QualType elementType = SemaRef->Context.getAsArrayType(DeclType)
475 ->getElementType();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000476 while (Index < IList->getNumInits()) {
477 Expr *Init = IList->getInit(Index);
478 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000479 // If we're not the subobject that matches up with the '{' for
480 // the designator, we shouldn't be handling the
481 // designator. Return immediately.
482 if (!SubobjectIsDesignatorContext)
483 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000484
Douglas Gregor710f6d42009-01-22 23:26:18 +0000485 // Handle this designated initializer. elementIndex will be
486 // updated to be the next array element we'll initialize.
487 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000488 DeclType, 0, &elementIndex, Index,
489 StructuredList, StructuredIndex)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000490 hadError = true;
491 continue;
492 }
493
Douglas Gregor5a203a62009-01-23 16:54:12 +0000494 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
495 maxElements.extend(elementIndex.getBitWidth());
496 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
497 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000498 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor5a203a62009-01-23 16:54:12 +0000499
Douglas Gregor710f6d42009-01-22 23:26:18 +0000500 // If the array is of incomplete type, keep track of the number of
501 // elements in the initializer.
502 if (!maxElementsKnown && elementIndex > maxElements)
503 maxElements = elementIndex;
504
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000505 continue;
506 }
507
508 // If we know the maximum number of elements, and we've already
509 // hit it, stop consuming elements in the initializer list.
510 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000511 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000512
513 // Check this element.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000514 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000515 StructuredList, StructuredIndex);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000516 ++elementIndex;
517
518 // If the array is of incomplete type, keep track of the number of
519 // elements in the initializer.
520 if (!maxElementsKnown && elementIndex > maxElements)
521 maxElements = elementIndex;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000522 }
523 if (DeclType->isIncompleteArrayType()) {
524 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000525 // be calculated here.
Douglas Gregor69722702009-01-23 18:58:42 +0000526 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000527 if (maxElements == Zero) {
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000528 // Sizing an array implicitly to zero is not allowed by ISO C,
529 // but is supported by GNU.
Steve Naroffc4d4a482008-05-01 22:18:59 +0000530 SemaRef->Diag(IList->getLocStart(),
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000531 diag::ext_typecheck_zero_array_size);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000532 }
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000533
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000534 DeclType = SemaRef->Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000535 ArrayType::Normal, 0);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000536 }
537}
538
539void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
540 QualType DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000541 RecordDecl::field_iterator Field,
542 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000543 unsigned &Index,
544 InitListExpr *StructuredList,
545 unsigned &StructuredIndex) {
Eli Friedman683cedf2008-05-19 19:16:24 +0000546 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000547
Eli Friedman683cedf2008-05-19 19:16:24 +0000548 // If the record is invalid, some of it's members are invalid. To avoid
549 // confusion, we forgo checking the intializer for the entire record.
550 if (structDecl->isInvalidDecl()) {
551 hadError = true;
552 return;
553 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000554 // If structDecl is a forward declaration, this loop won't do
555 // anything except look at designated initializers; That's okay,
556 // because an error should get printed out elsewhere. It might be
557 // worthwhile to skip over the rest of the initializer, though.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000558 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor710f6d42009-01-22 23:26:18 +0000559 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000560 while (Index < IList->getNumInits()) {
561 Expr *Init = IList->getInit(Index);
562
563 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000564 // If we're not the subobject that matches up with the '{' for
565 // the designator, we shouldn't be handling the
566 // designator. Return immediately.
567 if (!SubobjectIsDesignatorContext)
568 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000569
Douglas Gregor710f6d42009-01-22 23:26:18 +0000570 // Handle this designated initializer. Field will be updated to
571 // the next field that we'll be initializing.
572 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000573 DeclType, &Field, 0, Index,
574 StructuredList, StructuredIndex))
Douglas Gregor710f6d42009-01-22 23:26:18 +0000575 hadError = true;
576
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000577 continue;
578 }
579
580 if (Field == FieldEnd) {
581 // We've run out of fields. We're done.
582 break;
583 }
584
Douglas Gregor8acb7272008-12-11 16:49:14 +0000585 // If we've hit the flexible array member at the end, we're done.
586 if (Field->getType()->isIncompleteArrayType())
587 break;
588
Douglas Gregorf603b472009-01-28 21:54:33 +0000589 if (!Field->getIdentifier() && Field->isBitField()) {
590 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000591 ++Field;
Eli Friedman683cedf2008-05-19 19:16:24 +0000592 continue;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000593 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000594
Douglas Gregor36859eb2009-01-29 00:39:20 +0000595 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000596 StructuredList, StructuredIndex);
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000597 if (DeclType->isUnionType())
Eli Friedman683cedf2008-05-19 19:16:24 +0000598 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000599
600 ++Field;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000601 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000602
Eli Friedman683cedf2008-05-19 19:16:24 +0000603 // FIXME: Implement flexible array initialization GCC extension (it's a
604 // really messy extension to implement, unfortunately...the necessary
605 // information isn't actually even here!)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000606}
Steve Naroffc4d4a482008-05-01 22:18:59 +0000607
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000608/// @brief Check the well-formedness of a C99 designated initializer.
609///
610/// Determines whether the designated initializer @p DIE, which
611/// resides at the given @p Index within the initializer list @p
612/// IList, is well-formed for a current object of type @p DeclType
613/// (C99 6.7.8). The actual subobject that this designator refers to
614/// within the current subobject is returned in either
Douglas Gregorf603b472009-01-28 21:54:33 +0000615/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000616///
617/// @param IList The initializer list in which this designated
618/// initializer occurs.
619///
620/// @param DIE The designated initializer and its initialization
621/// expression.
622///
623/// @param DeclType The type of the "current object" (C99 6.7.8p17),
624/// into which the designation in @p DIE should refer.
625///
Douglas Gregor710f6d42009-01-22 23:26:18 +0000626/// @param NextField If non-NULL and the first designator in @p DIE is
627/// a field, this will be set to the field declaration corresponding
628/// to the field named by the designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000629///
Douglas Gregor710f6d42009-01-22 23:26:18 +0000630/// @param NextElementIndex If non-NULL and the first designator in @p
631/// DIE is an array designator or GNU array-range designator, this
632/// will be set to the last index initialized by this designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000633///
634/// @param Index Index into @p IList where the designated initializer
635/// @p DIE occurs.
636///
Douglas Gregorf603b472009-01-28 21:54:33 +0000637/// @param StructuredList The initializer list expression that
638/// describes all of the subobject initializers in the order they'll
639/// actually be initialized.
640///
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000641/// @returns true if there was an error, false otherwise.
Douglas Gregor710f6d42009-01-22 23:26:18 +0000642bool
643InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
644 DesignatedInitExpr *DIE,
645 DesignatedInitExpr::designators_iterator D,
646 QualType &CurrentObjectType,
647 RecordDecl::field_iterator *NextField,
648 llvm::APSInt *NextElementIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +0000649 unsigned &Index,
650 InitListExpr *StructuredList,
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000651 unsigned &StructuredIndex,
652 bool FinishSubobjectInit) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000653 if (D == DIE->designators_end()) {
654 // Check the actual initialization for the designated object type.
655 bool prevHadError = hadError;
Douglas Gregor36859eb2009-01-29 00:39:20 +0000656
657 // Temporarily remove the designator expression from the
658 // initializer list that the child calls see, so that we don't try
659 // to re-process the designator.
660 unsigned OldIndex = Index;
661 IList->setInit(OldIndex, DIE->getInit());
662
663 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000664 StructuredList, StructuredIndex);
Douglas Gregor36859eb2009-01-29 00:39:20 +0000665
666 // Restore the designated initializer expression in the syntactic
667 // form of the initializer list.
668 if (IList->getInit(OldIndex) != DIE->getInit())
669 DIE->setInit(IList->getInit(OldIndex));
670 IList->setInit(OldIndex, DIE);
671
Douglas Gregor710f6d42009-01-22 23:26:18 +0000672 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000673 }
674
Douglas Gregorf603b472009-01-28 21:54:33 +0000675 bool IsFirstDesignator = (D == DIE->designators_begin());
676 assert((IsFirstDesignator || StructuredList) &&
677 "Need a non-designated initializer list to start from");
678
679 // Determine the structural initializer list that corresponds to the
680 // current subobject.
681 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
682 : getStructuredSubobjectInit(IList, Index, CurrentObjectType, StructuredList,
683 StructuredIndex,
684 SourceRange(D->getStartLocation(),
685 DIE->getSourceRange().getEnd()));
686 assert(StructuredList && "Expected a structured initializer list");
687
Douglas Gregor710f6d42009-01-22 23:26:18 +0000688 if (D->isFieldDesignator()) {
689 // C99 6.7.8p7:
690 //
691 // If a designator has the form
692 //
693 // . identifier
694 //
695 // then the current object (defined below) shall have
696 // structure or union type and the identifier shall be the
697 // name of a member of that type.
698 const RecordType *RT = CurrentObjectType->getAsRecordType();
699 if (!RT) {
700 SourceLocation Loc = D->getDotLoc();
701 if (Loc.isInvalid())
702 Loc = D->getFieldLoc();
703 SemaRef->Diag(Loc, diag::err_field_designator_non_aggr)
704 << SemaRef->getLangOptions().CPlusPlus << CurrentObjectType;
705 ++Index;
706 return true;
707 }
708
Douglas Gregorf603b472009-01-28 21:54:33 +0000709 // Note: we perform a linear search of the fields here, despite
710 // the fact that we have a faster lookup method, because we always
711 // need to compute the field's index.
Douglas Gregor710f6d42009-01-22 23:26:18 +0000712 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregorf603b472009-01-28 21:54:33 +0000713 unsigned FieldIndex = 0;
714 RecordDecl::field_iterator Field = RT->getDecl()->field_begin(),
715 FieldEnd = RT->getDecl()->field_end();
716 for (; Field != FieldEnd; ++Field) {
717 if (Field->isUnnamedBitfield())
718 continue;
719
720 if (Field->getIdentifier() == FieldName)
721 break;
722
723 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000724 }
725
Douglas Gregorf603b472009-01-28 21:54:33 +0000726 if (Field == FieldEnd) {
727 // We did not find the field we're looking for. Produce a
728 // suitable diagnostic and return a failure.
729 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
730 if (Lookup.first == Lookup.second) {
731 // Name lookup didn't find anything.
732 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
733 << FieldName << CurrentObjectType;
734 } else {
735 // Name lookup found something, but it wasn't a field.
736 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
737 << FieldName;
738 SemaRef->Diag((*Lookup.first)->getLocation(),
739 diag::note_field_designator_found);
740 }
741
742 ++Index;
743 return true;
744 } else if (cast<RecordDecl>((*Field)->getDeclContext())
745 ->isAnonymousStructOrUnion()) {
746 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_anon_class)
747 << FieldName
748 << (cast<RecordDecl>((*Field)->getDeclContext())->isUnion()? 2 :
749 (int)SemaRef->getLangOptions().CPlusPlus);
750 SemaRef->Diag((*Field)->getLocation(), diag::note_field_designator_found);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000751 ++Index;
752 return true;
753 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000754
755 // All of the fields of a union are located at the same place in
756 // the initializer list.
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000757 if (RT->getDecl()->isUnion())
Douglas Gregorf603b472009-01-28 21:54:33 +0000758 FieldIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000759
Douglas Gregor710f6d42009-01-22 23:26:18 +0000760 // Update the designator with the field declaration.
Douglas Gregorf603b472009-01-28 21:54:33 +0000761 D->setField(*Field);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000762
Douglas Gregorf603b472009-01-28 21:54:33 +0000763 // Make sure that our non-designated initializer list has space
764 // for a subobject corresponding to this field.
765 if (FieldIndex >= StructuredList->getNumInits())
766 StructuredList->resizeInits(SemaRef->Context, FieldIndex + 1);
767
Douglas Gregor710f6d42009-01-22 23:26:18 +0000768 // Recurse to check later designated subobjects.
Douglas Gregorf603b472009-01-28 21:54:33 +0000769 QualType FieldType = (*Field)->getType();
770 unsigned newStructuredIndex = FieldIndex;
771 if (CheckDesignatedInitializer(IList, DIE, ++D, FieldType, 0, 0, Index,
772 StructuredList, newStructuredIndex))
Douglas Gregor710f6d42009-01-22 23:26:18 +0000773 return true;
774
775 // Find the position of the next field to be initialized in this
776 // subobject.
Douglas Gregor710f6d42009-01-22 23:26:18 +0000777 ++Field;
Douglas Gregorf603b472009-01-28 21:54:33 +0000778 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000779
780 // If this the first designator, our caller will continue checking
781 // the rest of this struct/class/union subobject.
782 if (IsFirstDesignator) {
783 if (NextField)
784 *NextField = Field;
Douglas Gregorf603b472009-01-28 21:54:33 +0000785 StructuredIndex = FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000786 return false;
787 }
788
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000789 if (!FinishSubobjectInit)
790 return false;
791
Douglas Gregor710f6d42009-01-22 23:26:18 +0000792 // Check the remaining fields within this class/struct/union subobject.
793 bool prevHadError = hadError;
Douglas Gregorf603b472009-01-28 21:54:33 +0000794 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
795 StructuredList, FieldIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000796 return hadError && !prevHadError;
797 }
798
799 // C99 6.7.8p6:
800 //
801 // If a designator has the form
802 //
803 // [ constant-expression ]
804 //
805 // then the current object (defined below) shall have array
806 // type and the expression shall be an integer constant
807 // expression. If the array is of unknown size, any
808 // nonnegative value is valid.
809 //
810 // Additionally, cope with the GNU extension that permits
811 // designators of the form
812 //
813 // [ constant-expression ... constant-expression ]
814 const ArrayType *AT = SemaRef->Context.getAsArrayType(CurrentObjectType);
815 if (!AT) {
816 SemaRef->Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
817 << CurrentObjectType;
818 ++Index;
819 return true;
820 }
821
822 Expr *IndexExpr = 0;
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000823 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
824 if (D->isArrayDesignator()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000825 IndexExpr = DIE->getArrayIndex(*D);
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000826
827 bool ConstExpr
828 = IndexExpr->isIntegerConstantExpr(DesignatedStartIndex, SemaRef->Context);
829 assert(ConstExpr && "Expression must be constant"); (void)ConstExpr;
830
831 DesignatedEndIndex = DesignatedStartIndex;
832 } else {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000833 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000834
835 bool StartConstExpr
836 = DIE->getArrayRangeStart(*D)->isIntegerConstantExpr(DesignatedStartIndex,
837 SemaRef->Context);
838 assert(StartConstExpr && "Expression must be constant"); (void)StartConstExpr;
839
840 bool EndConstExpr
841 = DIE->getArrayRangeEnd(*D)->isIntegerConstantExpr(DesignatedEndIndex,
842 SemaRef->Context);
843 assert(EndConstExpr && "Expression must be constant"); (void)EndConstExpr;
844
Douglas Gregor710f6d42009-01-22 23:26:18 +0000845 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000846
847 if (DesignatedStartIndex.getZExtValue() != DesignatedEndIndex.getZExtValue())
848 SemaRef->Diag(D->getEllipsisLoc(),
849 diag::warn_gnu_array_range_designator_side_effects)
850 << SourceRange(D->getLBracketLoc(), D->getRBracketLoc());
Douglas Gregor710f6d42009-01-22 23:26:18 +0000851 }
852
Douglas Gregor710f6d42009-01-22 23:26:18 +0000853 if (isa<ConstantArrayType>(AT)) {
854 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000855 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
856 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
857 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
858 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
859 if (DesignatedEndIndex >= MaxElements) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000860 SemaRef->Diag(IndexExpr->getSourceRange().getBegin(),
861 diag::err_array_designator_too_large)
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000862 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor710f6d42009-01-22 23:26:18 +0000863 << IndexExpr->getSourceRange();
864 ++Index;
865 return true;
866 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000867 } else {
868 // Make sure the bit-widths and signedness match.
869 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
870 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
871 else if (DesignatedStartIndex.getBitWidth() < DesignatedEndIndex.getBitWidth())
872 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
873 DesignatedStartIndex.setIsUnsigned(true);
874 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000875 }
876
Douglas Gregorf603b472009-01-28 21:54:33 +0000877 // Make sure that our non-designated initializer list has space
878 // for a subobject corresponding to this array element.
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000879 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
880 StructuredList->resizeInits(SemaRef->Context,
881 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +0000882
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000883 // Repeatedly perform subobject initializations in the range
884 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor710f6d42009-01-22 23:26:18 +0000885
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000886 // Move to the next designator
887 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
888 unsigned OldIndex = Index;
889 ++D;
890 while (DesignatedStartIndex <= DesignatedEndIndex) {
891 // Recurse to check later designated subobjects.
892 QualType ElementType = AT->getElementType();
893 Index = OldIndex;
894 if (CheckDesignatedInitializer(IList, DIE, D, ElementType, 0, 0, Index,
895 StructuredList, ElementIndex,
896 (DesignatedStartIndex == DesignatedEndIndex)))
897 return true;
898
899 // Move to the next index in the array that we'll be initializing.
900 ++DesignatedStartIndex;
901 ElementIndex = DesignatedStartIndex.getZExtValue();
902 }
Douglas Gregor710f6d42009-01-22 23:26:18 +0000903
904 // If this the first designator, our caller will continue checking
905 // the rest of this array subobject.
906 if (IsFirstDesignator) {
907 if (NextElementIndex)
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000908 *NextElementIndex = DesignatedStartIndex;
Douglas Gregorf603b472009-01-28 21:54:33 +0000909 StructuredIndex = ElementIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000910 return false;
911 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000912
913 if (!FinishSubobjectInit)
914 return false;
915
Douglas Gregor710f6d42009-01-22 23:26:18 +0000916 // Check the remaining elements within this array subobject.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000917 bool prevHadError = hadError;
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000918 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, true, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000919 StructuredList, ElementIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000920 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000921}
922
Douglas Gregorf603b472009-01-28 21:54:33 +0000923// Get the structured initializer list for a subobject of type
924// @p CurrentObjectType.
925InitListExpr *
926InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
927 QualType CurrentObjectType,
928 InitListExpr *StructuredList,
929 unsigned StructuredIndex,
930 SourceRange InitRange) {
931 Expr *ExistingInit = 0;
932 if (!StructuredList)
933 ExistingInit = SyntacticToSemantic[IList];
934 else if (StructuredIndex < StructuredList->getNumInits())
935 ExistingInit = StructuredList->getInit(StructuredIndex);
936
937 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
938 return Result;
939
940 if (ExistingInit) {
941 // We are creating an initializer list that initializes the
942 // subobjects of the current object, but there was already an
943 // initialization that completely initialized the current
944 // subobject, e.g., by a compound literal:
945 //
946 // struct X { int a, b; };
947 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
948 //
949 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
950 // designated initializer re-initializes the whole
951 // subobject [0], overwriting previous initializers.
952 SemaRef->Diag(InitRange.getBegin(), diag::warn_subobject_initializer_overrides)
953 << InitRange;
954 SemaRef->Diag(ExistingInit->getSourceRange().getBegin(),
955 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +0000956 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +0000957 << ExistingInit->getSourceRange();
958 }
959
960 InitListExpr *Result
961 = new (SemaRef->Context) InitListExpr(SourceLocation(), 0, 0,
962 SourceLocation());
963 Result->setType(CurrentObjectType);
964
965 // Link this new initializer list into the structured initializer
966 // lists.
967 if (StructuredList)
968 StructuredList->updateInit(StructuredIndex, Result);
969 else {
970 Result->setSyntacticForm(IList);
971 SyntacticToSemantic[IList] = Result;
972 }
973
974 return Result;
975}
976
977/// Update the initializer at index @p StructuredIndex within the
978/// structured initializer list to the value @p expr.
979void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
980 unsigned &StructuredIndex,
981 Expr *expr) {
982 // No structured initializer list to update
983 if (!StructuredList)
984 return;
985
986 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
987 // This initializer overwrites a previous initializer. Warn.
988 SemaRef->Diag(expr->getSourceRange().getBegin(),
989 diag::warn_initializer_overrides)
990 << expr->getSourceRange();
991 SemaRef->Diag(PrevInit->getSourceRange().getBegin(),
992 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +0000993 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +0000994 << PrevInit->getSourceRange();
995 }
996
997 ++StructuredIndex;
998}
999
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001000/// Check that the given Index expression is a valid array designator
1001/// value. This is essentailly just a wrapper around
1002/// Expr::isIntegerConstantExpr that also checks for negative values
1003/// and produces a reasonable diagnostic if there is a
1004/// failure. Returns true if there was an error, false otherwise. If
1005/// everything went okay, Value will receive the value of the constant
1006/// expression.
1007static bool
1008CheckArrayDesignatorExpr(Sema &Self, Expr *Index, llvm::APSInt &Value) {
1009 SourceLocation Loc = Index->getSourceRange().getBegin();
1010
1011 // Make sure this is an integer constant expression.
1012 if (!Index->isIntegerConstantExpr(Value, Self.Context, &Loc))
1013 return Self.Diag(Loc, diag::err_array_designator_nonconstant)
1014 << Index->getSourceRange();
1015
1016 // Make sure this constant expression is non-negative.
Douglas Gregor69722702009-01-23 18:58:42 +00001017 llvm::APSInt Zero(llvm::APSInt::getNullValue(Value.getBitWidth()),
1018 Value.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001019 if (Value < Zero)
1020 return Self.Diag(Loc, diag::err_array_designator_negative)
1021 << Value.toString(10) << Index->getSourceRange();
1022
Douglas Gregore498e372009-01-23 21:04:18 +00001023 Value.setIsUnsigned(true);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001024 return false;
1025}
1026
1027Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1028 SourceLocation Loc,
1029 bool UsedColonSyntax,
1030 OwningExprResult Init) {
1031 typedef DesignatedInitExpr::Designator ASTDesignator;
1032
1033 bool Invalid = false;
1034 llvm::SmallVector<ASTDesignator, 32> Designators;
1035 llvm::SmallVector<Expr *, 32> InitExpressions;
1036
1037 // Build designators and check array designator expressions.
1038 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1039 const Designator &D = Desig.getDesignator(Idx);
1040 switch (D.getKind()) {
1041 case Designator::FieldDesignator:
1042 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1043 D.getFieldLoc()));
1044 break;
1045
1046 case Designator::ArrayDesignator: {
1047 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1048 llvm::APSInt IndexValue;
1049 if (CheckArrayDesignatorExpr(*this, Index, IndexValue))
1050 Invalid = true;
1051 else {
1052 Designators.push_back(ASTDesignator(InitExpressions.size(),
1053 D.getLBracketLoc(),
1054 D.getRBracketLoc()));
1055 InitExpressions.push_back(Index);
1056 }
1057 break;
1058 }
1059
1060 case Designator::ArrayRangeDesignator: {
1061 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1062 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1063 llvm::APSInt StartValue;
1064 llvm::APSInt EndValue;
1065 if (CheckArrayDesignatorExpr(*this, StartIndex, StartValue) ||
1066 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))
1067 Invalid = true;
Douglas Gregorea0528d2009-01-23 22:22:29 +00001068 else {
1069 // Make sure we're comparing values with the same bit width.
1070 if (StartValue.getBitWidth() > EndValue.getBitWidth())
1071 EndValue.extend(StartValue.getBitWidth());
1072 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1073 StartValue.extend(EndValue.getBitWidth());
1074
1075 if (EndValue < StartValue) {
1076 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1077 << StartValue.toString(10) << EndValue.toString(10)
1078 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1079 Invalid = true;
1080 } else {
1081 Designators.push_back(ASTDesignator(InitExpressions.size(),
1082 D.getLBracketLoc(),
1083 D.getEllipsisLoc(),
1084 D.getRBracketLoc()));
1085 InitExpressions.push_back(StartIndex);
1086 InitExpressions.push_back(EndIndex);
1087 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001088 }
1089 break;
1090 }
1091 }
1092 }
1093
1094 if (Invalid || Init.isInvalid())
1095 return ExprError();
1096
1097 // Clear out the expressions within the designation.
1098 Desig.ClearExprs(*this);
1099
1100 DesignatedInitExpr *DIE
1101 = DesignatedInitExpr::Create(Context, &Designators[0], Designators.size(),
1102 &InitExpressions[0], InitExpressions.size(),
1103 Loc, UsedColonSyntax,
1104 static_cast<Expr *>(Init.release()));
1105 return Owned(DIE);
1106}
Douglas Gregor849afc32009-01-29 00:45:39 +00001107
1108bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
1109 InitListChecker CheckInitList(this, InitList, DeclType);
1110 if (!CheckInitList.HadError())
1111 InitList = CheckInitList.getFullyStructuredList();
1112
1113 return CheckInitList.HadError();
1114}