blob: 527f965dc3f6118b58e9b88055e037c5c0cb06c9 [file] [log] [blame]
Steve Naroff0cca7492008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Douglas Gregor9e80f722009-01-29 01:05:33 +000010// This file implements semantic analysis for initializers. The entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
Steve Naroff0cca7492008-05-01 22:18:59 +000013//
14//===----------------------------------------------------------------------===//
15
16#include "Sema.h"
Douglas Gregor05c13a32009-01-22 00:58:24 +000017#include "clang/Parse/Designator.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
Douglas Gregor4c678342009-01-28 21:54:33 +000020#include "clang/AST/ExprCXX.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000021#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000022using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000023
Douglas Gregor9e80f722009-01-29 01:05:33 +000024/// @brief Semantic checking for initializer lists.
25///
26/// The InitListChecker class contains a set of routines that each
27/// handle the initialization of a certain kind of entity, e.g.,
28/// arrays, vectors, struct/union types, scalars, etc. The
29/// InitListChecker itself performs a recursive walk of the subobject
30/// structure of the type to be initialized, while stepping through
31/// the initializer list one element at a time. The IList and Index
32/// parameters to each of the Check* routines contain the active
33/// (syntactic) initializer list and the index into that initializer
34/// list that represents the current initializer. Each routine is
35/// responsible for moving that Index forward as it consumes elements.
36///
37/// Each Check* routine also has a StructuredList/StructuredIndex
38/// arguments, which contains the current the "structured" (semantic)
39/// initializer list and the index into that initializer list where we
40/// are copying initializers as we map them over to the semantic
41/// list. Once we have completed our recursive walk of the subobject
42/// structure, we will have constructed a full semantic initializer
43/// list.
44///
45/// C99 designators cause changes in the initializer list traversal,
46/// because they make the initialization "jump" into a specific
47/// subobject and then continue the initialization from that
48/// point. CheckDesignatedInitializer() recursively steps into the
49/// designated subobject and manages backing out the recursion to
50/// initialize the subobjects after the one designated.
Chris Lattner68355a52009-01-29 05:10:57 +000051namespace clang {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000052class InitListChecker {
53 Sema *SemaRef;
54 bool hadError;
55 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
56 InitListExpr *FullyStructuredList;
57
58 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +000059 unsigned &Index, InitListExpr *StructuredList,
60 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000061 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +000062 unsigned &Index, InitListExpr *StructuredList,
63 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000064 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
65 bool SubobjectIsDesignatorContext,
66 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +000067 InitListExpr *StructuredList,
68 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000069 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
70 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +000071 InitListExpr *StructuredList,
72 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000073 // FIXME: Does DeclType need to be a reference type?
74 void CheckScalarType(InitListExpr *IList, QualType &DeclType,
75 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +000076 InitListExpr *StructuredList,
77 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000078 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +000079 InitListExpr *StructuredList,
80 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000081 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
82 RecordDecl::field_iterator Field,
83 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +000084 InitListExpr *StructuredList,
85 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000086 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
87 llvm::APSInt elementIndex,
88 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +000089 InitListExpr *StructuredList,
90 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000091 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
92 DesignatedInitExpr::designators_iterator D,
93 QualType &CurrentObjectType,
94 RecordDecl::field_iterator *NextField,
95 llvm::APSInt *NextElementIndex,
96 unsigned &Index,
97 InitListExpr *StructuredList,
98 unsigned &StructuredIndex,
99 bool FinishSubobjectInit = true);
100 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
101 QualType CurrentObjectType,
102 InitListExpr *StructuredList,
103 unsigned StructuredIndex,
104 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000105 void UpdateStructuredListElement(InitListExpr *StructuredList,
106 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000107 Expr *expr);
108 int numArrayElements(QualType DeclType);
109 int numStructUnionElements(QualType DeclType);
110public:
111 InitListChecker(Sema *S, InitListExpr *IL, QualType &T);
112 bool HadError() { return hadError; }
113
114 // @brief Retrieves the fully-structured initializer list used for
115 // semantic analysis and code generation.
116 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
117};
Chris Lattner68355a52009-01-29 05:10:57 +0000118}
119
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000120
Douglas Gregor4c678342009-01-28 21:54:33 +0000121/// Recursively replaces NULL values within the given initializer list
122/// with expressions that perform value-initialization of the
123/// appropriate type.
124static void fillInValueInitializations(ASTContext &Context, InitListExpr *ILE) {
125 assert((ILE->getType() != Context.VoidTy) && "Should not have void type");
126 if (const RecordType *RType = ILE->getType()->getAsRecordType()) {
127 unsigned Init = 0, NumInits = ILE->getNumInits();
128 for (RecordDecl::field_iterator Field = RType->getDecl()->field_begin(),
129 FieldEnd = RType->getDecl()->field_end();
130 Field != FieldEnd; ++Field) {
131 if (Field->isUnnamedBitfield())
132 continue;
133
134 if (Init >= NumInits)
135 break;
136
137 // FIXME: Check for fields with reference type in C++?
138 if (!ILE->getInit(Init))
139 ILE->setInit(Init,
140 new (Context) CXXZeroInitValueExpr(Field->getType(),
141 SourceLocation(),
142 SourceLocation()));
143 else if (InitListExpr *InnerILE = dyn_cast<InitListExpr>(ILE->getInit(Init)))
144 fillInValueInitializations(Context, InnerILE);
145 ++Init;
146 }
147
148 return;
149 }
150
151 QualType ElementType;
152
153 if (const ArrayType *AType = Context.getAsArrayType(ILE->getType()))
154 ElementType = AType->getElementType();
155 else if (const VectorType *VType = ILE->getType()->getAsVectorType())
156 ElementType = VType->getElementType();
157 else
158 ElementType = ILE->getType();
159
160 for (unsigned Init = 0, NumInits = ILE->getNumInits(); Init != NumInits;
161 ++Init) {
162 if (!ILE->getInit(Init))
163 ILE->setInit(Init, new (Context) CXXZeroInitValueExpr(ElementType,
164 SourceLocation(),
165 SourceLocation()));
Chris Lattner68355a52009-01-29 05:10:57 +0000166 else if (InitListExpr *InnerILE =dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor4c678342009-01-28 21:54:33 +0000167 fillInValueInitializations(Context, InnerILE);
168 }
169}
170
Chris Lattner68355a52009-01-29 05:10:57 +0000171
Steve Naroff0cca7492008-05-01 22:18:59 +0000172InitListChecker::InitListChecker(Sema *S, InitListExpr *IL, QualType &T) {
173 hadError = false;
174 SemaRef = S;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000175
Eli Friedmanb85f7072008-05-19 19:16:24 +0000176 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000177 unsigned newStructuredIndex = 0;
178 FullyStructuredList
179 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, SourceRange());
180 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000181
Douglas Gregor4c678342009-01-28 21:54:33 +0000182 if (!hadError) {
183 fillInValueInitializations(SemaRef->Context, FullyStructuredList);
184 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000185}
186
187int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000188 // FIXME: use a proper constant
189 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000190 if (const ConstantArrayType *CAT =
191 SemaRef->Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000192 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
193 }
194 return maxElements;
195}
196
197int InitListChecker::numStructUnionElements(QualType DeclType) {
198 RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000199 int InitializableMembers = 0;
200 for (RecordDecl::field_iterator Field = structDecl->field_begin(),
201 FieldEnd = structDecl->field_end();
202 Field != FieldEnd; ++Field) {
203 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
204 ++InitializableMembers;
205 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000206 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000207 return std::min(InitializableMembers, 1);
208 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000209}
210
211void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000212 QualType T, unsigned &Index,
213 InitListExpr *StructuredList,
214 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000215 int maxElements = 0;
216
217 if (T->isArrayType())
218 maxElements = numArrayElements(T);
219 else if (T->isStructureType() || T->isUnionType())
220 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000221 else if (T->isVectorType())
222 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000223 else
224 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000225
Douglas Gregor4c678342009-01-28 21:54:33 +0000226 // FIXME: Perhaps we should move this warning elsewhere?
Eli Friedman402256f2008-05-25 13:49:22 +0000227 if (maxElements == 0) {
228 SemaRef->Diag(ParentIList->getInit(Index)->getLocStart(),
229 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000230 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000231 hadError = true;
232 return;
233 }
234
Douglas Gregor4c678342009-01-28 21:54:33 +0000235 // Build a structured initializer list corresponding to this subobject.
236 InitListExpr *StructuredSubobjectInitList
237 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
238 StructuredIndex,
239 ParentIList->getInit(Index)->getSourceRange());
240 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000241
Douglas Gregor4c678342009-01-28 21:54:33 +0000242 // Check the element types and build the structural subobject.
243 CheckListElementTypes(ParentIList, T, false, Index,
244 StructuredSubobjectInitList,
245 StructuredSubobjectInitIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000246}
247
Steve Naroffa647caa2008-05-06 00:23:44 +0000248void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000249 unsigned &Index,
250 InitListExpr *StructuredList,
251 unsigned &StructuredIndex) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000252 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000253 SyntacticToSemantic[IList] = StructuredList;
254 StructuredList->setSyntacticForm(IList);
255 CheckListElementTypes(IList, T, true, Index, StructuredList,
256 StructuredIndex);
Steve Naroffa647caa2008-05-06 00:23:44 +0000257 IList->setType(T);
Douglas Gregor4c678342009-01-28 21:54:33 +0000258 StructuredList->setType(T);
Eli Friedman638e1442008-05-25 13:22:35 +0000259 if (hadError)
260 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000261
Eli Friedman638e1442008-05-25 13:22:35 +0000262 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000263 // We have leftover initializers
264 if (IList->getNumInits() > 0 &&
265 SemaRef->IsStringLiteralInit(IList->getInit(Index), T)) {
Eli Friedmanbb504d32008-05-19 20:12:18 +0000266 // Special-case
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000267 SemaRef->Diag(IList->getInit(Index)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000268 diag::err_excess_initializers_in_char_array_initializer)
269 << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000270 hadError = true;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000271 } else if (!T->isIncompleteType()) {
272 // Don't warn for incomplete types, since we'll get an error elsewhere
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000273 SemaRef->Diag(IList->getInit(Index)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000274 diag::warn_excess_initializers)
275 << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000276 }
277 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000278
Eli Friedman638e1442008-05-25 13:22:35 +0000279 if (T->isScalarType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000280 SemaRef->Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
281 << IList->getSourceRange();
Steve Naroff0cca7492008-05-01 22:18:59 +0000282}
283
Eli Friedmanb85f7072008-05-19 19:16:24 +0000284void InitListChecker::CheckListElementTypes(InitListExpr *IList,
285 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000286 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000287 unsigned &Index,
288 InitListExpr *StructuredList,
289 unsigned &StructuredIndex) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000290 if (DeclType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000291 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000292 } else if (DeclType->isVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000293 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000294 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000295 if (DeclType->isStructureType() || DeclType->isUnionType()) {
296 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
297 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000298 SubobjectIsDesignatorContext, Index,
299 StructuredList, StructuredIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000300 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000301 llvm::APSInt Zero(
302 SemaRef->Context.getTypeSize(SemaRef->Context.getSizeType()),
303 false);
Douglas Gregor4c678342009-01-28 21:54:33 +0000304 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
305 StructuredList, StructuredIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000306 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000307 else
Douglas Gregor4c678342009-01-28 21:54:33 +0000308 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000309 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
310 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000311 ++Index;
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000312 SemaRef->Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000313 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000314 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000315 } else {
316 // In C, all types are either scalars or aggregates, but
317 // additional handling is needed here for C++ (and possibly others?).
318 assert(0 && "Unsupported initializer type");
319 }
320}
321
Eli Friedmanb85f7072008-05-19 19:16:24 +0000322void InitListChecker::CheckSubElementType(InitListExpr *IList,
323 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000324 unsigned &Index,
325 InitListExpr *StructuredList,
326 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000327 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000328 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
329 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000330 unsigned newStructuredIndex = 0;
331 InitListExpr *newStructuredList
332 = getStructuredSubobjectInit(IList, Index, ElemType,
333 StructuredList, StructuredIndex,
334 SubInitList->getSourceRange());
335 CheckExplicitInitList(SubInitList, ElemType, newIndex,
336 newStructuredList, newStructuredIndex);
337 ++StructuredIndex;
338 ++Index;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000339 } else if (StringLiteral *lit =
340 SemaRef->IsStringLiteralInit(expr, ElemType)) {
341 SemaRef->CheckStringLiteralInit(lit, ElemType);
Douglas Gregor4c678342009-01-28 21:54:33 +0000342 UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
343 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000344 } else if (ElemType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000345 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000346 } else if (expr->getType()->getAsRecordType() &&
Eli Friedmanc92e5e42008-06-09 03:52:40 +0000347 SemaRef->Context.typesAreCompatible(
348 expr->getType().getUnqualifiedType(),
349 ElemType.getUnqualifiedType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000350 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
351 ++Index;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000352 // FIXME: Add checking
353 } else {
Douglas Gregor4c678342009-01-28 21:54:33 +0000354 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
355 StructuredIndex);
356 ++StructuredIndex;
357 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000358}
359
Douglas Gregor05c13a32009-01-22 00:58:24 +0000360void InitListChecker::CheckScalarType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000361 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000362 InitListExpr *StructuredList,
363 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000364 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000365 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000366 if (isa<InitListExpr>(expr)) {
Eli Friedmanbb504d32008-05-19 20:12:18 +0000367 SemaRef->Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000368 diag::err_many_braces_around_scalar_init)
369 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000370 hadError = true;
371 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000372 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000373 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000374 } else if (isa<DesignatedInitExpr>(expr)) {
375 SemaRef->Diag(expr->getSourceRange().getBegin(),
376 diag::err_designator_for_scalar_init)
377 << DeclType << expr->getSourceRange();
378 hadError = true;
379 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000380 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000381 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000382 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000383
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000384 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000385 if (SemaRef->CheckSingleInitializer(expr, DeclType, false))
Eli Friedmanbb504d32008-05-19 20:12:18 +0000386 hadError = true; // types weren't compatible.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000387 else if (savExpr != expr) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000388 // The type was promoted, update initializer list.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000389 IList->setInit(Index, expr);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000390 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000391 if (hadError)
392 ++StructuredIndex;
393 else
394 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000395 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000396 } else {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000397 SemaRef->Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
398 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000399 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000400 ++Index;
401 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000402 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000403 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000404}
405
406void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000407 unsigned &Index,
408 InitListExpr *StructuredList,
409 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000410 if (Index < IList->getNumInits()) {
411 const VectorType *VT = DeclType->getAsVectorType();
412 int maxElements = VT->getNumElements();
413 QualType elementType = VT->getElementType();
414
415 for (int i = 0; i < maxElements; ++i) {
416 // Don't attempt to go past the end of the init list
417 if (Index >= IList->getNumInits())
418 break;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000419 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000420 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000421 }
422 }
423}
424
425void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000426 llvm::APSInt elementIndex,
427 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000428 unsigned &Index,
429 InitListExpr *StructuredList,
430 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000431 // Check for the special-case of initializing an array with a string.
432 if (Index < IList->getNumInits()) {
433 if (StringLiteral *lit =
434 SemaRef->IsStringLiteralInit(IList->getInit(Index), DeclType)) {
435 SemaRef->CheckStringLiteralInit(lit, DeclType);
Douglas Gregor4c678342009-01-28 21:54:33 +0000436 // We place the string literal directly into the resulting
437 // initializer list. This is the only place where the structure
438 // of the structured initializer list doesn't match exactly,
439 // because doing so would involve allocating one character
440 // constant for each string.
441 UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
442 StructuredList->resizeInits(SemaRef->Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000443 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000444 return;
445 }
446 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000447 if (const VariableArrayType *VAT =
448 SemaRef->Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000449 // Check for VLAs; in standard C it would be possible to check this
450 // earlier, but I don't know where clang accepts VLAs (gcc accepts
451 // them in all sorts of strange places).
452 SemaRef->Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000453 diag::err_variable_object_no_init)
454 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000455 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000456 ++Index;
457 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000458 return;
459 }
460
Douglas Gregor05c13a32009-01-22 00:58:24 +0000461 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000462 llvm::APSInt maxElements(elementIndex.getBitWidth(),
463 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000464 bool maxElementsKnown = false;
465 if (const ConstantArrayType *CAT =
466 SemaRef->Context.getAsConstantArrayType(DeclType)) {
467 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000468 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000469 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000470 maxElementsKnown = true;
471 }
472
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000473 QualType elementType = SemaRef->Context.getAsArrayType(DeclType)
474 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000475 while (Index < IList->getNumInits()) {
476 Expr *Init = IList->getInit(Index);
477 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000478 // If we're not the subobject that matches up with the '{' for
479 // the designator, we shouldn't be handling the
480 // designator. Return immediately.
481 if (!SubobjectIsDesignatorContext)
482 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000483
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000484 // Handle this designated initializer. elementIndex will be
485 // updated to be the next array element we'll initialize.
486 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000487 DeclType, 0, &elementIndex, Index,
488 StructuredList, StructuredIndex)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000489 hadError = true;
490 continue;
491 }
492
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000493 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
494 maxElements.extend(elementIndex.getBitWidth());
495 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
496 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000497 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000498
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000499 // If the array is of incomplete type, keep track of the number of
500 // elements in the initializer.
501 if (!maxElementsKnown && elementIndex > maxElements)
502 maxElements = elementIndex;
503
Douglas Gregor05c13a32009-01-22 00:58:24 +0000504 continue;
505 }
506
507 // If we know the maximum number of elements, and we've already
508 // hit it, stop consuming elements in the initializer list.
509 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +0000510 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000511
512 // Check this element.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000513 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000514 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000515 ++elementIndex;
516
517 // If the array is of incomplete type, keep track of the number of
518 // elements in the initializer.
519 if (!maxElementsKnown && elementIndex > maxElements)
520 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +0000521 }
522 if (DeclType->isIncompleteArrayType()) {
523 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000524 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000525 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000526 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000527 // Sizing an array implicitly to zero is not allowed by ISO C,
528 // but is supported by GNU.
Steve Naroff0cca7492008-05-01 22:18:59 +0000529 SemaRef->Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000530 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +0000531 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000532
Douglas Gregor05c13a32009-01-22 00:58:24 +0000533 DeclType = SemaRef->Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000534 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +0000535 }
536}
537
538void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
539 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000540 RecordDecl::field_iterator Field,
541 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000542 unsigned &Index,
543 InitListExpr *StructuredList,
544 unsigned &StructuredIndex) {
Eli Friedmanb85f7072008-05-19 19:16:24 +0000545 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroff0cca7492008-05-01 22:18:59 +0000546
Eli Friedmanb85f7072008-05-19 19:16:24 +0000547 // If the record is invalid, some of it's members are invalid. To avoid
548 // confusion, we forgo checking the intializer for the entire record.
549 if (structDecl->isInvalidDecl()) {
550 hadError = true;
551 return;
552 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000553 // If structDecl is a forward declaration, this loop won't do
554 // anything except look at designated initializers; That's okay,
555 // because an error should get printed out elsewhere. It might be
556 // worthwhile to skip over the rest of the initializer, though.
Douglas Gregor44b43212008-12-11 16:49:14 +0000557 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000558 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000559 while (Index < IList->getNumInits()) {
560 Expr *Init = IList->getInit(Index);
561
562 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000563 // If we're not the subobject that matches up with the '{' for
564 // the designator, we shouldn't be handling the
565 // designator. Return immediately.
566 if (!SubobjectIsDesignatorContext)
567 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000568
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000569 // Handle this designated initializer. Field will be updated to
570 // the next field that we'll be initializing.
571 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000572 DeclType, &Field, 0, Index,
573 StructuredList, StructuredIndex))
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000574 hadError = true;
575
Douglas Gregor0bb76892009-01-29 16:53:55 +0000576 // Abort early for unions: the designator handled the
577 // initialization of the appropriate field.
578 if (DeclType->isUnionType())
579 break;
580
Douglas Gregor05c13a32009-01-22 00:58:24 +0000581 continue;
582 }
583
584 if (Field == FieldEnd) {
585 // We've run out of fields. We're done.
586 break;
587 }
588
Douglas Gregor44b43212008-12-11 16:49:14 +0000589 // If we've hit the flexible array member at the end, we're done.
590 if (Field->getType()->isIncompleteArrayType())
591 break;
592
Douglas Gregor0bb76892009-01-29 16:53:55 +0000593 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000594 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +0000595 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000596 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +0000597 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000598
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000599 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000600 StructuredList, StructuredIndex);
Douglas Gregor0bb76892009-01-29 16:53:55 +0000601
602 if (DeclType->isUnionType()) {
603 // Initialize the first field within the union.
604 StructuredList->setInitializedFieldInUnion(*Field);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000605 break;
Douglas Gregor0bb76892009-01-29 16:53:55 +0000606 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000607
608 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +0000609 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000610
Eli Friedmanb85f7072008-05-19 19:16:24 +0000611 // FIXME: Implement flexible array initialization GCC extension (it's a
612 // really messy extension to implement, unfortunately...the necessary
613 // information isn't actually even here!)
Steve Naroff0cca7492008-05-01 22:18:59 +0000614}
Steve Naroff0cca7492008-05-01 22:18:59 +0000615
Douglas Gregor05c13a32009-01-22 00:58:24 +0000616/// @brief Check the well-formedness of a C99 designated initializer.
617///
618/// Determines whether the designated initializer @p DIE, which
619/// resides at the given @p Index within the initializer list @p
620/// IList, is well-formed for a current object of type @p DeclType
621/// (C99 6.7.8). The actual subobject that this designator refers to
622/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +0000623/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +0000624///
625/// @param IList The initializer list in which this designated
626/// initializer occurs.
627///
628/// @param DIE The designated initializer and its initialization
629/// expression.
630///
631/// @param DeclType The type of the "current object" (C99 6.7.8p17),
632/// into which the designation in @p DIE should refer.
633///
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000634/// @param NextField If non-NULL and the first designator in @p DIE is
635/// a field, this will be set to the field declaration corresponding
636/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000637///
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000638/// @param NextElementIndex If non-NULL and the first designator in @p
639/// DIE is an array designator or GNU array-range designator, this
640/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000641///
642/// @param Index Index into @p IList where the designated initializer
643/// @p DIE occurs.
644///
Douglas Gregor4c678342009-01-28 21:54:33 +0000645/// @param StructuredList The initializer list expression that
646/// describes all of the subobject initializers in the order they'll
647/// actually be initialized.
648///
Douglas Gregor05c13a32009-01-22 00:58:24 +0000649/// @returns true if there was an error, false otherwise.
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000650bool
651InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
652 DesignatedInitExpr *DIE,
653 DesignatedInitExpr::designators_iterator D,
654 QualType &CurrentObjectType,
655 RecordDecl::field_iterator *NextField,
656 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000657 unsigned &Index,
658 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +0000659 unsigned &StructuredIndex,
660 bool FinishSubobjectInit) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000661 if (D == DIE->designators_end()) {
662 // Check the actual initialization for the designated object type.
663 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000664
665 // Temporarily remove the designator expression from the
666 // initializer list that the child calls see, so that we don't try
667 // to re-process the designator.
668 unsigned OldIndex = Index;
669 IList->setInit(OldIndex, DIE->getInit());
670
671 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000672 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000673
674 // Restore the designated initializer expression in the syntactic
675 // form of the initializer list.
676 if (IList->getInit(OldIndex) != DIE->getInit())
677 DIE->setInit(IList->getInit(OldIndex));
678 IList->setInit(OldIndex, DIE);
679
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000680 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000681 }
682
Douglas Gregor4c678342009-01-28 21:54:33 +0000683 bool IsFirstDesignator = (D == DIE->designators_begin());
684 assert((IsFirstDesignator || StructuredList) &&
685 "Need a non-designated initializer list to start from");
686
687 // Determine the structural initializer list that corresponds to the
688 // current subobject.
689 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
690 : getStructuredSubobjectInit(IList, Index, CurrentObjectType, StructuredList,
691 StructuredIndex,
692 SourceRange(D->getStartLocation(),
693 DIE->getSourceRange().getEnd()));
694 assert(StructuredList && "Expected a structured initializer list");
695
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000696 if (D->isFieldDesignator()) {
697 // C99 6.7.8p7:
698 //
699 // If a designator has the form
700 //
701 // . identifier
702 //
703 // then the current object (defined below) shall have
704 // structure or union type and the identifier shall be the
705 // name of a member of that type.
706 const RecordType *RT = CurrentObjectType->getAsRecordType();
707 if (!RT) {
708 SourceLocation Loc = D->getDotLoc();
709 if (Loc.isInvalid())
710 Loc = D->getFieldLoc();
711 SemaRef->Diag(Loc, diag::err_field_designator_non_aggr)
712 << SemaRef->getLangOptions().CPlusPlus << CurrentObjectType;
713 ++Index;
714 return true;
715 }
716
Douglas Gregor4c678342009-01-28 21:54:33 +0000717 // Note: we perform a linear search of the fields here, despite
718 // the fact that we have a faster lookup method, because we always
719 // need to compute the field's index.
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000720 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +0000721 unsigned FieldIndex = 0;
722 RecordDecl::field_iterator Field = RT->getDecl()->field_begin(),
723 FieldEnd = RT->getDecl()->field_end();
724 for (; Field != FieldEnd; ++Field) {
725 if (Field->isUnnamedBitfield())
726 continue;
727
728 if (Field->getIdentifier() == FieldName)
729 break;
730
731 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000732 }
733
Douglas Gregor4c678342009-01-28 21:54:33 +0000734 if (Field == FieldEnd) {
735 // We did not find the field we're looking for. Produce a
736 // suitable diagnostic and return a failure.
737 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
738 if (Lookup.first == Lookup.second) {
739 // Name lookup didn't find anything.
740 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
741 << FieldName << CurrentObjectType;
742 } else {
743 // Name lookup found something, but it wasn't a field.
744 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
745 << FieldName;
746 SemaRef->Diag((*Lookup.first)->getLocation(),
747 diag::note_field_designator_found);
748 }
749
750 ++Index;
751 return true;
752 } else if (cast<RecordDecl>((*Field)->getDeclContext())
753 ->isAnonymousStructOrUnion()) {
754 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_anon_class)
755 << FieldName
756 << (cast<RecordDecl>((*Field)->getDeclContext())->isUnion()? 2 :
757 (int)SemaRef->getLangOptions().CPlusPlus);
758 SemaRef->Diag((*Field)->getLocation(), diag::note_field_designator_found);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000759 ++Index;
760 return true;
761 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000762
763 // All of the fields of a union are located at the same place in
764 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +0000765 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000766 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +0000767 StructuredList->setInitializedFieldInUnion(*Field);
768 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000769
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000770 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +0000771 D->setField(*Field);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000772
Douglas Gregor4c678342009-01-28 21:54:33 +0000773 // Make sure that our non-designated initializer list has space
774 // for a subobject corresponding to this field.
775 if (FieldIndex >= StructuredList->getNumInits())
776 StructuredList->resizeInits(SemaRef->Context, FieldIndex + 1);
777
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000778 // Recurse to check later designated subobjects.
Douglas Gregor4c678342009-01-28 21:54:33 +0000779 QualType FieldType = (*Field)->getType();
780 unsigned newStructuredIndex = FieldIndex;
781 if (CheckDesignatedInitializer(IList, DIE, ++D, FieldType, 0, 0, Index,
782 StructuredList, newStructuredIndex))
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000783 return true;
784
785 // Find the position of the next field to be initialized in this
786 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000787 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +0000788 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000789
790 // If this the first designator, our caller will continue checking
791 // the rest of this struct/class/union subobject.
792 if (IsFirstDesignator) {
793 if (NextField)
794 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +0000795 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000796 return false;
797 }
798
Douglas Gregor34e79462009-01-28 23:36:17 +0000799 if (!FinishSubobjectInit)
800 return false;
801
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000802 // Check the remaining fields within this class/struct/union subobject.
803 bool prevHadError = hadError;
Douglas Gregor4c678342009-01-28 21:54:33 +0000804 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
805 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000806 return hadError && !prevHadError;
807 }
808
809 // C99 6.7.8p6:
810 //
811 // If a designator has the form
812 //
813 // [ constant-expression ]
814 //
815 // then the current object (defined below) shall have array
816 // type and the expression shall be an integer constant
817 // expression. If the array is of unknown size, any
818 // nonnegative value is valid.
819 //
820 // Additionally, cope with the GNU extension that permits
821 // designators of the form
822 //
823 // [ constant-expression ... constant-expression ]
824 const ArrayType *AT = SemaRef->Context.getAsArrayType(CurrentObjectType);
825 if (!AT) {
826 SemaRef->Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
827 << CurrentObjectType;
828 ++Index;
829 return true;
830 }
831
832 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +0000833 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
834 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000835 IndexExpr = DIE->getArrayIndex(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +0000836
837 bool ConstExpr
838 = IndexExpr->isIntegerConstantExpr(DesignatedStartIndex, SemaRef->Context);
839 assert(ConstExpr && "Expression must be constant"); (void)ConstExpr;
840
841 DesignatedEndIndex = DesignatedStartIndex;
842 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000843 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +0000844
845 bool StartConstExpr
846 = DIE->getArrayRangeStart(*D)->isIntegerConstantExpr(DesignatedStartIndex,
847 SemaRef->Context);
848 assert(StartConstExpr && "Expression must be constant"); (void)StartConstExpr;
849
850 bool EndConstExpr
851 = DIE->getArrayRangeEnd(*D)->isIntegerConstantExpr(DesignatedEndIndex,
852 SemaRef->Context);
853 assert(EndConstExpr && "Expression must be constant"); (void)EndConstExpr;
854
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000855 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +0000856
857 if (DesignatedStartIndex.getZExtValue() != DesignatedEndIndex.getZExtValue())
858 SemaRef->Diag(D->getEllipsisLoc(),
859 diag::warn_gnu_array_range_designator_side_effects)
860 << SourceRange(D->getLBracketLoc(), D->getRBracketLoc());
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000861 }
862
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000863 if (isa<ConstantArrayType>(AT)) {
864 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +0000865 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
866 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
867 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
868 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
869 if (DesignatedEndIndex >= MaxElements) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000870 SemaRef->Diag(IndexExpr->getSourceRange().getBegin(),
871 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +0000872 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000873 << IndexExpr->getSourceRange();
874 ++Index;
875 return true;
876 }
Douglas Gregor34e79462009-01-28 23:36:17 +0000877 } else {
878 // Make sure the bit-widths and signedness match.
879 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
880 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
881 else if (DesignatedStartIndex.getBitWidth() < DesignatedEndIndex.getBitWidth())
882 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
883 DesignatedStartIndex.setIsUnsigned(true);
884 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000885 }
886
Douglas Gregor4c678342009-01-28 21:54:33 +0000887 // Make sure that our non-designated initializer list has space
888 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +0000889 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
890 StructuredList->resizeInits(SemaRef->Context,
891 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +0000892
Douglas Gregor34e79462009-01-28 23:36:17 +0000893 // Repeatedly perform subobject initializations in the range
894 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000895
Douglas Gregor34e79462009-01-28 23:36:17 +0000896 // Move to the next designator
897 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
898 unsigned OldIndex = Index;
899 ++D;
900 while (DesignatedStartIndex <= DesignatedEndIndex) {
901 // Recurse to check later designated subobjects.
902 QualType ElementType = AT->getElementType();
903 Index = OldIndex;
904 if (CheckDesignatedInitializer(IList, DIE, D, ElementType, 0, 0, Index,
905 StructuredList, ElementIndex,
906 (DesignatedStartIndex == DesignatedEndIndex)))
907 return true;
908
909 // Move to the next index in the array that we'll be initializing.
910 ++DesignatedStartIndex;
911 ElementIndex = DesignatedStartIndex.getZExtValue();
912 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000913
914 // If this the first designator, our caller will continue checking
915 // the rest of this array subobject.
916 if (IsFirstDesignator) {
917 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +0000918 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +0000919 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000920 return false;
921 }
Douglas Gregor34e79462009-01-28 23:36:17 +0000922
923 if (!FinishSubobjectInit)
924 return false;
925
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000926 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000927 bool prevHadError = hadError;
Douglas Gregor34e79462009-01-28 23:36:17 +0000928 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, true, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000929 StructuredList, ElementIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000930 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000931}
932
Douglas Gregor4c678342009-01-28 21:54:33 +0000933// Get the structured initializer list for a subobject of type
934// @p CurrentObjectType.
935InitListExpr *
936InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
937 QualType CurrentObjectType,
938 InitListExpr *StructuredList,
939 unsigned StructuredIndex,
940 SourceRange InitRange) {
941 Expr *ExistingInit = 0;
942 if (!StructuredList)
943 ExistingInit = SyntacticToSemantic[IList];
944 else if (StructuredIndex < StructuredList->getNumInits())
945 ExistingInit = StructuredList->getInit(StructuredIndex);
946
947 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
948 return Result;
949
950 if (ExistingInit) {
951 // We are creating an initializer list that initializes the
952 // subobjects of the current object, but there was already an
953 // initialization that completely initialized the current
954 // subobject, e.g., by a compound literal:
955 //
956 // struct X { int a, b; };
957 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
958 //
959 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
960 // designated initializer re-initializes the whole
961 // subobject [0], overwriting previous initializers.
962 SemaRef->Diag(InitRange.getBegin(), diag::warn_subobject_initializer_overrides)
963 << InitRange;
964 SemaRef->Diag(ExistingInit->getSourceRange().getBegin(),
965 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +0000966 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +0000967 << ExistingInit->getSourceRange();
968 }
969
970 InitListExpr *Result
971 = new (SemaRef->Context) InitListExpr(SourceLocation(), 0, 0,
972 SourceLocation());
973 Result->setType(CurrentObjectType);
974
975 // Link this new initializer list into the structured initializer
976 // lists.
977 if (StructuredList)
978 StructuredList->updateInit(StructuredIndex, Result);
979 else {
980 Result->setSyntacticForm(IList);
981 SyntacticToSemantic[IList] = Result;
982 }
983
984 return Result;
985}
986
987/// Update the initializer at index @p StructuredIndex within the
988/// structured initializer list to the value @p expr.
989void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
990 unsigned &StructuredIndex,
991 Expr *expr) {
992 // No structured initializer list to update
993 if (!StructuredList)
994 return;
995
996 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
997 // This initializer overwrites a previous initializer. Warn.
998 SemaRef->Diag(expr->getSourceRange().getBegin(),
999 diag::warn_initializer_overrides)
1000 << expr->getSourceRange();
1001 SemaRef->Diag(PrevInit->getSourceRange().getBegin(),
1002 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001003 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001004 << PrevInit->getSourceRange();
1005 }
1006
1007 ++StructuredIndex;
1008}
1009
Douglas Gregor05c13a32009-01-22 00:58:24 +00001010/// Check that the given Index expression is a valid array designator
1011/// value. This is essentailly just a wrapper around
1012/// Expr::isIntegerConstantExpr that also checks for negative values
1013/// and produces a reasonable diagnostic if there is a
1014/// failure. Returns true if there was an error, false otherwise. If
1015/// everything went okay, Value will receive the value of the constant
1016/// expression.
1017static bool
1018CheckArrayDesignatorExpr(Sema &Self, Expr *Index, llvm::APSInt &Value) {
1019 SourceLocation Loc = Index->getSourceRange().getBegin();
1020
1021 // Make sure this is an integer constant expression.
1022 if (!Index->isIntegerConstantExpr(Value, Self.Context, &Loc))
1023 return Self.Diag(Loc, diag::err_array_designator_nonconstant)
1024 << Index->getSourceRange();
1025
1026 // Make sure this constant expression is non-negative.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001027 llvm::APSInt Zero(llvm::APSInt::getNullValue(Value.getBitWidth()),
1028 Value.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001029 if (Value < Zero)
1030 return Self.Diag(Loc, diag::err_array_designator_negative)
1031 << Value.toString(10) << Index->getSourceRange();
1032
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001033 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001034 return false;
1035}
1036
1037Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1038 SourceLocation Loc,
1039 bool UsedColonSyntax,
1040 OwningExprResult Init) {
1041 typedef DesignatedInitExpr::Designator ASTDesignator;
1042
1043 bool Invalid = false;
1044 llvm::SmallVector<ASTDesignator, 32> Designators;
1045 llvm::SmallVector<Expr *, 32> InitExpressions;
1046
1047 // Build designators and check array designator expressions.
1048 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1049 const Designator &D = Desig.getDesignator(Idx);
1050 switch (D.getKind()) {
1051 case Designator::FieldDesignator:
1052 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1053 D.getFieldLoc()));
1054 break;
1055
1056 case Designator::ArrayDesignator: {
1057 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1058 llvm::APSInt IndexValue;
1059 if (CheckArrayDesignatorExpr(*this, Index, IndexValue))
1060 Invalid = true;
1061 else {
1062 Designators.push_back(ASTDesignator(InitExpressions.size(),
1063 D.getLBracketLoc(),
1064 D.getRBracketLoc()));
1065 InitExpressions.push_back(Index);
1066 }
1067 break;
1068 }
1069
1070 case Designator::ArrayRangeDesignator: {
1071 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1072 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1073 llvm::APSInt StartValue;
1074 llvm::APSInt EndValue;
1075 if (CheckArrayDesignatorExpr(*this, StartIndex, StartValue) ||
1076 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))
1077 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001078 else {
1079 // Make sure we're comparing values with the same bit width.
1080 if (StartValue.getBitWidth() > EndValue.getBitWidth())
1081 EndValue.extend(StartValue.getBitWidth());
1082 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1083 StartValue.extend(EndValue.getBitWidth());
1084
1085 if (EndValue < StartValue) {
1086 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1087 << StartValue.toString(10) << EndValue.toString(10)
1088 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1089 Invalid = true;
1090 } else {
1091 Designators.push_back(ASTDesignator(InitExpressions.size(),
1092 D.getLBracketLoc(),
1093 D.getEllipsisLoc(),
1094 D.getRBracketLoc()));
1095 InitExpressions.push_back(StartIndex);
1096 InitExpressions.push_back(EndIndex);
1097 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001098 }
1099 break;
1100 }
1101 }
1102 }
1103
1104 if (Invalid || Init.isInvalid())
1105 return ExprError();
1106
1107 // Clear out the expressions within the designation.
1108 Desig.ClearExprs(*this);
1109
1110 DesignatedInitExpr *DIE
1111 = DesignatedInitExpr::Create(Context, &Designators[0], Designators.size(),
1112 &InitExpressions[0], InitExpressions.size(),
1113 Loc, UsedColonSyntax,
1114 static_cast<Expr *>(Init.release()));
1115 return Owned(DIE);
1116}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001117
1118bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
1119 InitListChecker CheckInitList(this, InitList, DeclType);
1120 if (!CheckInitList.HadError())
1121 InitList = CheckInitList.getFullyStructuredList();
1122
1123 return CheckInitList.HadError();
1124}