blob: 511a394d8f268226cc781a0158bc9db055f45a8b [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 Gregorc5a6bdc2009-01-22 00:58:24 +000020using namespace clang;
Steve Naroffc4d4a482008-05-01 22:18:59 +000021
Douglas Gregorf603b472009-01-28 21:54:33 +000022/// Recursively replaces NULL values within the given initializer list
23/// with expressions that perform value-initialization of the
24/// appropriate type.
25static void fillInValueInitializations(ASTContext &Context, InitListExpr *ILE) {
26 assert((ILE->getType() != Context.VoidTy) && "Should not have void type");
27 if (const RecordType *RType = ILE->getType()->getAsRecordType()) {
28 unsigned Init = 0, NumInits = ILE->getNumInits();
29 for (RecordDecl::field_iterator Field = RType->getDecl()->field_begin(),
30 FieldEnd = RType->getDecl()->field_end();
31 Field != FieldEnd; ++Field) {
32 if (Field->isUnnamedBitfield())
33 continue;
34
35 if (Init >= NumInits)
36 break;
37
38 // FIXME: Check for fields with reference type in C++?
39 if (!ILE->getInit(Init))
40 ILE->setInit(Init,
41 new (Context) CXXZeroInitValueExpr(Field->getType(),
42 SourceLocation(),
43 SourceLocation()));
44 else if (InitListExpr *InnerILE = dyn_cast<InitListExpr>(ILE->getInit(Init)))
45 fillInValueInitializations(Context, InnerILE);
46 ++Init;
47 }
48
49 return;
50 }
51
52 QualType ElementType;
53
54 if (const ArrayType *AType = Context.getAsArrayType(ILE->getType()))
55 ElementType = AType->getElementType();
56 else if (const VectorType *VType = ILE->getType()->getAsVectorType())
57 ElementType = VType->getElementType();
58 else
59 ElementType = ILE->getType();
60
61 for (unsigned Init = 0, NumInits = ILE->getNumInits(); Init != NumInits;
62 ++Init) {
63 if (!ILE->getInit(Init))
64 ILE->setInit(Init, new (Context) CXXZeroInitValueExpr(ElementType,
65 SourceLocation(),
66 SourceLocation()));
67 else if (InitListExpr *InnerILE = dyn_cast<InitListExpr>(ILE->getInit(Init)))
68 fillInValueInitializations(Context, InnerILE);
69 }
70}
71
Steve Naroffc4d4a482008-05-01 22:18:59 +000072InitListChecker::InitListChecker(Sema *S, InitListExpr *IL, QualType &T) {
73 hadError = false;
74 SemaRef = S;
Eli Friedmand8535af2008-05-19 20:00:43 +000075
Eli Friedman683cedf2008-05-19 19:16:24 +000076 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +000077 unsigned newStructuredIndex = 0;
78 FullyStructuredList
79 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, SourceRange());
80 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +000081
Douglas Gregorf603b472009-01-28 21:54:33 +000082 if (!hadError) {
83 fillInValueInitializations(SemaRef->Context, FullyStructuredList);
84 }
Steve Naroffc4d4a482008-05-01 22:18:59 +000085}
86
87int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman46f81662008-05-25 13:22:35 +000088 // FIXME: use a proper constant
89 int maxElements = 0x7FFFFFFF;
Chris Lattnera1923f62008-08-04 07:31:14 +000090 if (const ConstantArrayType *CAT =
91 SemaRef->Context.getAsConstantArrayType(DeclType)) {
Steve Naroffc4d4a482008-05-01 22:18:59 +000092 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
93 }
94 return maxElements;
95}
96
97int InitListChecker::numStructUnionElements(QualType DeclType) {
98 RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl();
Douglas Gregorf603b472009-01-28 21:54:33 +000099 int InitializableMembers = 0;
100 for (RecordDecl::field_iterator Field = structDecl->field_begin(),
101 FieldEnd = structDecl->field_end();
102 Field != FieldEnd; ++Field) {
103 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
104 ++InitializableMembers;
105 }
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000106 if (structDecl->isUnion())
Eli Friedman9f5250b2008-05-25 14:03:31 +0000107 return std::min(InitializableMembers, 1);
108 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000109}
110
111void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregorf603b472009-01-28 21:54:33 +0000112 QualType T, unsigned &Index,
113 InitListExpr *StructuredList,
114 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000115 int maxElements = 0;
116
117 if (T->isArrayType())
118 maxElements = numArrayElements(T);
119 else if (T->isStructureType() || T->isUnionType())
120 maxElements = numStructUnionElements(T);
Eli Friedman683cedf2008-05-19 19:16:24 +0000121 else if (T->isVectorType())
122 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000123 else
124 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman683cedf2008-05-19 19:16:24 +0000125
Douglas Gregorf603b472009-01-28 21:54:33 +0000126 // FIXME: Perhaps we should move this warning elsewhere?
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000127 if (maxElements == 0) {
128 SemaRef->Diag(ParentIList->getInit(Index)->getLocStart(),
129 diag::err_implicit_empty_initializer);
Douglas Gregorf603b472009-01-28 21:54:33 +0000130 ++Index;
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000131 hadError = true;
132 return;
133 }
134
Douglas Gregorf603b472009-01-28 21:54:33 +0000135 // Build a structured initializer list corresponding to this subobject.
136 InitListExpr *StructuredSubobjectInitList
137 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
138 StructuredIndex,
139 ParentIList->getInit(Index)->getSourceRange());
140 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman683cedf2008-05-19 19:16:24 +0000141
Douglas Gregorf603b472009-01-28 21:54:33 +0000142 // Check the element types and build the structural subobject.
143 CheckListElementTypes(ParentIList, T, false, Index,
144 StructuredSubobjectInitList,
145 StructuredSubobjectInitIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000146}
147
Steve Naroff56099522008-05-06 00:23:44 +0000148void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregorf603b472009-01-28 21:54:33 +0000149 unsigned &Index,
150 InitListExpr *StructuredList,
151 unsigned &StructuredIndex) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000152 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregorf603b472009-01-28 21:54:33 +0000153 SyntacticToSemantic[IList] = StructuredList;
154 StructuredList->setSyntacticForm(IList);
155 CheckListElementTypes(IList, T, true, Index, StructuredList,
156 StructuredIndex);
Steve Naroff56099522008-05-06 00:23:44 +0000157 IList->setType(T);
Douglas Gregorf603b472009-01-28 21:54:33 +0000158 StructuredList->setType(T);
Eli Friedman46f81662008-05-25 13:22:35 +0000159 if (hadError)
160 return;
Eli Friedmand8535af2008-05-19 20:00:43 +0000161
Eli Friedman46f81662008-05-25 13:22:35 +0000162 if (Index < IList->getNumInits()) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000163 // We have leftover initializers
164 if (IList->getNumInits() > 0 &&
165 SemaRef->IsStringLiteralInit(IList->getInit(Index), T)) {
Eli Friedman71de9eb2008-05-19 20:12:18 +0000166 // Special-case
Eli Friedmand8535af2008-05-19 20:00:43 +0000167 SemaRef->Diag(IList->getInit(Index)->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000168 diag::err_excess_initializers_in_char_array_initializer)
169 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000170 hadError = true;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000171 } else if (!T->isIncompleteType()) {
172 // Don't warn for incomplete types, since we'll get an error elsewhere
Eli Friedmand8535af2008-05-19 20:00:43 +0000173 SemaRef->Diag(IList->getInit(Index)->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000174 diag::warn_excess_initializers)
175 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000176 }
177 }
Eli Friedman455f7622008-05-19 20:20:43 +0000178
Eli Friedman46f81662008-05-25 13:22:35 +0000179 if (T->isScalarType())
Chris Lattner9d2cf082008-11-19 05:27:50 +0000180 SemaRef->Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
181 << IList->getSourceRange();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000182}
183
Eli Friedman683cedf2008-05-19 19:16:24 +0000184void InitListChecker::CheckListElementTypes(InitListExpr *IList,
185 QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000186 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000187 unsigned &Index,
188 InitListExpr *StructuredList,
189 unsigned &StructuredIndex) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000190 if (DeclType->isScalarType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000191 CheckScalarType(IList, DeclType, 0, Index, StructuredList, StructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000192 } else if (DeclType->isVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000193 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000194 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000195 if (DeclType->isStructureType() || DeclType->isUnionType()) {
196 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
197 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000198 SubobjectIsDesignatorContext, Index,
199 StructuredList, StructuredIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000200 } else if (DeclType->isArrayType()) {
Douglas Gregor5a203a62009-01-23 16:54:12 +0000201 llvm::APSInt Zero(
202 SemaRef->Context.getTypeSize(SemaRef->Context.getSizeType()),
203 false);
Douglas Gregorf603b472009-01-28 21:54:33 +0000204 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
205 StructuredList, StructuredIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000206 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000207 else
Douglas Gregorf603b472009-01-28 21:54:33 +0000208 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffff5b3a82008-08-10 16:05:48 +0000209 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
210 // This type is invalid, issue a diagnostic.
Douglas Gregorf603b472009-01-28 21:54:33 +0000211 ++Index;
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000212 SemaRef->Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000213 << DeclType;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000214 hadError = true;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000215 } else {
216 // In C, all types are either scalars or aggregates, but
217 // additional handling is needed here for C++ (and possibly others?).
218 assert(0 && "Unsupported initializer type");
219 }
220}
221
Eli Friedman683cedf2008-05-19 19:16:24 +0000222void InitListChecker::CheckSubElementType(InitListExpr *IList,
223 QualType ElemType,
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000224 Expr *expr,
Douglas Gregorf603b472009-01-28 21:54:33 +0000225 unsigned &Index,
226 InitListExpr *StructuredList,
227 unsigned &StructuredIndex) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000228 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
229 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000230 unsigned newStructuredIndex = 0;
231 InitListExpr *newStructuredList
232 = getStructuredSubobjectInit(IList, Index, ElemType,
233 StructuredList, StructuredIndex,
234 SubInitList->getSourceRange());
235 CheckExplicitInitList(SubInitList, ElemType, newIndex,
236 newStructuredList, newStructuredIndex);
237 ++StructuredIndex;
238 ++Index;
Eli Friedman683cedf2008-05-19 19:16:24 +0000239 } else if (StringLiteral *lit =
240 SemaRef->IsStringLiteralInit(expr, ElemType)) {
241 SemaRef->CheckStringLiteralInit(lit, ElemType);
Douglas Gregorf603b472009-01-28 21:54:33 +0000242 UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
243 ++Index;
Eli Friedmand8535af2008-05-19 20:00:43 +0000244 } else if (ElemType->isScalarType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000245 CheckScalarType(IList, ElemType, expr, Index, StructuredList,
246 StructuredIndex);
Eli Friedman683cedf2008-05-19 19:16:24 +0000247 } else if (expr->getType()->getAsRecordType() &&
Eli Friedman2ccfb512008-06-09 03:52:40 +0000248 SemaRef->Context.typesAreCompatible(
249 expr->getType().getUnqualifiedType(),
250 ElemType.getUnqualifiedType())) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000251 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
252 ++Index;
Eli Friedman683cedf2008-05-19 19:16:24 +0000253 // FIXME: Add checking
254 } else {
Douglas Gregorf603b472009-01-28 21:54:33 +0000255 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
256 StructuredIndex);
257 ++StructuredIndex;
258 }
Eli Friedman683cedf2008-05-19 19:16:24 +0000259}
260
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000261void InitListChecker::CheckScalarType(InitListExpr *IList, QualType &DeclType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000262 Expr *expr, unsigned &Index,
263 InitListExpr *StructuredList,
264 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000265 if (Index < IList->getNumInits()) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000266 if (!expr)
267 expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000268 if (isa<InitListExpr>(expr)) {
Eli Friedman71de9eb2008-05-19 20:12:18 +0000269 SemaRef->Diag(IList->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000270 diag::err_many_braces_around_scalar_init)
271 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000272 hadError = true;
273 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000274 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000275 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000276 } else if (isa<DesignatedInitExpr>(expr)) {
277 SemaRef->Diag(expr->getSourceRange().getBegin(),
278 diag::err_designator_for_scalar_init)
279 << DeclType << expr->getSourceRange();
280 hadError = true;
281 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000282 ++StructuredIndex;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000283 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000284 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000285
Eli Friedmand8535af2008-05-19 20:00:43 +0000286 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000287 if (SemaRef->CheckSingleInitializer(expr, DeclType, false))
Eli Friedman71de9eb2008-05-19 20:12:18 +0000288 hadError = true; // types weren't compatible.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000289 else if (savExpr != expr) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000290 // The type was promoted, update initializer list.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000291 if (DesignatedInitExpr *DIE
292 = dyn_cast<DesignatedInitExpr>(IList->getInit(Index)))
293 DIE->setInit(expr);
294 else
295 IList->setInit(Index, expr);
Douglas Gregorf603b472009-01-28 21:54:33 +0000296
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000297 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000298 if (hadError)
299 ++StructuredIndex;
300 else
301 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000302 ++Index;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000303 } else {
Chris Lattner9d2cf082008-11-19 05:27:50 +0000304 SemaRef->Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
305 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000306 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000307 ++Index;
308 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000309 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000310 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000311}
312
313void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000314 unsigned &Index,
315 InitListExpr *StructuredList,
316 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000317 if (Index < IList->getNumInits()) {
318 const VectorType *VT = DeclType->getAsVectorType();
319 int maxElements = VT->getNumElements();
320 QualType elementType = VT->getElementType();
321
322 for (int i = 0; i < maxElements; ++i) {
323 // Don't attempt to go past the end of the init list
324 if (Index >= IList->getNumInits())
325 break;
Douglas Gregorf603b472009-01-28 21:54:33 +0000326 CheckSubElementType(IList, elementType, IList->getInit(Index), Index,
327 StructuredList, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000328 }
329 }
330}
331
332void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000333 llvm::APSInt elementIndex,
334 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000335 unsigned &Index,
336 InitListExpr *StructuredList,
337 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000338 // Check for the special-case of initializing an array with a string.
339 if (Index < IList->getNumInits()) {
340 if (StringLiteral *lit =
341 SemaRef->IsStringLiteralInit(IList->getInit(Index), DeclType)) {
342 SemaRef->CheckStringLiteralInit(lit, DeclType);
Douglas Gregorf603b472009-01-28 21:54:33 +0000343 // We place the string literal directly into the resulting
344 // initializer list. This is the only place where the structure
345 // of the structured initializer list doesn't match exactly,
346 // because doing so would involve allocating one character
347 // constant for each string.
348 UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
349 StructuredList->resizeInits(SemaRef->Context, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000350 ++Index;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000351 return;
352 }
353 }
Chris Lattnera1923f62008-08-04 07:31:14 +0000354 if (const VariableArrayType *VAT =
355 SemaRef->Context.getAsVariableArrayType(DeclType)) {
Eli Friedman46f81662008-05-25 13:22:35 +0000356 // Check for VLAs; in standard C it would be possible to check this
357 // earlier, but I don't know where clang accepts VLAs (gcc accepts
358 // them in all sorts of strange places).
359 SemaRef->Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000360 diag::err_variable_object_no_init)
361 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman46f81662008-05-25 13:22:35 +0000362 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000363 ++Index;
364 ++StructuredIndex;
Eli Friedman46f81662008-05-25 13:22:35 +0000365 return;
366 }
367
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000368 // We might know the maximum number of elements in advance.
Douglas Gregorf603b472009-01-28 21:54:33 +0000369 llvm::APSInt maxElements(elementIndex.getBitWidth(),
370 elementIndex.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000371 bool maxElementsKnown = false;
372 if (const ConstantArrayType *CAT =
373 SemaRef->Context.getAsConstantArrayType(DeclType)) {
374 maxElements = CAT->getSize();
Douglas Gregor5a203a62009-01-23 16:54:12 +0000375 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000376 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000377 maxElementsKnown = true;
378 }
379
Chris Lattnera1923f62008-08-04 07:31:14 +0000380 QualType elementType = SemaRef->Context.getAsArrayType(DeclType)
381 ->getElementType();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000382 while (Index < IList->getNumInits()) {
383 Expr *Init = IList->getInit(Index);
384 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000385 // If we're not the subobject that matches up with the '{' for
386 // the designator, we shouldn't be handling the
387 // designator. Return immediately.
388 if (!SubobjectIsDesignatorContext)
389 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000390
Douglas Gregor710f6d42009-01-22 23:26:18 +0000391 // Handle this designated initializer. elementIndex will be
392 // updated to be the next array element we'll initialize.
393 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000394 DeclType, 0, &elementIndex, Index,
395 StructuredList, StructuredIndex)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000396 hadError = true;
397 continue;
398 }
399
Douglas Gregor5a203a62009-01-23 16:54:12 +0000400 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
401 maxElements.extend(elementIndex.getBitWidth());
402 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
403 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000404 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor5a203a62009-01-23 16:54:12 +0000405
Douglas Gregor710f6d42009-01-22 23:26:18 +0000406 // If the array is of incomplete type, keep track of the number of
407 // elements in the initializer.
408 if (!maxElementsKnown && elementIndex > maxElements)
409 maxElements = elementIndex;
410
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000411 continue;
412 }
413
414 // If we know the maximum number of elements, and we've already
415 // hit it, stop consuming elements in the initializer list.
416 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000417 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000418
419 // Check this element.
Douglas Gregorf603b472009-01-28 21:54:33 +0000420 CheckSubElementType(IList, elementType, IList->getInit(Index), Index,
421 StructuredList, StructuredIndex);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000422 ++elementIndex;
423
424 // If the array is of incomplete type, keep track of the number of
425 // elements in the initializer.
426 if (!maxElementsKnown && elementIndex > maxElements)
427 maxElements = elementIndex;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000428 }
429 if (DeclType->isIncompleteArrayType()) {
430 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000431 // be calculated here.
Douglas Gregor69722702009-01-23 18:58:42 +0000432 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000433 if (maxElements == Zero) {
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000434 // Sizing an array implicitly to zero is not allowed by ISO C,
435 // but is supported by GNU.
Steve Naroffc4d4a482008-05-01 22:18:59 +0000436 SemaRef->Diag(IList->getLocStart(),
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000437 diag::ext_typecheck_zero_array_size);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000438 }
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000439
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000440 DeclType = SemaRef->Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000441 ArrayType::Normal, 0);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000442 }
443}
444
445void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
446 QualType DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000447 RecordDecl::field_iterator Field,
448 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000449 unsigned &Index,
450 InitListExpr *StructuredList,
451 unsigned &StructuredIndex) {
Eli Friedman683cedf2008-05-19 19:16:24 +0000452 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000453
Eli Friedman683cedf2008-05-19 19:16:24 +0000454 // If the record is invalid, some of it's members are invalid. To avoid
455 // confusion, we forgo checking the intializer for the entire record.
456 if (structDecl->isInvalidDecl()) {
457 hadError = true;
458 return;
459 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000460 // If structDecl is a forward declaration, this loop won't do
461 // anything except look at designated initializers; That's okay,
462 // because an error should get printed out elsewhere. It might be
463 // worthwhile to skip over the rest of the initializer, though.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000464 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor710f6d42009-01-22 23:26:18 +0000465 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000466 while (Index < IList->getNumInits()) {
467 Expr *Init = IList->getInit(Index);
468
469 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000470 // If we're not the subobject that matches up with the '{' for
471 // the designator, we shouldn't be handling the
472 // designator. Return immediately.
473 if (!SubobjectIsDesignatorContext)
474 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000475
Douglas Gregor710f6d42009-01-22 23:26:18 +0000476 // Handle this designated initializer. Field will be updated to
477 // the next field that we'll be initializing.
478 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000479 DeclType, &Field, 0, Index,
480 StructuredList, StructuredIndex))
Douglas Gregor710f6d42009-01-22 23:26:18 +0000481 hadError = true;
482
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000483 continue;
484 }
485
486 if (Field == FieldEnd) {
487 // We've run out of fields. We're done.
488 break;
489 }
490
Douglas Gregor8acb7272008-12-11 16:49:14 +0000491 // If we've hit the flexible array member at the end, we're done.
492 if (Field->getType()->isIncompleteArrayType())
493 break;
494
Douglas Gregorf603b472009-01-28 21:54:33 +0000495 if (!Field->getIdentifier() && Field->isBitField()) {
496 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000497 ++Field;
Eli Friedman683cedf2008-05-19 19:16:24 +0000498 continue;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000499 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000500
Douglas Gregorf603b472009-01-28 21:54:33 +0000501 CheckSubElementType(IList, Field->getType(), IList->getInit(Index), Index,
502 StructuredList, StructuredIndex);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000503 if (DeclType->isUnionType()) // FIXME: designated initializers?
Eli Friedman683cedf2008-05-19 19:16:24 +0000504 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000505
506 ++Field;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000507 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000508
Eli Friedman683cedf2008-05-19 19:16:24 +0000509 // FIXME: Implement flexible array initialization GCC extension (it's a
510 // really messy extension to implement, unfortunately...the necessary
511 // information isn't actually even here!)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000512}
Steve Naroffc4d4a482008-05-01 22:18:59 +0000513
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000514/// @brief Check the well-formedness of a C99 designated initializer.
515///
516/// Determines whether the designated initializer @p DIE, which
517/// resides at the given @p Index within the initializer list @p
518/// IList, is well-formed for a current object of type @p DeclType
519/// (C99 6.7.8). The actual subobject that this designator refers to
520/// within the current subobject is returned in either
Douglas Gregorf603b472009-01-28 21:54:33 +0000521/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000522///
523/// @param IList The initializer list in which this designated
524/// initializer occurs.
525///
526/// @param DIE The designated initializer and its initialization
527/// expression.
528///
529/// @param DeclType The type of the "current object" (C99 6.7.8p17),
530/// into which the designation in @p DIE should refer.
531///
Douglas Gregor710f6d42009-01-22 23:26:18 +0000532/// @param NextField If non-NULL and the first designator in @p DIE is
533/// a field, this will be set to the field declaration corresponding
534/// to the field named by the designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000535///
Douglas Gregor710f6d42009-01-22 23:26:18 +0000536/// @param NextElementIndex If non-NULL and the first designator in @p
537/// DIE is an array designator or GNU array-range designator, this
538/// will be set to the last index initialized by this designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000539///
540/// @param Index Index into @p IList where the designated initializer
541/// @p DIE occurs.
542///
Douglas Gregorf603b472009-01-28 21:54:33 +0000543/// @param StructuredList The initializer list expression that
544/// describes all of the subobject initializers in the order they'll
545/// actually be initialized.
546///
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000547/// @returns true if there was an error, false otherwise.
Douglas Gregor710f6d42009-01-22 23:26:18 +0000548bool
549InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
550 DesignatedInitExpr *DIE,
551 DesignatedInitExpr::designators_iterator D,
552 QualType &CurrentObjectType,
553 RecordDecl::field_iterator *NextField,
554 llvm::APSInt *NextElementIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +0000555 unsigned &Index,
556 InitListExpr *StructuredList,
557 unsigned &StructuredIndex) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000558 if (D == DIE->designators_end()) {
559 // Check the actual initialization for the designated object type.
560 bool prevHadError = hadError;
Douglas Gregorf603b472009-01-28 21:54:33 +0000561 CheckSubElementType(IList, CurrentObjectType, DIE->getInit(), Index,
562 StructuredList, StructuredIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000563 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000564 }
565
Douglas Gregorf603b472009-01-28 21:54:33 +0000566 bool IsFirstDesignator = (D == DIE->designators_begin());
567 assert((IsFirstDesignator || StructuredList) &&
568 "Need a non-designated initializer list to start from");
569
570 // Determine the structural initializer list that corresponds to the
571 // current subobject.
572 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
573 : getStructuredSubobjectInit(IList, Index, CurrentObjectType, StructuredList,
574 StructuredIndex,
575 SourceRange(D->getStartLocation(),
576 DIE->getSourceRange().getEnd()));
577 assert(StructuredList && "Expected a structured initializer list");
578
Douglas Gregor710f6d42009-01-22 23:26:18 +0000579 if (D->isFieldDesignator()) {
580 // C99 6.7.8p7:
581 //
582 // If a designator has the form
583 //
584 // . identifier
585 //
586 // then the current object (defined below) shall have
587 // structure or union type and the identifier shall be the
588 // name of a member of that type.
589 const RecordType *RT = CurrentObjectType->getAsRecordType();
590 if (!RT) {
591 SourceLocation Loc = D->getDotLoc();
592 if (Loc.isInvalid())
593 Loc = D->getFieldLoc();
594 SemaRef->Diag(Loc, diag::err_field_designator_non_aggr)
595 << SemaRef->getLangOptions().CPlusPlus << CurrentObjectType;
596 ++Index;
597 return true;
598 }
599
Douglas Gregorf603b472009-01-28 21:54:33 +0000600 // Note: we perform a linear search of the fields here, despite
601 // the fact that we have a faster lookup method, because we always
602 // need to compute the field's index.
Douglas Gregor710f6d42009-01-22 23:26:18 +0000603 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregorf603b472009-01-28 21:54:33 +0000604 unsigned FieldIndex = 0;
605 RecordDecl::field_iterator Field = RT->getDecl()->field_begin(),
606 FieldEnd = RT->getDecl()->field_end();
607 for (; Field != FieldEnd; ++Field) {
608 if (Field->isUnnamedBitfield())
609 continue;
610
611 if (Field->getIdentifier() == FieldName)
612 break;
613
614 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000615 }
616
Douglas Gregorf603b472009-01-28 21:54:33 +0000617 if (Field == FieldEnd) {
618 // We did not find the field we're looking for. Produce a
619 // suitable diagnostic and return a failure.
620 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
621 if (Lookup.first == Lookup.second) {
622 // Name lookup didn't find anything.
623 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
624 << FieldName << CurrentObjectType;
625 } else {
626 // Name lookup found something, but it wasn't a field.
627 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
628 << FieldName;
629 SemaRef->Diag((*Lookup.first)->getLocation(),
630 diag::note_field_designator_found);
631 }
632
633 ++Index;
634 return true;
635 } else if (cast<RecordDecl>((*Field)->getDeclContext())
636 ->isAnonymousStructOrUnion()) {
637 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_anon_class)
638 << FieldName
639 << (cast<RecordDecl>((*Field)->getDeclContext())->isUnion()? 2 :
640 (int)SemaRef->getLangOptions().CPlusPlus);
641 SemaRef->Diag((*Field)->getLocation(), diag::note_field_designator_found);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000642 ++Index;
643 return true;
644 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000645
646 // All of the fields of a union are located at the same place in
647 // the initializer list.
648 // FIXME: Need to tell CodeGen which type to initialize to. ImplicitCastExpr?
649 if (RT->getDecl()->isUnion() && FieldIndex != 0) {
650 SemaRef->Diag(D->getStartLocation(),
651 diag::warn_designator_into_union_broken_init)
652 << SourceRange(D->getStartLocation(), DIE->getSourceRange().getEnd());
653 FieldIndex = 0;
654 }
655
Douglas Gregor710f6d42009-01-22 23:26:18 +0000656 // Update the designator with the field declaration.
Douglas Gregorf603b472009-01-28 21:54:33 +0000657 D->setField(*Field);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000658
Douglas Gregorf603b472009-01-28 21:54:33 +0000659 // Make sure that our non-designated initializer list has space
660 // for a subobject corresponding to this field.
661 if (FieldIndex >= StructuredList->getNumInits())
662 StructuredList->resizeInits(SemaRef->Context, FieldIndex + 1);
663
Douglas Gregor710f6d42009-01-22 23:26:18 +0000664 // Recurse to check later designated subobjects.
Douglas Gregorf603b472009-01-28 21:54:33 +0000665 QualType FieldType = (*Field)->getType();
666 unsigned newStructuredIndex = FieldIndex;
667 if (CheckDesignatedInitializer(IList, DIE, ++D, FieldType, 0, 0, Index,
668 StructuredList, newStructuredIndex))
Douglas Gregor710f6d42009-01-22 23:26:18 +0000669 return true;
670
671 // Find the position of the next field to be initialized in this
672 // subobject.
Douglas Gregor710f6d42009-01-22 23:26:18 +0000673 ++Field;
Douglas Gregorf603b472009-01-28 21:54:33 +0000674 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000675
676 // If this the first designator, our caller will continue checking
677 // the rest of this struct/class/union subobject.
678 if (IsFirstDesignator) {
679 if (NextField)
680 *NextField = Field;
Douglas Gregorf603b472009-01-28 21:54:33 +0000681 StructuredIndex = FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000682 return false;
683 }
684
685 // Check the remaining fields within this class/struct/union subobject.
686 bool prevHadError = hadError;
Douglas Gregorf603b472009-01-28 21:54:33 +0000687 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
688 StructuredList, FieldIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000689 return hadError && !prevHadError;
690 }
691
692 // C99 6.7.8p6:
693 //
694 // If a designator has the form
695 //
696 // [ constant-expression ]
697 //
698 // then the current object (defined below) shall have array
699 // type and the expression shall be an integer constant
700 // expression. If the array is of unknown size, any
701 // nonnegative value is valid.
702 //
703 // Additionally, cope with the GNU extension that permits
704 // designators of the form
705 //
706 // [ constant-expression ... constant-expression ]
707 const ArrayType *AT = SemaRef->Context.getAsArrayType(CurrentObjectType);
708 if (!AT) {
709 SemaRef->Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
710 << CurrentObjectType;
711 ++Index;
712 return true;
713 }
714
715 Expr *IndexExpr = 0;
716 llvm::APSInt DesignatedIndex;
717 if (D->isArrayDesignator())
718 IndexExpr = DIE->getArrayIndex(*D);
719 else {
720 assert(D->isArrayRangeDesignator() && "Need array-range designator");
721 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregorf603b472009-01-28 21:54:33 +0000722 SemaRef->Diag(D->getEllipsisLoc(),
723 diag::warn_gnu_array_range_designator_unsupported)
724 << SourceRange(D->getLBracketLoc(), D->getRBracketLoc());
Douglas Gregor710f6d42009-01-22 23:26:18 +0000725 }
726
727 bool ConstExpr
728 = IndexExpr->isIntegerConstantExpr(DesignatedIndex, SemaRef->Context);
729 assert(ConstExpr && "Expression must be constant"); (void)ConstExpr;
730
731 if (isa<ConstantArrayType>(AT)) {
732 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor5a203a62009-01-23 16:54:12 +0000733 DesignatedIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000734 DesignatedIndex.setIsUnsigned(MaxElements.isUnsigned());
Douglas Gregor710f6d42009-01-22 23:26:18 +0000735 if (DesignatedIndex >= MaxElements) {
736 SemaRef->Diag(IndexExpr->getSourceRange().getBegin(),
737 diag::err_array_designator_too_large)
738 << DesignatedIndex.toString(10) << MaxElements.toString(10)
739 << IndexExpr->getSourceRange();
740 ++Index;
741 return true;
742 }
743 }
744
Douglas Gregorf603b472009-01-28 21:54:33 +0000745 // Make sure that our non-designated initializer list has space
746 // for a subobject corresponding to this array element.
747 unsigned ElementIndex = DesignatedIndex.getZExtValue();
748 if (ElementIndex >= StructuredList->getNumInits())
749 StructuredList->resizeInits(SemaRef->Context, ElementIndex + 1);
750
Douglas Gregor710f6d42009-01-22 23:26:18 +0000751 // Recurse to check later designated subobjects.
752 QualType ElementType = AT->getElementType();
Douglas Gregorf603b472009-01-28 21:54:33 +0000753 if (CheckDesignatedInitializer(IList, DIE, ++D, ElementType, 0, 0, Index,
754 StructuredList, ElementIndex))
Douglas Gregor710f6d42009-01-22 23:26:18 +0000755 return true;
756
757 // Move to the next index in the array that we'll be initializing.
758 ++DesignatedIndex;
Douglas Gregorf603b472009-01-28 21:54:33 +0000759 ElementIndex = DesignatedIndex.getZExtValue();
Douglas Gregor710f6d42009-01-22 23:26:18 +0000760
761 // If this the first designator, our caller will continue checking
762 // the rest of this array subobject.
763 if (IsFirstDesignator) {
764 if (NextElementIndex)
765 *NextElementIndex = DesignatedIndex;
Douglas Gregorf603b472009-01-28 21:54:33 +0000766 StructuredIndex = ElementIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000767 return false;
768 }
769
770 // Check the remaining elements within this array subobject.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000771 bool prevHadError = hadError;
Douglas Gregorf603b472009-01-28 21:54:33 +0000772 CheckArrayType(IList, CurrentObjectType, DesignatedIndex, true, Index,
773 StructuredList, ElementIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000774 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000775}
776
Douglas Gregorf603b472009-01-28 21:54:33 +0000777// Get the structured initializer list for a subobject of type
778// @p CurrentObjectType.
779InitListExpr *
780InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
781 QualType CurrentObjectType,
782 InitListExpr *StructuredList,
783 unsigned StructuredIndex,
784 SourceRange InitRange) {
785 Expr *ExistingInit = 0;
786 if (!StructuredList)
787 ExistingInit = SyntacticToSemantic[IList];
788 else if (StructuredIndex < StructuredList->getNumInits())
789 ExistingInit = StructuredList->getInit(StructuredIndex);
790
791 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
792 return Result;
793
794 if (ExistingInit) {
795 // We are creating an initializer list that initializes the
796 // subobjects of the current object, but there was already an
797 // initialization that completely initialized the current
798 // subobject, e.g., by a compound literal:
799 //
800 // struct X { int a, b; };
801 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
802 //
803 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
804 // designated initializer re-initializes the whole
805 // subobject [0], overwriting previous initializers.
806 SemaRef->Diag(InitRange.getBegin(), diag::warn_subobject_initializer_overrides)
807 << InitRange;
808 SemaRef->Diag(ExistingInit->getSourceRange().getBegin(),
809 diag::note_previous_initializer)
810 << ExistingInit->hasSideEffects(SemaRef->Context)
811 << ExistingInit->getSourceRange();
812 }
813
814 InitListExpr *Result
815 = new (SemaRef->Context) InitListExpr(SourceLocation(), 0, 0,
816 SourceLocation());
817 Result->setType(CurrentObjectType);
818
819 // Link this new initializer list into the structured initializer
820 // lists.
821 if (StructuredList)
822 StructuredList->updateInit(StructuredIndex, Result);
823 else {
824 Result->setSyntacticForm(IList);
825 SyntacticToSemantic[IList] = Result;
826 }
827
828 return Result;
829}
830
831/// Update the initializer at index @p StructuredIndex within the
832/// structured initializer list to the value @p expr.
833void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
834 unsigned &StructuredIndex,
835 Expr *expr) {
836 // No structured initializer list to update
837 if (!StructuredList)
838 return;
839
840 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
841 // This initializer overwrites a previous initializer. Warn.
842 SemaRef->Diag(expr->getSourceRange().getBegin(),
843 diag::warn_initializer_overrides)
844 << expr->getSourceRange();
845 SemaRef->Diag(PrevInit->getSourceRange().getBegin(),
846 diag::note_previous_initializer)
847 << (int)PrevInit->hasSideEffects(SemaRef->Context)
848 << PrevInit->getSourceRange();
849 }
850
851 ++StructuredIndex;
852}
853
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000854/// Check that the given Index expression is a valid array designator
855/// value. This is essentailly just a wrapper around
856/// Expr::isIntegerConstantExpr that also checks for negative values
857/// and produces a reasonable diagnostic if there is a
858/// failure. Returns true if there was an error, false otherwise. If
859/// everything went okay, Value will receive the value of the constant
860/// expression.
861static bool
862CheckArrayDesignatorExpr(Sema &Self, Expr *Index, llvm::APSInt &Value) {
863 SourceLocation Loc = Index->getSourceRange().getBegin();
864
865 // Make sure this is an integer constant expression.
866 if (!Index->isIntegerConstantExpr(Value, Self.Context, &Loc))
867 return Self.Diag(Loc, diag::err_array_designator_nonconstant)
868 << Index->getSourceRange();
869
870 // Make sure this constant expression is non-negative.
Douglas Gregor69722702009-01-23 18:58:42 +0000871 llvm::APSInt Zero(llvm::APSInt::getNullValue(Value.getBitWidth()),
872 Value.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000873 if (Value < Zero)
874 return Self.Diag(Loc, diag::err_array_designator_negative)
875 << Value.toString(10) << Index->getSourceRange();
876
Douglas Gregore498e372009-01-23 21:04:18 +0000877 Value.setIsUnsigned(true);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000878 return false;
879}
880
881Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
882 SourceLocation Loc,
883 bool UsedColonSyntax,
884 OwningExprResult Init) {
885 typedef DesignatedInitExpr::Designator ASTDesignator;
886
887 bool Invalid = false;
888 llvm::SmallVector<ASTDesignator, 32> Designators;
889 llvm::SmallVector<Expr *, 32> InitExpressions;
890
891 // Build designators and check array designator expressions.
892 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
893 const Designator &D = Desig.getDesignator(Idx);
894 switch (D.getKind()) {
895 case Designator::FieldDesignator:
896 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
897 D.getFieldLoc()));
898 break;
899
900 case Designator::ArrayDesignator: {
901 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
902 llvm::APSInt IndexValue;
903 if (CheckArrayDesignatorExpr(*this, Index, IndexValue))
904 Invalid = true;
905 else {
906 Designators.push_back(ASTDesignator(InitExpressions.size(),
907 D.getLBracketLoc(),
908 D.getRBracketLoc()));
909 InitExpressions.push_back(Index);
910 }
911 break;
912 }
913
914 case Designator::ArrayRangeDesignator: {
915 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
916 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
917 llvm::APSInt StartValue;
918 llvm::APSInt EndValue;
919 if (CheckArrayDesignatorExpr(*this, StartIndex, StartValue) ||
920 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))
921 Invalid = true;
Douglas Gregorea0528d2009-01-23 22:22:29 +0000922 else {
923 // Make sure we're comparing values with the same bit width.
924 if (StartValue.getBitWidth() > EndValue.getBitWidth())
925 EndValue.extend(StartValue.getBitWidth());
926 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
927 StartValue.extend(EndValue.getBitWidth());
928
929 if (EndValue < StartValue) {
930 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
931 << StartValue.toString(10) << EndValue.toString(10)
932 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
933 Invalid = true;
934 } else {
935 Designators.push_back(ASTDesignator(InitExpressions.size(),
936 D.getLBracketLoc(),
937 D.getEllipsisLoc(),
938 D.getRBracketLoc()));
939 InitExpressions.push_back(StartIndex);
940 InitExpressions.push_back(EndIndex);
941 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000942 }
943 break;
944 }
945 }
946 }
947
948 if (Invalid || Init.isInvalid())
949 return ExprError();
950
951 // Clear out the expressions within the designation.
952 Desig.ClearExprs(*this);
953
954 DesignatedInitExpr *DIE
955 = DesignatedInitExpr::Create(Context, &Designators[0], Designators.size(),
956 &InitExpressions[0], InitExpressions.size(),
957 Loc, UsedColonSyntax,
958 static_cast<Expr *>(Init.release()));
959 return Owned(DIE);
960}