blob: f810a86250318402f8199bc6e237663eece9ced0 [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.
Douglas Gregor849afc32009-01-29 00:45:39 +000052class InitListChecker {
53 Sema *SemaRef;
54 bool hadError;
55 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
56 InitListExpr *FullyStructuredList;
57
58 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregoraaa20962009-01-29 01:05:33 +000059 unsigned &Index, InitListExpr *StructuredList,
60 unsigned &StructuredIndex);
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,
63 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000064 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
65 bool SubobjectIsDesignatorContext,
66 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +000067 InitListExpr *StructuredList,
68 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000069 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
70 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +000071 InitListExpr *StructuredList,
72 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000073 // FIXME: Does DeclType need to be a reference type?
74 void CheckScalarType(InitListExpr *IList, QualType &DeclType,
75 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +000076 InitListExpr *StructuredList,
77 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000078 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +000079 InitListExpr *StructuredList,
80 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000081 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
82 RecordDecl::field_iterator Field,
83 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +000084 InitListExpr *StructuredList,
85 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000086 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
87 llvm::APSInt elementIndex,
88 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +000089 InitListExpr *StructuredList,
90 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000091 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
92 DesignatedInitExpr::designators_iterator D,
93 QualType &CurrentObjectType,
94 RecordDecl::field_iterator *NextField,
95 llvm::APSInt *NextElementIndex,
96 unsigned &Index,
97 InitListExpr *StructuredList,
98 unsigned &StructuredIndex,
99 bool FinishSubobjectInit = true);
100 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
101 QualType CurrentObjectType,
102 InitListExpr *StructuredList,
103 unsigned StructuredIndex,
104 SourceRange InitRange);
Douglas Gregoraaa20962009-01-29 01:05:33 +0000105 void UpdateStructuredListElement(InitListExpr *StructuredList,
106 unsigned &StructuredIndex,
Douglas Gregor849afc32009-01-29 00:45:39 +0000107 Expr *expr);
108 int numArrayElements(QualType DeclType);
109 int numStructUnionElements(QualType DeclType);
110public:
111 InitListChecker(Sema *S, InitListExpr *IL, QualType &T);
112 bool HadError() { return hadError; }
113
114 // @brief Retrieves the fully-structured initializer list used for
115 // semantic analysis and code generation.
116 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
117};
118
Douglas Gregorf603b472009-01-28 21:54:33 +0000119/// Recursively replaces NULL values within the given initializer list
120/// with expressions that perform value-initialization of the
121/// appropriate type.
122static void fillInValueInitializations(ASTContext &Context, InitListExpr *ILE) {
123 assert((ILE->getType() != Context.VoidTy) && "Should not have void type");
124 if (const RecordType *RType = ILE->getType()->getAsRecordType()) {
125 unsigned Init = 0, NumInits = ILE->getNumInits();
126 for (RecordDecl::field_iterator Field = RType->getDecl()->field_begin(),
127 FieldEnd = RType->getDecl()->field_end();
128 Field != FieldEnd; ++Field) {
129 if (Field->isUnnamedBitfield())
130 continue;
131
132 if (Init >= NumInits)
133 break;
134
135 // FIXME: Check for fields with reference type in C++?
136 if (!ILE->getInit(Init))
137 ILE->setInit(Init,
138 new (Context) CXXZeroInitValueExpr(Field->getType(),
139 SourceLocation(),
140 SourceLocation()));
141 else if (InitListExpr *InnerILE = dyn_cast<InitListExpr>(ILE->getInit(Init)))
142 fillInValueInitializations(Context, InnerILE);
143 ++Init;
144 }
145
146 return;
147 }
148
149 QualType ElementType;
150
151 if (const ArrayType *AType = Context.getAsArrayType(ILE->getType()))
152 ElementType = AType->getElementType();
153 else if (const VectorType *VType = ILE->getType()->getAsVectorType())
154 ElementType = VType->getElementType();
155 else
156 ElementType = ILE->getType();
157
158 for (unsigned Init = 0, NumInits = ILE->getNumInits(); Init != NumInits;
159 ++Init) {
160 if (!ILE->getInit(Init))
161 ILE->setInit(Init, new (Context) CXXZeroInitValueExpr(ElementType,
162 SourceLocation(),
163 SourceLocation()));
164 else if (InitListExpr *InnerILE = dyn_cast<InitListExpr>(ILE->getInit(Init)))
165 fillInValueInitializations(Context, InnerILE);
166 }
167}
168
Steve Naroffc4d4a482008-05-01 22:18:59 +0000169InitListChecker::InitListChecker(Sema *S, InitListExpr *IL, QualType &T) {
170 hadError = false;
171 SemaRef = S;
Eli Friedmand8535af2008-05-19 20:00:43 +0000172
Eli Friedman683cedf2008-05-19 19:16:24 +0000173 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000174 unsigned newStructuredIndex = 0;
175 FullyStructuredList
176 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, SourceRange());
177 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000178
Douglas Gregorf603b472009-01-28 21:54:33 +0000179 if (!hadError) {
180 fillInValueInitializations(SemaRef->Context, FullyStructuredList);
181 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000182}
183
184int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman46f81662008-05-25 13:22:35 +0000185 // FIXME: use a proper constant
186 int maxElements = 0x7FFFFFFF;
Chris Lattnera1923f62008-08-04 07:31:14 +0000187 if (const ConstantArrayType *CAT =
188 SemaRef->Context.getAsConstantArrayType(DeclType)) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000189 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
190 }
191 return maxElements;
192}
193
194int InitListChecker::numStructUnionElements(QualType DeclType) {
195 RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl();
Douglas Gregorf603b472009-01-28 21:54:33 +0000196 int InitializableMembers = 0;
197 for (RecordDecl::field_iterator Field = structDecl->field_begin(),
198 FieldEnd = structDecl->field_end();
199 Field != FieldEnd; ++Field) {
200 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
201 ++InitializableMembers;
202 }
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000203 if (structDecl->isUnion())
Eli Friedman9f5250b2008-05-25 14:03:31 +0000204 return std::min(InitializableMembers, 1);
205 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000206}
207
208void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregorf603b472009-01-28 21:54:33 +0000209 QualType T, unsigned &Index,
210 InitListExpr *StructuredList,
211 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000212 int maxElements = 0;
213
214 if (T->isArrayType())
215 maxElements = numArrayElements(T);
216 else if (T->isStructureType() || T->isUnionType())
217 maxElements = numStructUnionElements(T);
Eli Friedman683cedf2008-05-19 19:16:24 +0000218 else if (T->isVectorType())
219 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000220 else
221 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman683cedf2008-05-19 19:16:24 +0000222
Douglas Gregorf603b472009-01-28 21:54:33 +0000223 // FIXME: Perhaps we should move this warning elsewhere?
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000224 if (maxElements == 0) {
225 SemaRef->Diag(ParentIList->getInit(Index)->getLocStart(),
226 diag::err_implicit_empty_initializer);
Douglas Gregorf603b472009-01-28 21:54:33 +0000227 ++Index;
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000228 hadError = true;
229 return;
230 }
231
Douglas Gregorf603b472009-01-28 21:54:33 +0000232 // Build a structured initializer list corresponding to this subobject.
233 InitListExpr *StructuredSubobjectInitList
234 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
235 StructuredIndex,
236 ParentIList->getInit(Index)->getSourceRange());
237 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman683cedf2008-05-19 19:16:24 +0000238
Douglas Gregorf603b472009-01-28 21:54:33 +0000239 // Check the element types and build the structural subobject.
240 CheckListElementTypes(ParentIList, T, false, Index,
241 StructuredSubobjectInitList,
242 StructuredSubobjectInitIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000243}
244
Steve Naroff56099522008-05-06 00:23:44 +0000245void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregorf603b472009-01-28 21:54:33 +0000246 unsigned &Index,
247 InitListExpr *StructuredList,
248 unsigned &StructuredIndex) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000249 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregorf603b472009-01-28 21:54:33 +0000250 SyntacticToSemantic[IList] = StructuredList;
251 StructuredList->setSyntacticForm(IList);
252 CheckListElementTypes(IList, T, true, Index, StructuredList,
253 StructuredIndex);
Steve Naroff56099522008-05-06 00:23:44 +0000254 IList->setType(T);
Douglas Gregorf603b472009-01-28 21:54:33 +0000255 StructuredList->setType(T);
Eli Friedman46f81662008-05-25 13:22:35 +0000256 if (hadError)
257 return;
Eli Friedmand8535af2008-05-19 20:00:43 +0000258
Eli Friedman46f81662008-05-25 13:22:35 +0000259 if (Index < IList->getNumInits()) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000260 // We have leftover initializers
261 if (IList->getNumInits() > 0 &&
262 SemaRef->IsStringLiteralInit(IList->getInit(Index), T)) {
Eli Friedman71de9eb2008-05-19 20:12:18 +0000263 // Special-case
Eli Friedmand8535af2008-05-19 20:00:43 +0000264 SemaRef->Diag(IList->getInit(Index)->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000265 diag::err_excess_initializers_in_char_array_initializer)
266 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000267 hadError = true;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000268 } else if (!T->isIncompleteType()) {
269 // Don't warn for incomplete types, since we'll get an error elsewhere
Eli Friedmand8535af2008-05-19 20:00:43 +0000270 SemaRef->Diag(IList->getInit(Index)->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000271 diag::warn_excess_initializers)
272 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000273 }
274 }
Eli Friedman455f7622008-05-19 20:20:43 +0000275
Eli Friedman46f81662008-05-25 13:22:35 +0000276 if (T->isScalarType())
Chris Lattner9d2cf082008-11-19 05:27:50 +0000277 SemaRef->Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
278 << IList->getSourceRange();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000279}
280
Eli Friedman683cedf2008-05-19 19:16:24 +0000281void InitListChecker::CheckListElementTypes(InitListExpr *IList,
282 QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000283 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000284 unsigned &Index,
285 InitListExpr *StructuredList,
286 unsigned &StructuredIndex) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000287 if (DeclType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000288 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000289 } else if (DeclType->isVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000290 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000291 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000292 if (DeclType->isStructureType() || DeclType->isUnionType()) {
293 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
294 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000295 SubobjectIsDesignatorContext, Index,
296 StructuredList, StructuredIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000297 } else if (DeclType->isArrayType()) {
Douglas Gregor5a203a62009-01-23 16:54:12 +0000298 llvm::APSInt Zero(
299 SemaRef->Context.getTypeSize(SemaRef->Context.getSizeType()),
300 false);
Douglas Gregorf603b472009-01-28 21:54:33 +0000301 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
302 StructuredList, StructuredIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000303 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000304 else
Douglas Gregorf603b472009-01-28 21:54:33 +0000305 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffff5b3a82008-08-10 16:05:48 +0000306 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
307 // This type is invalid, issue a diagnostic.
Douglas Gregorf603b472009-01-28 21:54:33 +0000308 ++Index;
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000309 SemaRef->Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000310 << DeclType;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000311 hadError = true;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000312 } else {
313 // In C, all types are either scalars or aggregates, but
314 // additional handling is needed here for C++ (and possibly others?).
315 assert(0 && "Unsupported initializer type");
316 }
317}
318
Eli Friedman683cedf2008-05-19 19:16:24 +0000319void InitListChecker::CheckSubElementType(InitListExpr *IList,
320 QualType ElemType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000321 unsigned &Index,
322 InitListExpr *StructuredList,
323 unsigned &StructuredIndex) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000324 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000325 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
326 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000327 unsigned newStructuredIndex = 0;
328 InitListExpr *newStructuredList
329 = getStructuredSubobjectInit(IList, Index, ElemType,
330 StructuredList, StructuredIndex,
331 SubInitList->getSourceRange());
332 CheckExplicitInitList(SubInitList, ElemType, newIndex,
333 newStructuredList, newStructuredIndex);
334 ++StructuredIndex;
335 ++Index;
Eli Friedman683cedf2008-05-19 19:16:24 +0000336 } else if (StringLiteral *lit =
337 SemaRef->IsStringLiteralInit(expr, ElemType)) {
338 SemaRef->CheckStringLiteralInit(lit, ElemType);
Douglas Gregorf603b472009-01-28 21:54:33 +0000339 UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
340 ++Index;
Eli Friedmand8535af2008-05-19 20:00:43 +0000341 } else if (ElemType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000342 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedman683cedf2008-05-19 19:16:24 +0000343 } else if (expr->getType()->getAsRecordType() &&
Eli Friedman2ccfb512008-06-09 03:52:40 +0000344 SemaRef->Context.typesAreCompatible(
345 expr->getType().getUnqualifiedType(),
346 ElemType.getUnqualifiedType())) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000347 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
348 ++Index;
Eli Friedman683cedf2008-05-19 19:16:24 +0000349 // FIXME: Add checking
350 } else {
Douglas Gregorf603b472009-01-28 21:54:33 +0000351 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
352 StructuredIndex);
353 ++StructuredIndex;
354 }
Eli Friedman683cedf2008-05-19 19:16:24 +0000355}
356
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000357void InitListChecker::CheckScalarType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor36859eb2009-01-29 00:39:20 +0000358 unsigned &Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000359 InitListExpr *StructuredList,
360 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000361 if (Index < IList->getNumInits()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000362 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000363 if (isa<InitListExpr>(expr)) {
Eli Friedman71de9eb2008-05-19 20:12:18 +0000364 SemaRef->Diag(IList->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000365 diag::err_many_braces_around_scalar_init)
366 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000367 hadError = true;
368 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000369 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000370 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000371 } else if (isa<DesignatedInitExpr>(expr)) {
372 SemaRef->Diag(expr->getSourceRange().getBegin(),
373 diag::err_designator_for_scalar_init)
374 << DeclType << expr->getSourceRange();
375 hadError = true;
376 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000377 ++StructuredIndex;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000378 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000379 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000380
Eli Friedmand8535af2008-05-19 20:00:43 +0000381 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000382 if (SemaRef->CheckSingleInitializer(expr, DeclType, false))
Eli Friedman71de9eb2008-05-19 20:12:18 +0000383 hadError = true; // types weren't compatible.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000384 else if (savExpr != expr) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000385 // The type was promoted, update initializer list.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000386 IList->setInit(Index, expr);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000387 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000388 if (hadError)
389 ++StructuredIndex;
390 else
391 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000392 ++Index;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000393 } else {
Chris Lattner9d2cf082008-11-19 05:27:50 +0000394 SemaRef->Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
395 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000396 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000397 ++Index;
398 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000399 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000400 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000401}
402
403void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000404 unsigned &Index,
405 InitListExpr *StructuredList,
406 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000407 if (Index < IList->getNumInits()) {
408 const VectorType *VT = DeclType->getAsVectorType();
409 int maxElements = VT->getNumElements();
410 QualType elementType = VT->getElementType();
411
412 for (int i = 0; i < maxElements; ++i) {
413 // Don't attempt to go past the end of the init list
414 if (Index >= IList->getNumInits())
415 break;
Douglas Gregor36859eb2009-01-29 00:39:20 +0000416 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000417 StructuredList, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000418 }
419 }
420}
421
422void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000423 llvm::APSInt elementIndex,
424 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000425 unsigned &Index,
426 InitListExpr *StructuredList,
427 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000428 // Check for the special-case of initializing an array with a string.
429 if (Index < IList->getNumInits()) {
430 if (StringLiteral *lit =
431 SemaRef->IsStringLiteralInit(IList->getInit(Index), DeclType)) {
432 SemaRef->CheckStringLiteralInit(lit, DeclType);
Douglas Gregorf603b472009-01-28 21:54:33 +0000433 // We place the string literal directly into the resulting
434 // initializer list. This is the only place where the structure
435 // of the structured initializer list doesn't match exactly,
436 // because doing so would involve allocating one character
437 // constant for each string.
438 UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
439 StructuredList->resizeInits(SemaRef->Context, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000440 ++Index;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000441 return;
442 }
443 }
Chris Lattnera1923f62008-08-04 07:31:14 +0000444 if (const VariableArrayType *VAT =
445 SemaRef->Context.getAsVariableArrayType(DeclType)) {
Eli Friedman46f81662008-05-25 13:22:35 +0000446 // Check for VLAs; in standard C it would be possible to check this
447 // earlier, but I don't know where clang accepts VLAs (gcc accepts
448 // them in all sorts of strange places).
449 SemaRef->Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000450 diag::err_variable_object_no_init)
451 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman46f81662008-05-25 13:22:35 +0000452 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000453 ++Index;
454 ++StructuredIndex;
Eli Friedman46f81662008-05-25 13:22:35 +0000455 return;
456 }
457
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000458 // We might know the maximum number of elements in advance.
Douglas Gregorf603b472009-01-28 21:54:33 +0000459 llvm::APSInt maxElements(elementIndex.getBitWidth(),
460 elementIndex.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000461 bool maxElementsKnown = false;
462 if (const ConstantArrayType *CAT =
463 SemaRef->Context.getAsConstantArrayType(DeclType)) {
464 maxElements = CAT->getSize();
Douglas Gregor5a203a62009-01-23 16:54:12 +0000465 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000466 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000467 maxElementsKnown = true;
468 }
469
Chris Lattnera1923f62008-08-04 07:31:14 +0000470 QualType elementType = SemaRef->Context.getAsArrayType(DeclType)
471 ->getElementType();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000472 while (Index < IList->getNumInits()) {
473 Expr *Init = IList->getInit(Index);
474 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000475 // If we're not the subobject that matches up with the '{' for
476 // the designator, we shouldn't be handling the
477 // designator. Return immediately.
478 if (!SubobjectIsDesignatorContext)
479 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000480
Douglas Gregor710f6d42009-01-22 23:26:18 +0000481 // Handle this designated initializer. elementIndex will be
482 // updated to be the next array element we'll initialize.
483 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000484 DeclType, 0, &elementIndex, Index,
485 StructuredList, StructuredIndex)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000486 hadError = true;
487 continue;
488 }
489
Douglas Gregor5a203a62009-01-23 16:54:12 +0000490 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
491 maxElements.extend(elementIndex.getBitWidth());
492 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
493 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000494 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor5a203a62009-01-23 16:54:12 +0000495
Douglas Gregor710f6d42009-01-22 23:26:18 +0000496 // If the array is of incomplete type, keep track of the number of
497 // elements in the initializer.
498 if (!maxElementsKnown && elementIndex > maxElements)
499 maxElements = elementIndex;
500
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000501 continue;
502 }
503
504 // If we know the maximum number of elements, and we've already
505 // hit it, stop consuming elements in the initializer list.
506 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000507 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000508
509 // Check this element.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000510 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000511 StructuredList, StructuredIndex);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000512 ++elementIndex;
513
514 // If the array is of incomplete type, keep track of the number of
515 // elements in the initializer.
516 if (!maxElementsKnown && elementIndex > maxElements)
517 maxElements = elementIndex;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000518 }
519 if (DeclType->isIncompleteArrayType()) {
520 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000521 // be calculated here.
Douglas Gregor69722702009-01-23 18:58:42 +0000522 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000523 if (maxElements == Zero) {
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000524 // Sizing an array implicitly to zero is not allowed by ISO C,
525 // but is supported by GNU.
Steve Naroffc4d4a482008-05-01 22:18:59 +0000526 SemaRef->Diag(IList->getLocStart(),
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000527 diag::ext_typecheck_zero_array_size);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000528 }
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000529
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000530 DeclType = SemaRef->Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000531 ArrayType::Normal, 0);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000532 }
533}
534
535void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
536 QualType DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000537 RecordDecl::field_iterator Field,
538 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000539 unsigned &Index,
540 InitListExpr *StructuredList,
541 unsigned &StructuredIndex) {
Eli Friedman683cedf2008-05-19 19:16:24 +0000542 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000543
Eli Friedman683cedf2008-05-19 19:16:24 +0000544 // If the record is invalid, some of it's members are invalid. To avoid
545 // confusion, we forgo checking the intializer for the entire record.
546 if (structDecl->isInvalidDecl()) {
547 hadError = true;
548 return;
549 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000550 // If structDecl is a forward declaration, this loop won't do
551 // anything except look at designated initializers; That's okay,
552 // because an error should get printed out elsewhere. It might be
553 // worthwhile to skip over the rest of the initializer, though.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000554 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor710f6d42009-01-22 23:26:18 +0000555 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000556 while (Index < IList->getNumInits()) {
557 Expr *Init = IList->getInit(Index);
558
559 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000560 // If we're not the subobject that matches up with the '{' for
561 // the designator, we shouldn't be handling the
562 // designator. Return immediately.
563 if (!SubobjectIsDesignatorContext)
564 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000565
Douglas Gregor710f6d42009-01-22 23:26:18 +0000566 // Handle this designated initializer. Field will be updated to
567 // the next field that we'll be initializing.
568 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000569 DeclType, &Field, 0, Index,
570 StructuredList, StructuredIndex))
Douglas Gregor710f6d42009-01-22 23:26:18 +0000571 hadError = true;
572
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000573 continue;
574 }
575
576 if (Field == FieldEnd) {
577 // We've run out of fields. We're done.
578 break;
579 }
580
Douglas Gregor8acb7272008-12-11 16:49:14 +0000581 // If we've hit the flexible array member at the end, we're done.
582 if (Field->getType()->isIncompleteArrayType())
583 break;
584
Douglas Gregorf603b472009-01-28 21:54:33 +0000585 if (!Field->getIdentifier() && Field->isBitField()) {
586 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000587 ++Field;
Eli Friedman683cedf2008-05-19 19:16:24 +0000588 continue;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000589 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000590
Douglas Gregor36859eb2009-01-29 00:39:20 +0000591 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000592 StructuredList, StructuredIndex);
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000593 if (DeclType->isUnionType())
Eli Friedman683cedf2008-05-19 19:16:24 +0000594 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000595
596 ++Field;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000597 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000598
Eli Friedman683cedf2008-05-19 19:16:24 +0000599 // FIXME: Implement flexible array initialization GCC extension (it's a
600 // really messy extension to implement, unfortunately...the necessary
601 // information isn't actually even here!)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000602}
Steve Naroffc4d4a482008-05-01 22:18:59 +0000603
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000604/// @brief Check the well-formedness of a C99 designated initializer.
605///
606/// Determines whether the designated initializer @p DIE, which
607/// resides at the given @p Index within the initializer list @p
608/// IList, is well-formed for a current object of type @p DeclType
609/// (C99 6.7.8). The actual subobject that this designator refers to
610/// within the current subobject is returned in either
Douglas Gregorf603b472009-01-28 21:54:33 +0000611/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000612///
613/// @param IList The initializer list in which this designated
614/// initializer occurs.
615///
616/// @param DIE The designated initializer and its initialization
617/// expression.
618///
619/// @param DeclType The type of the "current object" (C99 6.7.8p17),
620/// into which the designation in @p DIE should refer.
621///
Douglas Gregor710f6d42009-01-22 23:26:18 +0000622/// @param NextField If non-NULL and the first designator in @p DIE is
623/// a field, this will be set to the field declaration corresponding
624/// to the field named by the designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000625///
Douglas Gregor710f6d42009-01-22 23:26:18 +0000626/// @param NextElementIndex If non-NULL and the first designator in @p
627/// DIE is an array designator or GNU array-range designator, this
628/// will be set to the last index initialized by this designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000629///
630/// @param Index Index into @p IList where the designated initializer
631/// @p DIE occurs.
632///
Douglas Gregorf603b472009-01-28 21:54:33 +0000633/// @param StructuredList The initializer list expression that
634/// describes all of the subobject initializers in the order they'll
635/// actually be initialized.
636///
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000637/// @returns true if there was an error, false otherwise.
Douglas Gregor710f6d42009-01-22 23:26:18 +0000638bool
639InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
640 DesignatedInitExpr *DIE,
641 DesignatedInitExpr::designators_iterator D,
642 QualType &CurrentObjectType,
643 RecordDecl::field_iterator *NextField,
644 llvm::APSInt *NextElementIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +0000645 unsigned &Index,
646 InitListExpr *StructuredList,
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000647 unsigned &StructuredIndex,
648 bool FinishSubobjectInit) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000649 if (D == DIE->designators_end()) {
650 // Check the actual initialization for the designated object type.
651 bool prevHadError = hadError;
Douglas Gregor36859eb2009-01-29 00:39:20 +0000652
653 // Temporarily remove the designator expression from the
654 // initializer list that the child calls see, so that we don't try
655 // to re-process the designator.
656 unsigned OldIndex = Index;
657 IList->setInit(OldIndex, DIE->getInit());
658
659 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000660 StructuredList, StructuredIndex);
Douglas Gregor36859eb2009-01-29 00:39:20 +0000661
662 // Restore the designated initializer expression in the syntactic
663 // form of the initializer list.
664 if (IList->getInit(OldIndex) != DIE->getInit())
665 DIE->setInit(IList->getInit(OldIndex));
666 IList->setInit(OldIndex, DIE);
667
Douglas Gregor710f6d42009-01-22 23:26:18 +0000668 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000669 }
670
Douglas Gregorf603b472009-01-28 21:54:33 +0000671 bool IsFirstDesignator = (D == DIE->designators_begin());
672 assert((IsFirstDesignator || StructuredList) &&
673 "Need a non-designated initializer list to start from");
674
675 // Determine the structural initializer list that corresponds to the
676 // current subobject.
677 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
678 : getStructuredSubobjectInit(IList, Index, CurrentObjectType, StructuredList,
679 StructuredIndex,
680 SourceRange(D->getStartLocation(),
681 DIE->getSourceRange().getEnd()));
682 assert(StructuredList && "Expected a structured initializer list");
683
Douglas Gregor710f6d42009-01-22 23:26:18 +0000684 if (D->isFieldDesignator()) {
685 // C99 6.7.8p7:
686 //
687 // If a designator has the form
688 //
689 // . identifier
690 //
691 // then the current object (defined below) shall have
692 // structure or union type and the identifier shall be the
693 // name of a member of that type.
694 const RecordType *RT = CurrentObjectType->getAsRecordType();
695 if (!RT) {
696 SourceLocation Loc = D->getDotLoc();
697 if (Loc.isInvalid())
698 Loc = D->getFieldLoc();
699 SemaRef->Diag(Loc, diag::err_field_designator_non_aggr)
700 << SemaRef->getLangOptions().CPlusPlus << CurrentObjectType;
701 ++Index;
702 return true;
703 }
704
Douglas Gregorf603b472009-01-28 21:54:33 +0000705 // Note: we perform a linear search of the fields here, despite
706 // the fact that we have a faster lookup method, because we always
707 // need to compute the field's index.
Douglas Gregor710f6d42009-01-22 23:26:18 +0000708 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregorf603b472009-01-28 21:54:33 +0000709 unsigned FieldIndex = 0;
710 RecordDecl::field_iterator Field = RT->getDecl()->field_begin(),
711 FieldEnd = RT->getDecl()->field_end();
712 for (; Field != FieldEnd; ++Field) {
713 if (Field->isUnnamedBitfield())
714 continue;
715
716 if (Field->getIdentifier() == FieldName)
717 break;
718
719 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000720 }
721
Douglas Gregorf603b472009-01-28 21:54:33 +0000722 if (Field == FieldEnd) {
723 // We did not find the field we're looking for. Produce a
724 // suitable diagnostic and return a failure.
725 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
726 if (Lookup.first == Lookup.second) {
727 // Name lookup didn't find anything.
728 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
729 << FieldName << CurrentObjectType;
730 } else {
731 // Name lookup found something, but it wasn't a field.
732 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
733 << FieldName;
734 SemaRef->Diag((*Lookup.first)->getLocation(),
735 diag::note_field_designator_found);
736 }
737
738 ++Index;
739 return true;
740 } else if (cast<RecordDecl>((*Field)->getDeclContext())
741 ->isAnonymousStructOrUnion()) {
742 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_anon_class)
743 << FieldName
744 << (cast<RecordDecl>((*Field)->getDeclContext())->isUnion()? 2 :
745 (int)SemaRef->getLangOptions().CPlusPlus);
746 SemaRef->Diag((*Field)->getLocation(), diag::note_field_designator_found);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000747 ++Index;
748 return true;
749 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000750
751 // All of the fields of a union are located at the same place in
752 // the initializer list.
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000753 if (RT->getDecl()->isUnion())
Douglas Gregorf603b472009-01-28 21:54:33 +0000754 FieldIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000755
Douglas Gregor710f6d42009-01-22 23:26:18 +0000756 // Update the designator with the field declaration.
Douglas Gregorf603b472009-01-28 21:54:33 +0000757 D->setField(*Field);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000758
Douglas Gregorf603b472009-01-28 21:54:33 +0000759 // Make sure that our non-designated initializer list has space
760 // for a subobject corresponding to this field.
761 if (FieldIndex >= StructuredList->getNumInits())
762 StructuredList->resizeInits(SemaRef->Context, FieldIndex + 1);
763
Douglas Gregor710f6d42009-01-22 23:26:18 +0000764 // Recurse to check later designated subobjects.
Douglas Gregorf603b472009-01-28 21:54:33 +0000765 QualType FieldType = (*Field)->getType();
766 unsigned newStructuredIndex = FieldIndex;
767 if (CheckDesignatedInitializer(IList, DIE, ++D, FieldType, 0, 0, Index,
768 StructuredList, newStructuredIndex))
Douglas Gregor710f6d42009-01-22 23:26:18 +0000769 return true;
770
771 // Find the position of the next field to be initialized in this
772 // subobject.
Douglas Gregor710f6d42009-01-22 23:26:18 +0000773 ++Field;
Douglas Gregorf603b472009-01-28 21:54:33 +0000774 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000775
776 // If this the first designator, our caller will continue checking
777 // the rest of this struct/class/union subobject.
778 if (IsFirstDesignator) {
779 if (NextField)
780 *NextField = Field;
Douglas Gregorf603b472009-01-28 21:54:33 +0000781 StructuredIndex = FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000782 return false;
783 }
784
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000785 if (!FinishSubobjectInit)
786 return false;
787
Douglas Gregor710f6d42009-01-22 23:26:18 +0000788 // Check the remaining fields within this class/struct/union subobject.
789 bool prevHadError = hadError;
Douglas Gregorf603b472009-01-28 21:54:33 +0000790 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
791 StructuredList, FieldIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000792 return hadError && !prevHadError;
793 }
794
795 // C99 6.7.8p6:
796 //
797 // If a designator has the form
798 //
799 // [ constant-expression ]
800 //
801 // then the current object (defined below) shall have array
802 // type and the expression shall be an integer constant
803 // expression. If the array is of unknown size, any
804 // nonnegative value is valid.
805 //
806 // Additionally, cope with the GNU extension that permits
807 // designators of the form
808 //
809 // [ constant-expression ... constant-expression ]
810 const ArrayType *AT = SemaRef->Context.getAsArrayType(CurrentObjectType);
811 if (!AT) {
812 SemaRef->Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
813 << CurrentObjectType;
814 ++Index;
815 return true;
816 }
817
818 Expr *IndexExpr = 0;
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000819 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
820 if (D->isArrayDesignator()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000821 IndexExpr = DIE->getArrayIndex(*D);
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000822
823 bool ConstExpr
824 = IndexExpr->isIntegerConstantExpr(DesignatedStartIndex, SemaRef->Context);
825 assert(ConstExpr && "Expression must be constant"); (void)ConstExpr;
826
827 DesignatedEndIndex = DesignatedStartIndex;
828 } else {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000829 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000830
831 bool StartConstExpr
832 = DIE->getArrayRangeStart(*D)->isIntegerConstantExpr(DesignatedStartIndex,
833 SemaRef->Context);
834 assert(StartConstExpr && "Expression must be constant"); (void)StartConstExpr;
835
836 bool EndConstExpr
837 = DIE->getArrayRangeEnd(*D)->isIntegerConstantExpr(DesignatedEndIndex,
838 SemaRef->Context);
839 assert(EndConstExpr && "Expression must be constant"); (void)EndConstExpr;
840
Douglas Gregor710f6d42009-01-22 23:26:18 +0000841 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000842
843 if (DesignatedStartIndex.getZExtValue() != DesignatedEndIndex.getZExtValue())
844 SemaRef->Diag(D->getEllipsisLoc(),
845 diag::warn_gnu_array_range_designator_side_effects)
846 << SourceRange(D->getLBracketLoc(), D->getRBracketLoc());
Douglas Gregor710f6d42009-01-22 23:26:18 +0000847 }
848
Douglas Gregor710f6d42009-01-22 23:26:18 +0000849 if (isa<ConstantArrayType>(AT)) {
850 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000851 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
852 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
853 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
854 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
855 if (DesignatedEndIndex >= MaxElements) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000856 SemaRef->Diag(IndexExpr->getSourceRange().getBegin(),
857 diag::err_array_designator_too_large)
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000858 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor710f6d42009-01-22 23:26:18 +0000859 << IndexExpr->getSourceRange();
860 ++Index;
861 return true;
862 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000863 } else {
864 // Make sure the bit-widths and signedness match.
865 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
866 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
867 else if (DesignatedStartIndex.getBitWidth() < DesignatedEndIndex.getBitWidth())
868 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
869 DesignatedStartIndex.setIsUnsigned(true);
870 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000871 }
872
Douglas Gregorf603b472009-01-28 21:54:33 +0000873 // Make sure that our non-designated initializer list has space
874 // for a subobject corresponding to this array element.
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000875 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
876 StructuredList->resizeInits(SemaRef->Context,
877 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +0000878
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000879 // Repeatedly perform subobject initializations in the range
880 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor710f6d42009-01-22 23:26:18 +0000881
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000882 // Move to the next designator
883 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
884 unsigned OldIndex = Index;
885 ++D;
886 while (DesignatedStartIndex <= DesignatedEndIndex) {
887 // Recurse to check later designated subobjects.
888 QualType ElementType = AT->getElementType();
889 Index = OldIndex;
890 if (CheckDesignatedInitializer(IList, DIE, D, ElementType, 0, 0, Index,
891 StructuredList, ElementIndex,
892 (DesignatedStartIndex == DesignatedEndIndex)))
893 return true;
894
895 // Move to the next index in the array that we'll be initializing.
896 ++DesignatedStartIndex;
897 ElementIndex = DesignatedStartIndex.getZExtValue();
898 }
Douglas Gregor710f6d42009-01-22 23:26:18 +0000899
900 // If this the first designator, our caller will continue checking
901 // the rest of this array subobject.
902 if (IsFirstDesignator) {
903 if (NextElementIndex)
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000904 *NextElementIndex = DesignatedStartIndex;
Douglas Gregorf603b472009-01-28 21:54:33 +0000905 StructuredIndex = ElementIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000906 return false;
907 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000908
909 if (!FinishSubobjectInit)
910 return false;
911
Douglas Gregor710f6d42009-01-22 23:26:18 +0000912 // Check the remaining elements within this array subobject.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000913 bool prevHadError = hadError;
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000914 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, true, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000915 StructuredList, ElementIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000916 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000917}
918
Douglas Gregorf603b472009-01-28 21:54:33 +0000919// Get the structured initializer list for a subobject of type
920// @p CurrentObjectType.
921InitListExpr *
922InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
923 QualType CurrentObjectType,
924 InitListExpr *StructuredList,
925 unsigned StructuredIndex,
926 SourceRange InitRange) {
927 Expr *ExistingInit = 0;
928 if (!StructuredList)
929 ExistingInit = SyntacticToSemantic[IList];
930 else if (StructuredIndex < StructuredList->getNumInits())
931 ExistingInit = StructuredList->getInit(StructuredIndex);
932
933 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
934 return Result;
935
936 if (ExistingInit) {
937 // We are creating an initializer list that initializes the
938 // subobjects of the current object, but there was already an
939 // initialization that completely initialized the current
940 // subobject, e.g., by a compound literal:
941 //
942 // struct X { int a, b; };
943 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
944 //
945 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
946 // designated initializer re-initializes the whole
947 // subobject [0], overwriting previous initializers.
948 SemaRef->Diag(InitRange.getBegin(), diag::warn_subobject_initializer_overrides)
949 << InitRange;
950 SemaRef->Diag(ExistingInit->getSourceRange().getBegin(),
951 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +0000952 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +0000953 << ExistingInit->getSourceRange();
954 }
955
956 InitListExpr *Result
957 = new (SemaRef->Context) InitListExpr(SourceLocation(), 0, 0,
958 SourceLocation());
959 Result->setType(CurrentObjectType);
960
961 // Link this new initializer list into the structured initializer
962 // lists.
963 if (StructuredList)
964 StructuredList->updateInit(StructuredIndex, Result);
965 else {
966 Result->setSyntacticForm(IList);
967 SyntacticToSemantic[IList] = Result;
968 }
969
970 return Result;
971}
972
973/// Update the initializer at index @p StructuredIndex within the
974/// structured initializer list to the value @p expr.
975void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
976 unsigned &StructuredIndex,
977 Expr *expr) {
978 // No structured initializer list to update
979 if (!StructuredList)
980 return;
981
982 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
983 // This initializer overwrites a previous initializer. Warn.
984 SemaRef->Diag(expr->getSourceRange().getBegin(),
985 diag::warn_initializer_overrides)
986 << expr->getSourceRange();
987 SemaRef->Diag(PrevInit->getSourceRange().getBegin(),
988 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +0000989 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +0000990 << PrevInit->getSourceRange();
991 }
992
993 ++StructuredIndex;
994}
995
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000996/// Check that the given Index expression is a valid array designator
997/// value. This is essentailly just a wrapper around
998/// Expr::isIntegerConstantExpr that also checks for negative values
999/// and produces a reasonable diagnostic if there is a
1000/// failure. Returns true if there was an error, false otherwise. If
1001/// everything went okay, Value will receive the value of the constant
1002/// expression.
1003static bool
1004CheckArrayDesignatorExpr(Sema &Self, Expr *Index, llvm::APSInt &Value) {
1005 SourceLocation Loc = Index->getSourceRange().getBegin();
1006
1007 // Make sure this is an integer constant expression.
1008 if (!Index->isIntegerConstantExpr(Value, Self.Context, &Loc))
1009 return Self.Diag(Loc, diag::err_array_designator_nonconstant)
1010 << Index->getSourceRange();
1011
1012 // Make sure this constant expression is non-negative.
Douglas Gregor69722702009-01-23 18:58:42 +00001013 llvm::APSInt Zero(llvm::APSInt::getNullValue(Value.getBitWidth()),
1014 Value.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001015 if (Value < Zero)
1016 return Self.Diag(Loc, diag::err_array_designator_negative)
1017 << Value.toString(10) << Index->getSourceRange();
1018
Douglas Gregore498e372009-01-23 21:04:18 +00001019 Value.setIsUnsigned(true);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001020 return false;
1021}
1022
1023Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1024 SourceLocation Loc,
1025 bool UsedColonSyntax,
1026 OwningExprResult Init) {
1027 typedef DesignatedInitExpr::Designator ASTDesignator;
1028
1029 bool Invalid = false;
1030 llvm::SmallVector<ASTDesignator, 32> Designators;
1031 llvm::SmallVector<Expr *, 32> InitExpressions;
1032
1033 // Build designators and check array designator expressions.
1034 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1035 const Designator &D = Desig.getDesignator(Idx);
1036 switch (D.getKind()) {
1037 case Designator::FieldDesignator:
1038 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1039 D.getFieldLoc()));
1040 break;
1041
1042 case Designator::ArrayDesignator: {
1043 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1044 llvm::APSInt IndexValue;
1045 if (CheckArrayDesignatorExpr(*this, Index, IndexValue))
1046 Invalid = true;
1047 else {
1048 Designators.push_back(ASTDesignator(InitExpressions.size(),
1049 D.getLBracketLoc(),
1050 D.getRBracketLoc()));
1051 InitExpressions.push_back(Index);
1052 }
1053 break;
1054 }
1055
1056 case Designator::ArrayRangeDesignator: {
1057 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1058 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1059 llvm::APSInt StartValue;
1060 llvm::APSInt EndValue;
1061 if (CheckArrayDesignatorExpr(*this, StartIndex, StartValue) ||
1062 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))
1063 Invalid = true;
Douglas Gregorea0528d2009-01-23 22:22:29 +00001064 else {
1065 // Make sure we're comparing values with the same bit width.
1066 if (StartValue.getBitWidth() > EndValue.getBitWidth())
1067 EndValue.extend(StartValue.getBitWidth());
1068 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1069 StartValue.extend(EndValue.getBitWidth());
1070
1071 if (EndValue < StartValue) {
1072 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1073 << StartValue.toString(10) << EndValue.toString(10)
1074 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1075 Invalid = true;
1076 } else {
1077 Designators.push_back(ASTDesignator(InitExpressions.size(),
1078 D.getLBracketLoc(),
1079 D.getEllipsisLoc(),
1080 D.getRBracketLoc()));
1081 InitExpressions.push_back(StartIndex);
1082 InitExpressions.push_back(EndIndex);
1083 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001084 }
1085 break;
1086 }
1087 }
1088 }
1089
1090 if (Invalid || Init.isInvalid())
1091 return ExprError();
1092
1093 // Clear out the expressions within the designation.
1094 Desig.ClearExprs(*this);
1095
1096 DesignatedInitExpr *DIE
1097 = DesignatedInitExpr::Create(Context, &Designators[0], Designators.size(),
1098 &InitExpressions[0], InitExpressions.size(),
1099 Loc, UsedColonSyntax,
1100 static_cast<Expr *>(Init.release()));
1101 return Owned(DIE);
1102}
Douglas Gregor849afc32009-01-29 00:45:39 +00001103
1104bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
1105 InitListChecker CheckInitList(this, InitList, DeclType);
1106 if (!CheckInitList.HadError())
1107 InitList = CheckInitList.getFullyStructuredList();
1108
1109 return CheckInitList.HadError();
1110}