blob: c2539913ce398cb52d4ea54d22f82eba4127250a [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//
10// This file implements semantic analysis for initializers.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +000015#include "clang/Parse/Designator.h"
Steve Naroffc4d4a482008-05-01 22:18:59 +000016#include "clang/AST/ASTContext.h"
17#include "clang/AST/Expr.h"
Douglas Gregorf603b472009-01-28 21:54:33 +000018#include "clang/AST/ExprCXX.h"
Chris Lattner52a425b2009-01-27 18:30:58 +000019#include "clang/Basic/DiagnosticSema.h"
Douglas Gregor849afc32009-01-29 00:45:39 +000020#include <map>
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +000021using namespace clang;
Steve Naroffc4d4a482008-05-01 22:18:59 +000022
Douglas Gregor849afc32009-01-29 00:45:39 +000023class InitListChecker {
24 Sema *SemaRef;
25 bool hadError;
26 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
27 InitListExpr *FullyStructuredList;
28
29 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
30 unsigned &Index, InitListExpr *StructuredInitList,
31 unsigned &StructuredInitIndex);
32 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
33 unsigned &Index, InitListExpr *StructuredInitList,
34 unsigned &StructuredInitIndex);
35 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
36 bool SubobjectIsDesignatorContext,
37 unsigned &Index,
38 InitListExpr *StructuredInitList,
39 unsigned &StructuredInitIndex);
40 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
41 unsigned &Index,
42 InitListExpr *StructuredInitList,
43 unsigned &StructuredInitIndex);
44 // FIXME: Does DeclType need to be a reference type?
45 void CheckScalarType(InitListExpr *IList, QualType &DeclType,
46 unsigned &Index,
47 InitListExpr *StructuredInitList,
48 unsigned &StructuredInitIndex);
49 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
50 InitListExpr *StructuredInitList,
51 unsigned &StructuredInitIndex);
52 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
53 RecordDecl::field_iterator Field,
54 bool SubobjectIsDesignatorContext, unsigned &Index,
55 InitListExpr *StructuredInitList,
56 unsigned &StructuredInitIndex);
57 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
58 llvm::APSInt elementIndex,
59 bool SubobjectIsDesignatorContext, unsigned &Index,
60 InitListExpr *StructuredInitList,
61 unsigned &StructuredInitIndex);
62 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
63 DesignatedInitExpr::designators_iterator D,
64 QualType &CurrentObjectType,
65 RecordDecl::field_iterator *NextField,
66 llvm::APSInt *NextElementIndex,
67 unsigned &Index,
68 InitListExpr *StructuredList,
69 unsigned &StructuredIndex,
70 bool FinishSubobjectInit = true);
71 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
72 QualType CurrentObjectType,
73 InitListExpr *StructuredList,
74 unsigned StructuredIndex,
75 SourceRange InitRange);
76 void UpdateStructuredListElement(InitListExpr *StructuredInitList,
77 unsigned &StructuredInitIndex,
78 Expr *expr);
79 int numArrayElements(QualType DeclType);
80 int numStructUnionElements(QualType DeclType);
81public:
82 InitListChecker(Sema *S, InitListExpr *IL, QualType &T);
83 bool HadError() { return hadError; }
84
85 // @brief Retrieves the fully-structured initializer list used for
86 // semantic analysis and code generation.
87 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
88};
89
Douglas Gregorf603b472009-01-28 21:54:33 +000090/// Recursively replaces NULL values within the given initializer list
91/// with expressions that perform value-initialization of the
92/// appropriate type.
93static void fillInValueInitializations(ASTContext &Context, InitListExpr *ILE) {
94 assert((ILE->getType() != Context.VoidTy) && "Should not have void type");
95 if (const RecordType *RType = ILE->getType()->getAsRecordType()) {
96 unsigned Init = 0, NumInits = ILE->getNumInits();
97 for (RecordDecl::field_iterator Field = RType->getDecl()->field_begin(),
98 FieldEnd = RType->getDecl()->field_end();
99 Field != FieldEnd; ++Field) {
100 if (Field->isUnnamedBitfield())
101 continue;
102
103 if (Init >= NumInits)
104 break;
105
106 // FIXME: Check for fields with reference type in C++?
107 if (!ILE->getInit(Init))
108 ILE->setInit(Init,
109 new (Context) CXXZeroInitValueExpr(Field->getType(),
110 SourceLocation(),
111 SourceLocation()));
112 else if (InitListExpr *InnerILE = dyn_cast<InitListExpr>(ILE->getInit(Init)))
113 fillInValueInitializations(Context, InnerILE);
114 ++Init;
115 }
116
117 return;
118 }
119
120 QualType ElementType;
121
122 if (const ArrayType *AType = Context.getAsArrayType(ILE->getType()))
123 ElementType = AType->getElementType();
124 else if (const VectorType *VType = ILE->getType()->getAsVectorType())
125 ElementType = VType->getElementType();
126 else
127 ElementType = ILE->getType();
128
129 for (unsigned Init = 0, NumInits = ILE->getNumInits(); Init != NumInits;
130 ++Init) {
131 if (!ILE->getInit(Init))
132 ILE->setInit(Init, new (Context) CXXZeroInitValueExpr(ElementType,
133 SourceLocation(),
134 SourceLocation()));
135 else if (InitListExpr *InnerILE = dyn_cast<InitListExpr>(ILE->getInit(Init)))
136 fillInValueInitializations(Context, InnerILE);
137 }
138}
139
Steve Naroffc4d4a482008-05-01 22:18:59 +0000140InitListChecker::InitListChecker(Sema *S, InitListExpr *IL, QualType &T) {
141 hadError = false;
142 SemaRef = S;
Eli Friedmand8535af2008-05-19 20:00:43 +0000143
Eli Friedman683cedf2008-05-19 19:16:24 +0000144 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000145 unsigned newStructuredIndex = 0;
146 FullyStructuredList
147 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, SourceRange());
148 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000149
Douglas Gregorf603b472009-01-28 21:54:33 +0000150 if (!hadError) {
151 fillInValueInitializations(SemaRef->Context, FullyStructuredList);
152 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000153}
154
155int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman46f81662008-05-25 13:22:35 +0000156 // FIXME: use a proper constant
157 int maxElements = 0x7FFFFFFF;
Chris Lattnera1923f62008-08-04 07:31:14 +0000158 if (const ConstantArrayType *CAT =
159 SemaRef->Context.getAsConstantArrayType(DeclType)) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000160 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
161 }
162 return maxElements;
163}
164
165int InitListChecker::numStructUnionElements(QualType DeclType) {
166 RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl();
Douglas Gregorf603b472009-01-28 21:54:33 +0000167 int InitializableMembers = 0;
168 for (RecordDecl::field_iterator Field = structDecl->field_begin(),
169 FieldEnd = structDecl->field_end();
170 Field != FieldEnd; ++Field) {
171 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
172 ++InitializableMembers;
173 }
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000174 if (structDecl->isUnion())
Eli Friedman9f5250b2008-05-25 14:03:31 +0000175 return std::min(InitializableMembers, 1);
176 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000177}
178
179void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregorf603b472009-01-28 21:54:33 +0000180 QualType T, unsigned &Index,
181 InitListExpr *StructuredList,
182 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000183 int maxElements = 0;
184
185 if (T->isArrayType())
186 maxElements = numArrayElements(T);
187 else if (T->isStructureType() || T->isUnionType())
188 maxElements = numStructUnionElements(T);
Eli Friedman683cedf2008-05-19 19:16:24 +0000189 else if (T->isVectorType())
190 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000191 else
192 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman683cedf2008-05-19 19:16:24 +0000193
Douglas Gregorf603b472009-01-28 21:54:33 +0000194 // FIXME: Perhaps we should move this warning elsewhere?
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000195 if (maxElements == 0) {
196 SemaRef->Diag(ParentIList->getInit(Index)->getLocStart(),
197 diag::err_implicit_empty_initializer);
Douglas Gregorf603b472009-01-28 21:54:33 +0000198 ++Index;
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000199 hadError = true;
200 return;
201 }
202
Douglas Gregorf603b472009-01-28 21:54:33 +0000203 // Build a structured initializer list corresponding to this subobject.
204 InitListExpr *StructuredSubobjectInitList
205 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
206 StructuredIndex,
207 ParentIList->getInit(Index)->getSourceRange());
208 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman683cedf2008-05-19 19:16:24 +0000209
Douglas Gregorf603b472009-01-28 21:54:33 +0000210 // Check the element types and build the structural subobject.
211 CheckListElementTypes(ParentIList, T, false, Index,
212 StructuredSubobjectInitList,
213 StructuredSubobjectInitIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000214}
215
Steve Naroff56099522008-05-06 00:23:44 +0000216void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregorf603b472009-01-28 21:54:33 +0000217 unsigned &Index,
218 InitListExpr *StructuredList,
219 unsigned &StructuredIndex) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000220 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregorf603b472009-01-28 21:54:33 +0000221 SyntacticToSemantic[IList] = StructuredList;
222 StructuredList->setSyntacticForm(IList);
223 CheckListElementTypes(IList, T, true, Index, StructuredList,
224 StructuredIndex);
Steve Naroff56099522008-05-06 00:23:44 +0000225 IList->setType(T);
Douglas Gregorf603b472009-01-28 21:54:33 +0000226 StructuredList->setType(T);
Eli Friedman46f81662008-05-25 13:22:35 +0000227 if (hadError)
228 return;
Eli Friedmand8535af2008-05-19 20:00:43 +0000229
Eli Friedman46f81662008-05-25 13:22:35 +0000230 if (Index < IList->getNumInits()) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000231 // We have leftover initializers
232 if (IList->getNumInits() > 0 &&
233 SemaRef->IsStringLiteralInit(IList->getInit(Index), T)) {
Eli Friedman71de9eb2008-05-19 20:12:18 +0000234 // Special-case
Eli Friedmand8535af2008-05-19 20:00:43 +0000235 SemaRef->Diag(IList->getInit(Index)->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000236 diag::err_excess_initializers_in_char_array_initializer)
237 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000238 hadError = true;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000239 } else if (!T->isIncompleteType()) {
240 // Don't warn for incomplete types, since we'll get an error elsewhere
Eli Friedmand8535af2008-05-19 20:00:43 +0000241 SemaRef->Diag(IList->getInit(Index)->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000242 diag::warn_excess_initializers)
243 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000244 }
245 }
Eli Friedman455f7622008-05-19 20:20:43 +0000246
Eli Friedman46f81662008-05-25 13:22:35 +0000247 if (T->isScalarType())
Chris Lattner9d2cf082008-11-19 05:27:50 +0000248 SemaRef->Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
249 << IList->getSourceRange();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000250}
251
Eli Friedman683cedf2008-05-19 19:16:24 +0000252void InitListChecker::CheckListElementTypes(InitListExpr *IList,
253 QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000254 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000255 unsigned &Index,
256 InitListExpr *StructuredList,
257 unsigned &StructuredIndex) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000258 if (DeclType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000259 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000260 } else if (DeclType->isVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000261 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000262 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000263 if (DeclType->isStructureType() || DeclType->isUnionType()) {
264 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
265 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000266 SubobjectIsDesignatorContext, Index,
267 StructuredList, StructuredIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000268 } else if (DeclType->isArrayType()) {
Douglas Gregor5a203a62009-01-23 16:54:12 +0000269 llvm::APSInt Zero(
270 SemaRef->Context.getTypeSize(SemaRef->Context.getSizeType()),
271 false);
Douglas Gregorf603b472009-01-28 21:54:33 +0000272 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
273 StructuredList, StructuredIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000274 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000275 else
Douglas Gregorf603b472009-01-28 21:54:33 +0000276 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffff5b3a82008-08-10 16:05:48 +0000277 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
278 // This type is invalid, issue a diagnostic.
Douglas Gregorf603b472009-01-28 21:54:33 +0000279 ++Index;
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000280 SemaRef->Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000281 << DeclType;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000282 hadError = true;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000283 } else {
284 // In C, all types are either scalars or aggregates, but
285 // additional handling is needed here for C++ (and possibly others?).
286 assert(0 && "Unsupported initializer type");
287 }
288}
289
Eli Friedman683cedf2008-05-19 19:16:24 +0000290void InitListChecker::CheckSubElementType(InitListExpr *IList,
291 QualType ElemType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000292 unsigned &Index,
293 InitListExpr *StructuredList,
294 unsigned &StructuredIndex) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000295 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000296 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
297 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000298 unsigned newStructuredIndex = 0;
299 InitListExpr *newStructuredList
300 = getStructuredSubobjectInit(IList, Index, ElemType,
301 StructuredList, StructuredIndex,
302 SubInitList->getSourceRange());
303 CheckExplicitInitList(SubInitList, ElemType, newIndex,
304 newStructuredList, newStructuredIndex);
305 ++StructuredIndex;
306 ++Index;
Eli Friedman683cedf2008-05-19 19:16:24 +0000307 } else if (StringLiteral *lit =
308 SemaRef->IsStringLiteralInit(expr, ElemType)) {
309 SemaRef->CheckStringLiteralInit(lit, ElemType);
Douglas Gregorf603b472009-01-28 21:54:33 +0000310 UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
311 ++Index;
Eli Friedmand8535af2008-05-19 20:00:43 +0000312 } else if (ElemType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000313 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedman683cedf2008-05-19 19:16:24 +0000314 } else if (expr->getType()->getAsRecordType() &&
Eli Friedman2ccfb512008-06-09 03:52:40 +0000315 SemaRef->Context.typesAreCompatible(
316 expr->getType().getUnqualifiedType(),
317 ElemType.getUnqualifiedType())) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000318 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
319 ++Index;
Eli Friedman683cedf2008-05-19 19:16:24 +0000320 // FIXME: Add checking
321 } else {
Douglas Gregorf603b472009-01-28 21:54:33 +0000322 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
323 StructuredIndex);
324 ++StructuredIndex;
325 }
Eli Friedman683cedf2008-05-19 19:16:24 +0000326}
327
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000328void InitListChecker::CheckScalarType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor36859eb2009-01-29 00:39:20 +0000329 unsigned &Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000330 InitListExpr *StructuredList,
331 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000332 if (Index < IList->getNumInits()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000333 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000334 if (isa<InitListExpr>(expr)) {
Eli Friedman71de9eb2008-05-19 20:12:18 +0000335 SemaRef->Diag(IList->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000336 diag::err_many_braces_around_scalar_init)
337 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000338 hadError = true;
339 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000340 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000341 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000342 } else if (isa<DesignatedInitExpr>(expr)) {
343 SemaRef->Diag(expr->getSourceRange().getBegin(),
344 diag::err_designator_for_scalar_init)
345 << DeclType << expr->getSourceRange();
346 hadError = true;
347 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000348 ++StructuredIndex;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000349 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000350 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000351
Eli Friedmand8535af2008-05-19 20:00:43 +0000352 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000353 if (SemaRef->CheckSingleInitializer(expr, DeclType, false))
Eli Friedman71de9eb2008-05-19 20:12:18 +0000354 hadError = true; // types weren't compatible.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000355 else if (savExpr != expr) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000356 // The type was promoted, update initializer list.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000357 IList->setInit(Index, expr);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000358 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000359 if (hadError)
360 ++StructuredIndex;
361 else
362 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000363 ++Index;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000364 } else {
Chris Lattner9d2cf082008-11-19 05:27:50 +0000365 SemaRef->Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
366 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000367 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000368 ++Index;
369 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000370 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000371 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000372}
373
374void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000375 unsigned &Index,
376 InitListExpr *StructuredList,
377 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000378 if (Index < IList->getNumInits()) {
379 const VectorType *VT = DeclType->getAsVectorType();
380 int maxElements = VT->getNumElements();
381 QualType elementType = VT->getElementType();
382
383 for (int i = 0; i < maxElements; ++i) {
384 // Don't attempt to go past the end of the init list
385 if (Index >= IList->getNumInits())
386 break;
Douglas Gregor36859eb2009-01-29 00:39:20 +0000387 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000388 StructuredList, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000389 }
390 }
391}
392
393void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000394 llvm::APSInt elementIndex,
395 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000396 unsigned &Index,
397 InitListExpr *StructuredList,
398 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000399 // Check for the special-case of initializing an array with a string.
400 if (Index < IList->getNumInits()) {
401 if (StringLiteral *lit =
402 SemaRef->IsStringLiteralInit(IList->getInit(Index), DeclType)) {
403 SemaRef->CheckStringLiteralInit(lit, DeclType);
Douglas Gregorf603b472009-01-28 21:54:33 +0000404 // We place the string literal directly into the resulting
405 // initializer list. This is the only place where the structure
406 // of the structured initializer list doesn't match exactly,
407 // because doing so would involve allocating one character
408 // constant for each string.
409 UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
410 StructuredList->resizeInits(SemaRef->Context, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000411 ++Index;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000412 return;
413 }
414 }
Chris Lattnera1923f62008-08-04 07:31:14 +0000415 if (const VariableArrayType *VAT =
416 SemaRef->Context.getAsVariableArrayType(DeclType)) {
Eli Friedman46f81662008-05-25 13:22:35 +0000417 // Check for VLAs; in standard C it would be possible to check this
418 // earlier, but I don't know where clang accepts VLAs (gcc accepts
419 // them in all sorts of strange places).
420 SemaRef->Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000421 diag::err_variable_object_no_init)
422 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman46f81662008-05-25 13:22:35 +0000423 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000424 ++Index;
425 ++StructuredIndex;
Eli Friedman46f81662008-05-25 13:22:35 +0000426 return;
427 }
428
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000429 // We might know the maximum number of elements in advance.
Douglas Gregorf603b472009-01-28 21:54:33 +0000430 llvm::APSInt maxElements(elementIndex.getBitWidth(),
431 elementIndex.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000432 bool maxElementsKnown = false;
433 if (const ConstantArrayType *CAT =
434 SemaRef->Context.getAsConstantArrayType(DeclType)) {
435 maxElements = CAT->getSize();
Douglas Gregor5a203a62009-01-23 16:54:12 +0000436 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000437 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000438 maxElementsKnown = true;
439 }
440
Chris Lattnera1923f62008-08-04 07:31:14 +0000441 QualType elementType = SemaRef->Context.getAsArrayType(DeclType)
442 ->getElementType();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000443 while (Index < IList->getNumInits()) {
444 Expr *Init = IList->getInit(Index);
445 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000446 // If we're not the subobject that matches up with the '{' for
447 // the designator, we shouldn't be handling the
448 // designator. Return immediately.
449 if (!SubobjectIsDesignatorContext)
450 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000451
Douglas Gregor710f6d42009-01-22 23:26:18 +0000452 // Handle this designated initializer. elementIndex will be
453 // updated to be the next array element we'll initialize.
454 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000455 DeclType, 0, &elementIndex, Index,
456 StructuredList, StructuredIndex)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000457 hadError = true;
458 continue;
459 }
460
Douglas Gregor5a203a62009-01-23 16:54:12 +0000461 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
462 maxElements.extend(elementIndex.getBitWidth());
463 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
464 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000465 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor5a203a62009-01-23 16:54:12 +0000466
Douglas Gregor710f6d42009-01-22 23:26:18 +0000467 // If the array is of incomplete type, keep track of the number of
468 // elements in the initializer.
469 if (!maxElementsKnown && elementIndex > maxElements)
470 maxElements = elementIndex;
471
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000472 continue;
473 }
474
475 // If we know the maximum number of elements, and we've already
476 // hit it, stop consuming elements in the initializer list.
477 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000478 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000479
480 // Check this element.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000481 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000482 StructuredList, StructuredIndex);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000483 ++elementIndex;
484
485 // If the array is of incomplete type, keep track of the number of
486 // elements in the initializer.
487 if (!maxElementsKnown && elementIndex > maxElements)
488 maxElements = elementIndex;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000489 }
490 if (DeclType->isIncompleteArrayType()) {
491 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000492 // be calculated here.
Douglas Gregor69722702009-01-23 18:58:42 +0000493 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000494 if (maxElements == Zero) {
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000495 // Sizing an array implicitly to zero is not allowed by ISO C,
496 // but is supported by GNU.
Steve Naroffc4d4a482008-05-01 22:18:59 +0000497 SemaRef->Diag(IList->getLocStart(),
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000498 diag::ext_typecheck_zero_array_size);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000499 }
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000500
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000501 DeclType = SemaRef->Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000502 ArrayType::Normal, 0);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000503 }
504}
505
506void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
507 QualType DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000508 RecordDecl::field_iterator Field,
509 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000510 unsigned &Index,
511 InitListExpr *StructuredList,
512 unsigned &StructuredIndex) {
Eli Friedman683cedf2008-05-19 19:16:24 +0000513 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000514
Eli Friedman683cedf2008-05-19 19:16:24 +0000515 // If the record is invalid, some of it's members are invalid. To avoid
516 // confusion, we forgo checking the intializer for the entire record.
517 if (structDecl->isInvalidDecl()) {
518 hadError = true;
519 return;
520 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000521 // If structDecl is a forward declaration, this loop won't do
522 // anything except look at designated initializers; That's okay,
523 // because an error should get printed out elsewhere. It might be
524 // worthwhile to skip over the rest of the initializer, though.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000525 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor710f6d42009-01-22 23:26:18 +0000526 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000527 while (Index < IList->getNumInits()) {
528 Expr *Init = IList->getInit(Index);
529
530 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000531 // If we're not the subobject that matches up with the '{' for
532 // the designator, we shouldn't be handling the
533 // designator. Return immediately.
534 if (!SubobjectIsDesignatorContext)
535 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000536
Douglas Gregor710f6d42009-01-22 23:26:18 +0000537 // Handle this designated initializer. Field will be updated to
538 // the next field that we'll be initializing.
539 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000540 DeclType, &Field, 0, Index,
541 StructuredList, StructuredIndex))
Douglas Gregor710f6d42009-01-22 23:26:18 +0000542 hadError = true;
543
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000544 continue;
545 }
546
547 if (Field == FieldEnd) {
548 // We've run out of fields. We're done.
549 break;
550 }
551
Douglas Gregor8acb7272008-12-11 16:49:14 +0000552 // If we've hit the flexible array member at the end, we're done.
553 if (Field->getType()->isIncompleteArrayType())
554 break;
555
Douglas Gregorf603b472009-01-28 21:54:33 +0000556 if (!Field->getIdentifier() && Field->isBitField()) {
557 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000558 ++Field;
Eli Friedman683cedf2008-05-19 19:16:24 +0000559 continue;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000560 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000561
Douglas Gregor36859eb2009-01-29 00:39:20 +0000562 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000563 StructuredList, StructuredIndex);
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000564 if (DeclType->isUnionType())
Eli Friedman683cedf2008-05-19 19:16:24 +0000565 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000566
567 ++Field;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000568 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000569
Eli Friedman683cedf2008-05-19 19:16:24 +0000570 // FIXME: Implement flexible array initialization GCC extension (it's a
571 // really messy extension to implement, unfortunately...the necessary
572 // information isn't actually even here!)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000573}
Steve Naroffc4d4a482008-05-01 22:18:59 +0000574
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000575/// @brief Check the well-formedness of a C99 designated initializer.
576///
577/// Determines whether the designated initializer @p DIE, which
578/// resides at the given @p Index within the initializer list @p
579/// IList, is well-formed for a current object of type @p DeclType
580/// (C99 6.7.8). The actual subobject that this designator refers to
581/// within the current subobject is returned in either
Douglas Gregorf603b472009-01-28 21:54:33 +0000582/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000583///
584/// @param IList The initializer list in which this designated
585/// initializer occurs.
586///
587/// @param DIE The designated initializer and its initialization
588/// expression.
589///
590/// @param DeclType The type of the "current object" (C99 6.7.8p17),
591/// into which the designation in @p DIE should refer.
592///
Douglas Gregor710f6d42009-01-22 23:26:18 +0000593/// @param NextField If non-NULL and the first designator in @p DIE is
594/// a field, this will be set to the field declaration corresponding
595/// to the field named by the designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000596///
Douglas Gregor710f6d42009-01-22 23:26:18 +0000597/// @param NextElementIndex If non-NULL and the first designator in @p
598/// DIE is an array designator or GNU array-range designator, this
599/// will be set to the last index initialized by this designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000600///
601/// @param Index Index into @p IList where the designated initializer
602/// @p DIE occurs.
603///
Douglas Gregorf603b472009-01-28 21:54:33 +0000604/// @param StructuredList The initializer list expression that
605/// describes all of the subobject initializers in the order they'll
606/// actually be initialized.
607///
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000608/// @returns true if there was an error, false otherwise.
Douglas Gregor710f6d42009-01-22 23:26:18 +0000609bool
610InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
611 DesignatedInitExpr *DIE,
612 DesignatedInitExpr::designators_iterator D,
613 QualType &CurrentObjectType,
614 RecordDecl::field_iterator *NextField,
615 llvm::APSInt *NextElementIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +0000616 unsigned &Index,
617 InitListExpr *StructuredList,
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000618 unsigned &StructuredIndex,
619 bool FinishSubobjectInit) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000620 if (D == DIE->designators_end()) {
621 // Check the actual initialization for the designated object type.
622 bool prevHadError = hadError;
Douglas Gregor36859eb2009-01-29 00:39:20 +0000623
624 // Temporarily remove the designator expression from the
625 // initializer list that the child calls see, so that we don't try
626 // to re-process the designator.
627 unsigned OldIndex = Index;
628 IList->setInit(OldIndex, DIE->getInit());
629
630 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000631 StructuredList, StructuredIndex);
Douglas Gregor36859eb2009-01-29 00:39:20 +0000632
633 // Restore the designated initializer expression in the syntactic
634 // form of the initializer list.
635 if (IList->getInit(OldIndex) != DIE->getInit())
636 DIE->setInit(IList->getInit(OldIndex));
637 IList->setInit(OldIndex, DIE);
638
Douglas Gregor710f6d42009-01-22 23:26:18 +0000639 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000640 }
641
Douglas Gregorf603b472009-01-28 21:54:33 +0000642 bool IsFirstDesignator = (D == DIE->designators_begin());
643 assert((IsFirstDesignator || StructuredList) &&
644 "Need a non-designated initializer list to start from");
645
646 // Determine the structural initializer list that corresponds to the
647 // current subobject.
648 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
649 : getStructuredSubobjectInit(IList, Index, CurrentObjectType, StructuredList,
650 StructuredIndex,
651 SourceRange(D->getStartLocation(),
652 DIE->getSourceRange().getEnd()));
653 assert(StructuredList && "Expected a structured initializer list");
654
Douglas Gregor710f6d42009-01-22 23:26:18 +0000655 if (D->isFieldDesignator()) {
656 // C99 6.7.8p7:
657 //
658 // If a designator has the form
659 //
660 // . identifier
661 //
662 // then the current object (defined below) shall have
663 // structure or union type and the identifier shall be the
664 // name of a member of that type.
665 const RecordType *RT = CurrentObjectType->getAsRecordType();
666 if (!RT) {
667 SourceLocation Loc = D->getDotLoc();
668 if (Loc.isInvalid())
669 Loc = D->getFieldLoc();
670 SemaRef->Diag(Loc, diag::err_field_designator_non_aggr)
671 << SemaRef->getLangOptions().CPlusPlus << CurrentObjectType;
672 ++Index;
673 return true;
674 }
675
Douglas Gregorf603b472009-01-28 21:54:33 +0000676 // Note: we perform a linear search of the fields here, despite
677 // the fact that we have a faster lookup method, because we always
678 // need to compute the field's index.
Douglas Gregor710f6d42009-01-22 23:26:18 +0000679 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregorf603b472009-01-28 21:54:33 +0000680 unsigned FieldIndex = 0;
681 RecordDecl::field_iterator Field = RT->getDecl()->field_begin(),
682 FieldEnd = RT->getDecl()->field_end();
683 for (; Field != FieldEnd; ++Field) {
684 if (Field->isUnnamedBitfield())
685 continue;
686
687 if (Field->getIdentifier() == FieldName)
688 break;
689
690 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000691 }
692
Douglas Gregorf603b472009-01-28 21:54:33 +0000693 if (Field == FieldEnd) {
694 // We did not find the field we're looking for. Produce a
695 // suitable diagnostic and return a failure.
696 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
697 if (Lookup.first == Lookup.second) {
698 // Name lookup didn't find anything.
699 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
700 << FieldName << CurrentObjectType;
701 } else {
702 // Name lookup found something, but it wasn't a field.
703 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
704 << FieldName;
705 SemaRef->Diag((*Lookup.first)->getLocation(),
706 diag::note_field_designator_found);
707 }
708
709 ++Index;
710 return true;
711 } else if (cast<RecordDecl>((*Field)->getDeclContext())
712 ->isAnonymousStructOrUnion()) {
713 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_anon_class)
714 << FieldName
715 << (cast<RecordDecl>((*Field)->getDeclContext())->isUnion()? 2 :
716 (int)SemaRef->getLangOptions().CPlusPlus);
717 SemaRef->Diag((*Field)->getLocation(), diag::note_field_designator_found);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000718 ++Index;
719 return true;
720 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000721
722 // All of the fields of a union are located at the same place in
723 // the initializer list.
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000724 if (RT->getDecl()->isUnion())
Douglas Gregorf603b472009-01-28 21:54:33 +0000725 FieldIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000726
Douglas Gregor710f6d42009-01-22 23:26:18 +0000727 // Update the designator with the field declaration.
Douglas Gregorf603b472009-01-28 21:54:33 +0000728 D->setField(*Field);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000729
Douglas Gregorf603b472009-01-28 21:54:33 +0000730 // Make sure that our non-designated initializer list has space
731 // for a subobject corresponding to this field.
732 if (FieldIndex >= StructuredList->getNumInits())
733 StructuredList->resizeInits(SemaRef->Context, FieldIndex + 1);
734
Douglas Gregor710f6d42009-01-22 23:26:18 +0000735 // Recurse to check later designated subobjects.
Douglas Gregorf603b472009-01-28 21:54:33 +0000736 QualType FieldType = (*Field)->getType();
737 unsigned newStructuredIndex = FieldIndex;
738 if (CheckDesignatedInitializer(IList, DIE, ++D, FieldType, 0, 0, Index,
739 StructuredList, newStructuredIndex))
Douglas Gregor710f6d42009-01-22 23:26:18 +0000740 return true;
741
742 // Find the position of the next field to be initialized in this
743 // subobject.
Douglas Gregor710f6d42009-01-22 23:26:18 +0000744 ++Field;
Douglas Gregorf603b472009-01-28 21:54:33 +0000745 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000746
747 // If this the first designator, our caller will continue checking
748 // the rest of this struct/class/union subobject.
749 if (IsFirstDesignator) {
750 if (NextField)
751 *NextField = Field;
Douglas Gregorf603b472009-01-28 21:54:33 +0000752 StructuredIndex = FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000753 return false;
754 }
755
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000756 if (!FinishSubobjectInit)
757 return false;
758
Douglas Gregor710f6d42009-01-22 23:26:18 +0000759 // Check the remaining fields within this class/struct/union subobject.
760 bool prevHadError = hadError;
Douglas Gregorf603b472009-01-28 21:54:33 +0000761 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
762 StructuredList, FieldIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000763 return hadError && !prevHadError;
764 }
765
766 // C99 6.7.8p6:
767 //
768 // If a designator has the form
769 //
770 // [ constant-expression ]
771 //
772 // then the current object (defined below) shall have array
773 // type and the expression shall be an integer constant
774 // expression. If the array is of unknown size, any
775 // nonnegative value is valid.
776 //
777 // Additionally, cope with the GNU extension that permits
778 // designators of the form
779 //
780 // [ constant-expression ... constant-expression ]
781 const ArrayType *AT = SemaRef->Context.getAsArrayType(CurrentObjectType);
782 if (!AT) {
783 SemaRef->Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
784 << CurrentObjectType;
785 ++Index;
786 return true;
787 }
788
789 Expr *IndexExpr = 0;
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000790 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
791 if (D->isArrayDesignator()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000792 IndexExpr = DIE->getArrayIndex(*D);
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000793
794 bool ConstExpr
795 = IndexExpr->isIntegerConstantExpr(DesignatedStartIndex, SemaRef->Context);
796 assert(ConstExpr && "Expression must be constant"); (void)ConstExpr;
797
798 DesignatedEndIndex = DesignatedStartIndex;
799 } else {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000800 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000801
802 bool StartConstExpr
803 = DIE->getArrayRangeStart(*D)->isIntegerConstantExpr(DesignatedStartIndex,
804 SemaRef->Context);
805 assert(StartConstExpr && "Expression must be constant"); (void)StartConstExpr;
806
807 bool EndConstExpr
808 = DIE->getArrayRangeEnd(*D)->isIntegerConstantExpr(DesignatedEndIndex,
809 SemaRef->Context);
810 assert(EndConstExpr && "Expression must be constant"); (void)EndConstExpr;
811
Douglas Gregor710f6d42009-01-22 23:26:18 +0000812 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000813
814 if (DesignatedStartIndex.getZExtValue() != DesignatedEndIndex.getZExtValue())
815 SemaRef->Diag(D->getEllipsisLoc(),
816 diag::warn_gnu_array_range_designator_side_effects)
817 << SourceRange(D->getLBracketLoc(), D->getRBracketLoc());
Douglas Gregor710f6d42009-01-22 23:26:18 +0000818 }
819
Douglas Gregor710f6d42009-01-22 23:26:18 +0000820 if (isa<ConstantArrayType>(AT)) {
821 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000822 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
823 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
824 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
825 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
826 if (DesignatedEndIndex >= MaxElements) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000827 SemaRef->Diag(IndexExpr->getSourceRange().getBegin(),
828 diag::err_array_designator_too_large)
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000829 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor710f6d42009-01-22 23:26:18 +0000830 << IndexExpr->getSourceRange();
831 ++Index;
832 return true;
833 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000834 } else {
835 // Make sure the bit-widths and signedness match.
836 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
837 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
838 else if (DesignatedStartIndex.getBitWidth() < DesignatedEndIndex.getBitWidth())
839 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
840 DesignatedStartIndex.setIsUnsigned(true);
841 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000842 }
843
Douglas Gregorf603b472009-01-28 21:54:33 +0000844 // Make sure that our non-designated initializer list has space
845 // for a subobject corresponding to this array element.
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000846 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
847 StructuredList->resizeInits(SemaRef->Context,
848 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +0000849
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000850 // Repeatedly perform subobject initializations in the range
851 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor710f6d42009-01-22 23:26:18 +0000852
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000853 // Move to the next designator
854 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
855 unsigned OldIndex = Index;
856 ++D;
857 while (DesignatedStartIndex <= DesignatedEndIndex) {
858 // Recurse to check later designated subobjects.
859 QualType ElementType = AT->getElementType();
860 Index = OldIndex;
861 if (CheckDesignatedInitializer(IList, DIE, D, ElementType, 0, 0, Index,
862 StructuredList, ElementIndex,
863 (DesignatedStartIndex == DesignatedEndIndex)))
864 return true;
865
866 // Move to the next index in the array that we'll be initializing.
867 ++DesignatedStartIndex;
868 ElementIndex = DesignatedStartIndex.getZExtValue();
869 }
Douglas Gregor710f6d42009-01-22 23:26:18 +0000870
871 // If this the first designator, our caller will continue checking
872 // the rest of this array subobject.
873 if (IsFirstDesignator) {
874 if (NextElementIndex)
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000875 *NextElementIndex = DesignatedStartIndex;
Douglas Gregorf603b472009-01-28 21:54:33 +0000876 StructuredIndex = ElementIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000877 return false;
878 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000879
880 if (!FinishSubobjectInit)
881 return false;
882
Douglas Gregor710f6d42009-01-22 23:26:18 +0000883 // Check the remaining elements within this array subobject.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000884 bool prevHadError = hadError;
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000885 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, true, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000886 StructuredList, ElementIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000887 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000888}
889
Douglas Gregorf603b472009-01-28 21:54:33 +0000890// Get the structured initializer list for a subobject of type
891// @p CurrentObjectType.
892InitListExpr *
893InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
894 QualType CurrentObjectType,
895 InitListExpr *StructuredList,
896 unsigned StructuredIndex,
897 SourceRange InitRange) {
898 Expr *ExistingInit = 0;
899 if (!StructuredList)
900 ExistingInit = SyntacticToSemantic[IList];
901 else if (StructuredIndex < StructuredList->getNumInits())
902 ExistingInit = StructuredList->getInit(StructuredIndex);
903
904 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
905 return Result;
906
907 if (ExistingInit) {
908 // We are creating an initializer list that initializes the
909 // subobjects of the current object, but there was already an
910 // initialization that completely initialized the current
911 // subobject, e.g., by a compound literal:
912 //
913 // struct X { int a, b; };
914 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
915 //
916 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
917 // designated initializer re-initializes the whole
918 // subobject [0], overwriting previous initializers.
919 SemaRef->Diag(InitRange.getBegin(), diag::warn_subobject_initializer_overrides)
920 << InitRange;
921 SemaRef->Diag(ExistingInit->getSourceRange().getBegin(),
922 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +0000923 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +0000924 << ExistingInit->getSourceRange();
925 }
926
927 InitListExpr *Result
928 = new (SemaRef->Context) InitListExpr(SourceLocation(), 0, 0,
929 SourceLocation());
930 Result->setType(CurrentObjectType);
931
932 // Link this new initializer list into the structured initializer
933 // lists.
934 if (StructuredList)
935 StructuredList->updateInit(StructuredIndex, Result);
936 else {
937 Result->setSyntacticForm(IList);
938 SyntacticToSemantic[IList] = Result;
939 }
940
941 return Result;
942}
943
944/// Update the initializer at index @p StructuredIndex within the
945/// structured initializer list to the value @p expr.
946void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
947 unsigned &StructuredIndex,
948 Expr *expr) {
949 // No structured initializer list to update
950 if (!StructuredList)
951 return;
952
953 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
954 // This initializer overwrites a previous initializer. Warn.
955 SemaRef->Diag(expr->getSourceRange().getBegin(),
956 diag::warn_initializer_overrides)
957 << expr->getSourceRange();
958 SemaRef->Diag(PrevInit->getSourceRange().getBegin(),
959 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +0000960 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +0000961 << PrevInit->getSourceRange();
962 }
963
964 ++StructuredIndex;
965}
966
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000967/// Check that the given Index expression is a valid array designator
968/// value. This is essentailly just a wrapper around
969/// Expr::isIntegerConstantExpr that also checks for negative values
970/// and produces a reasonable diagnostic if there is a
971/// failure. Returns true if there was an error, false otherwise. If
972/// everything went okay, Value will receive the value of the constant
973/// expression.
974static bool
975CheckArrayDesignatorExpr(Sema &Self, Expr *Index, llvm::APSInt &Value) {
976 SourceLocation Loc = Index->getSourceRange().getBegin();
977
978 // Make sure this is an integer constant expression.
979 if (!Index->isIntegerConstantExpr(Value, Self.Context, &Loc))
980 return Self.Diag(Loc, diag::err_array_designator_nonconstant)
981 << Index->getSourceRange();
982
983 // Make sure this constant expression is non-negative.
Douglas Gregor69722702009-01-23 18:58:42 +0000984 llvm::APSInt Zero(llvm::APSInt::getNullValue(Value.getBitWidth()),
985 Value.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000986 if (Value < Zero)
987 return Self.Diag(Loc, diag::err_array_designator_negative)
988 << Value.toString(10) << Index->getSourceRange();
989
Douglas Gregore498e372009-01-23 21:04:18 +0000990 Value.setIsUnsigned(true);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000991 return false;
992}
993
994Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
995 SourceLocation Loc,
996 bool UsedColonSyntax,
997 OwningExprResult Init) {
998 typedef DesignatedInitExpr::Designator ASTDesignator;
999
1000 bool Invalid = false;
1001 llvm::SmallVector<ASTDesignator, 32> Designators;
1002 llvm::SmallVector<Expr *, 32> InitExpressions;
1003
1004 // Build designators and check array designator expressions.
1005 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1006 const Designator &D = Desig.getDesignator(Idx);
1007 switch (D.getKind()) {
1008 case Designator::FieldDesignator:
1009 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1010 D.getFieldLoc()));
1011 break;
1012
1013 case Designator::ArrayDesignator: {
1014 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1015 llvm::APSInt IndexValue;
1016 if (CheckArrayDesignatorExpr(*this, Index, IndexValue))
1017 Invalid = true;
1018 else {
1019 Designators.push_back(ASTDesignator(InitExpressions.size(),
1020 D.getLBracketLoc(),
1021 D.getRBracketLoc()));
1022 InitExpressions.push_back(Index);
1023 }
1024 break;
1025 }
1026
1027 case Designator::ArrayRangeDesignator: {
1028 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1029 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1030 llvm::APSInt StartValue;
1031 llvm::APSInt EndValue;
1032 if (CheckArrayDesignatorExpr(*this, StartIndex, StartValue) ||
1033 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))
1034 Invalid = true;
Douglas Gregorea0528d2009-01-23 22:22:29 +00001035 else {
1036 // Make sure we're comparing values with the same bit width.
1037 if (StartValue.getBitWidth() > EndValue.getBitWidth())
1038 EndValue.extend(StartValue.getBitWidth());
1039 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1040 StartValue.extend(EndValue.getBitWidth());
1041
1042 if (EndValue < StartValue) {
1043 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1044 << StartValue.toString(10) << EndValue.toString(10)
1045 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1046 Invalid = true;
1047 } else {
1048 Designators.push_back(ASTDesignator(InitExpressions.size(),
1049 D.getLBracketLoc(),
1050 D.getEllipsisLoc(),
1051 D.getRBracketLoc()));
1052 InitExpressions.push_back(StartIndex);
1053 InitExpressions.push_back(EndIndex);
1054 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001055 }
1056 break;
1057 }
1058 }
1059 }
1060
1061 if (Invalid || Init.isInvalid())
1062 return ExprError();
1063
1064 // Clear out the expressions within the designation.
1065 Desig.ClearExprs(*this);
1066
1067 DesignatedInitExpr *DIE
1068 = DesignatedInitExpr::Create(Context, &Designators[0], Designators.size(),
1069 &InitExpressions[0], InitExpressions.size(),
1070 Loc, UsedColonSyntax,
1071 static_cast<Expr *>(Init.release()));
1072 return Owned(DIE);
1073}
Douglas Gregor849afc32009-01-29 00:45:39 +00001074
1075bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
1076 InitListChecker CheckInitList(this, InitList, DeclType);
1077 if (!CheckInitList.HadError())
1078 InitList = CheckInitList.getFullyStructuredList();
1079
1080 return CheckInitList.HadError();
1081}