blob: 77679ee36f981e297499dbb6903bb65bd9c828b9 [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 Gregorc34ee5e2009-01-29 00:45:39 +000020#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000021using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000022
Douglas Gregor9e80f722009-01-29 01:05:33 +000023/// @brief Semantic checking for initializer lists.
24///
25/// The InitListChecker class contains a set of routines that each
26/// handle the initialization of a certain kind of entity, e.g.,
27/// arrays, vectors, struct/union types, scalars, etc. The
28/// InitListChecker itself performs a recursive walk of the subobject
29/// structure of the type to be initialized, while stepping through
30/// the initializer list one element at a time. The IList and Index
31/// parameters to each of the Check* routines contain the active
32/// (syntactic) initializer list and the index into that initializer
33/// list that represents the current initializer. Each routine is
34/// responsible for moving that Index forward as it consumes elements.
35///
36/// Each Check* routine also has a StructuredList/StructuredIndex
37/// arguments, which contains the current the "structured" (semantic)
38/// initializer list and the index into that initializer list where we
39/// are copying initializers as we map them over to the semantic
40/// list. Once we have completed our recursive walk of the subobject
41/// structure, we will have constructed a full semantic initializer
42/// list.
43///
44/// C99 designators cause changes in the initializer list traversal,
45/// because they make the initialization "jump" into a specific
46/// subobject and then continue the initialization from that
47/// point. CheckDesignatedInitializer() recursively steps into the
48/// designated subobject and manages backing out the recursion to
49/// initialize the subobjects after the one designated.
Chris Lattner68355a52009-01-29 05:10:57 +000050namespace clang {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000051class InitListChecker {
52 Sema *SemaRef;
53 bool hadError;
54 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
55 InitListExpr *FullyStructuredList;
56
57 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +000058 unsigned &Index, InitListExpr *StructuredList,
59 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000060 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +000061 unsigned &Index, InitListExpr *StructuredList,
62 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000063 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
64 bool SubobjectIsDesignatorContext,
65 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +000066 InitListExpr *StructuredList,
67 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000068 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
69 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +000070 InitListExpr *StructuredList,
71 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000072 // FIXME: Does DeclType need to be a reference type?
73 void CheckScalarType(InitListExpr *IList, QualType &DeclType,
74 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +000075 InitListExpr *StructuredList,
76 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000077 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +000078 InitListExpr *StructuredList,
79 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000080 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
81 RecordDecl::field_iterator Field,
82 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +000083 InitListExpr *StructuredList,
84 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000085 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
86 llvm::APSInt elementIndex,
87 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +000088 InitListExpr *StructuredList,
89 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000090 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
91 DesignatedInitExpr::designators_iterator D,
92 QualType &CurrentObjectType,
93 RecordDecl::field_iterator *NextField,
94 llvm::APSInt *NextElementIndex,
95 unsigned &Index,
96 InitListExpr *StructuredList,
97 unsigned &StructuredIndex,
98 bool FinishSubobjectInit = true);
99 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
100 QualType CurrentObjectType,
101 InitListExpr *StructuredList,
102 unsigned StructuredIndex,
103 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000104 void UpdateStructuredListElement(InitListExpr *StructuredList,
105 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000106 Expr *expr);
107 int numArrayElements(QualType DeclType);
108 int numStructUnionElements(QualType DeclType);
109public:
110 InitListChecker(Sema *S, InitListExpr *IL, QualType &T);
111 bool HadError() { return hadError; }
112
113 // @brief Retrieves the fully-structured initializer list used for
114 // semantic analysis and code generation.
115 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
116};
Chris Lattner68355a52009-01-29 05:10:57 +0000117}
118
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000119
Douglas Gregor4c678342009-01-28 21:54:33 +0000120/// Recursively replaces NULL values within the given initializer list
121/// with expressions that perform value-initialization of the
122/// appropriate type.
123static void fillInValueInitializations(ASTContext &Context, InitListExpr *ILE) {
124 assert((ILE->getType() != Context.VoidTy) && "Should not have void type");
125 if (const RecordType *RType = ILE->getType()->getAsRecordType()) {
126 unsigned Init = 0, NumInits = ILE->getNumInits();
127 for (RecordDecl::field_iterator Field = RType->getDecl()->field_begin(),
128 FieldEnd = RType->getDecl()->field_end();
129 Field != FieldEnd; ++Field) {
130 if (Field->isUnnamedBitfield())
131 continue;
132
133 if (Init >= NumInits)
134 break;
135
136 // FIXME: Check for fields with reference type in C++?
137 if (!ILE->getInit(Init))
138 ILE->setInit(Init,
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000139 new (Context) ImplicitValueInitExpr(Field->getType()));
140 else if (InitListExpr *InnerILE
141 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor4c678342009-01-28 21:54:33 +0000142 fillInValueInitializations(Context, InnerILE);
143 ++Init;
144 }
145
146 return;
147 }
148
149 QualType ElementType;
150
151 if (const ArrayType *AType = Context.getAsArrayType(ILE->getType()))
152 ElementType = AType->getElementType();
153 else if (const VectorType *VType = ILE->getType()->getAsVectorType())
154 ElementType = VType->getElementType();
155 else
156 ElementType = ILE->getType();
157
158 for (unsigned Init = 0, NumInits = ILE->getNumInits(); Init != NumInits;
159 ++Init) {
160 if (!ILE->getInit(Init))
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000161 ILE->setInit(Init, new (Context) ImplicitValueInitExpr(ElementType));
Chris Lattner68355a52009-01-29 05:10:57 +0000162 else if (InitListExpr *InnerILE =dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor4c678342009-01-28 21:54:33 +0000163 fillInValueInitializations(Context, InnerILE);
164 }
165}
166
Chris Lattner68355a52009-01-29 05:10:57 +0000167
Steve Naroff0cca7492008-05-01 22:18:59 +0000168InitListChecker::InitListChecker(Sema *S, InitListExpr *IL, QualType &T) {
169 hadError = false;
170 SemaRef = S;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000171
Eli Friedmanb85f7072008-05-19 19:16:24 +0000172 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000173 unsigned newStructuredIndex = 0;
174 FullyStructuredList
175 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, SourceRange());
176 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000177
Douglas Gregor4c678342009-01-28 21:54:33 +0000178 if (!hadError) {
179 fillInValueInitializations(SemaRef->Context, FullyStructuredList);
180 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000181}
182
183int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000184 // FIXME: use a proper constant
185 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000186 if (const ConstantArrayType *CAT =
187 SemaRef->Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000188 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
189 }
190 return maxElements;
191}
192
193int InitListChecker::numStructUnionElements(QualType DeclType) {
194 RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000195 int InitializableMembers = 0;
196 for (RecordDecl::field_iterator Field = structDecl->field_begin(),
197 FieldEnd = structDecl->field_end();
198 Field != FieldEnd; ++Field) {
199 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
200 ++InitializableMembers;
201 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000202 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000203 return std::min(InitializableMembers, 1);
204 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000205}
206
207void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000208 QualType T, unsigned &Index,
209 InitListExpr *StructuredList,
210 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000211 int maxElements = 0;
212
213 if (T->isArrayType())
214 maxElements = numArrayElements(T);
215 else if (T->isStructureType() || T->isUnionType())
216 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000217 else if (T->isVectorType())
218 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000219 else
220 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000221
Douglas Gregor4c678342009-01-28 21:54:33 +0000222 // FIXME: Perhaps we should move this warning elsewhere?
Eli Friedman402256f2008-05-25 13:49:22 +0000223 if (maxElements == 0) {
224 SemaRef->Diag(ParentIList->getInit(Index)->getLocStart(),
225 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000226 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000227 hadError = true;
228 return;
229 }
230
Douglas Gregor4c678342009-01-28 21:54:33 +0000231 // Build a structured initializer list corresponding to this subobject.
232 InitListExpr *StructuredSubobjectInitList
233 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
234 StructuredIndex,
235 ParentIList->getInit(Index)->getSourceRange());
236 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000237
Douglas Gregor4c678342009-01-28 21:54:33 +0000238 // Check the element types and build the structural subobject.
239 CheckListElementTypes(ParentIList, T, false, Index,
240 StructuredSubobjectInitList,
241 StructuredSubobjectInitIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000242}
243
Steve Naroffa647caa2008-05-06 00:23:44 +0000244void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000245 unsigned &Index,
246 InitListExpr *StructuredList,
247 unsigned &StructuredIndex) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000248 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000249 SyntacticToSemantic[IList] = StructuredList;
250 StructuredList->setSyntacticForm(IList);
251 CheckListElementTypes(IList, T, true, Index, StructuredList,
252 StructuredIndex);
Steve Naroffa647caa2008-05-06 00:23:44 +0000253 IList->setType(T);
Douglas Gregor4c678342009-01-28 21:54:33 +0000254 StructuredList->setType(T);
Eli Friedman638e1442008-05-25 13:22:35 +0000255 if (hadError)
256 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000257
Eli Friedman638e1442008-05-25 13:22:35 +0000258 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000259 // We have leftover initializers
260 if (IList->getNumInits() > 0 &&
261 SemaRef->IsStringLiteralInit(IList->getInit(Index), T)) {
Eli Friedmanbb504d32008-05-19 20:12:18 +0000262 // Special-case
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000263 SemaRef->Diag(IList->getInit(Index)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000264 diag::err_excess_initializers_in_char_array_initializer)
265 << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000266 hadError = true;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000267 } else if (!T->isIncompleteType()) {
268 // Don't warn for incomplete types, since we'll get an error elsewhere
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000269 SemaRef->Diag(IList->getInit(Index)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000270 diag::warn_excess_initializers)
271 << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000272 }
273 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000274
Eli Friedman638e1442008-05-25 13:22:35 +0000275 if (T->isScalarType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000276 SemaRef->Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
277 << IList->getSourceRange();
Steve Naroff0cca7492008-05-01 22:18:59 +0000278}
279
Eli Friedmanb85f7072008-05-19 19:16:24 +0000280void InitListChecker::CheckListElementTypes(InitListExpr *IList,
281 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000282 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000283 unsigned &Index,
284 InitListExpr *StructuredList,
285 unsigned &StructuredIndex) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000286 if (DeclType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000287 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000288 } else if (DeclType->isVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000289 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000290 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000291 if (DeclType->isStructureType() || DeclType->isUnionType()) {
292 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
293 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000294 SubobjectIsDesignatorContext, Index,
295 StructuredList, StructuredIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000296 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000297 llvm::APSInt Zero(
298 SemaRef->Context.getTypeSize(SemaRef->Context.getSizeType()),
299 false);
Douglas Gregor4c678342009-01-28 21:54:33 +0000300 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
301 StructuredList, StructuredIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000302 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000303 else
Douglas Gregor4c678342009-01-28 21:54:33 +0000304 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000305 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
306 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000307 ++Index;
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000308 SemaRef->Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000309 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000310 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000311 } else {
312 // In C, all types are either scalars or aggregates, but
313 // additional handling is needed here for C++ (and possibly others?).
314 assert(0 && "Unsupported initializer type");
315 }
316}
317
Eli Friedmanb85f7072008-05-19 19:16:24 +0000318void InitListChecker::CheckSubElementType(InitListExpr *IList,
319 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000320 unsigned &Index,
321 InitListExpr *StructuredList,
322 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000323 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000324 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
325 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000326 unsigned newStructuredIndex = 0;
327 InitListExpr *newStructuredList
328 = getStructuredSubobjectInit(IList, Index, ElemType,
329 StructuredList, StructuredIndex,
330 SubInitList->getSourceRange());
331 CheckExplicitInitList(SubInitList, ElemType, newIndex,
332 newStructuredList, newStructuredIndex);
333 ++StructuredIndex;
334 ++Index;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000335 } else if (StringLiteral *lit =
336 SemaRef->IsStringLiteralInit(expr, ElemType)) {
337 SemaRef->CheckStringLiteralInit(lit, ElemType);
Douglas Gregor4c678342009-01-28 21:54:33 +0000338 UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
339 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000340 } else if (ElemType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000341 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000342 } else if (expr->getType()->getAsRecordType() &&
Eli Friedmanc92e5e42008-06-09 03:52:40 +0000343 SemaRef->Context.typesAreCompatible(
344 expr->getType().getUnqualifiedType(),
345 ElemType.getUnqualifiedType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000346 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
347 ++Index;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000348 // FIXME: Add checking
349 } else {
Douglas Gregor4c678342009-01-28 21:54:33 +0000350 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
351 StructuredIndex);
352 ++StructuredIndex;
353 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000354}
355
Douglas Gregor05c13a32009-01-22 00:58:24 +0000356void InitListChecker::CheckScalarType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000357 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000358 InitListExpr *StructuredList,
359 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000360 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000361 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000362 if (isa<InitListExpr>(expr)) {
Eli Friedmanbb504d32008-05-19 20:12:18 +0000363 SemaRef->Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000364 diag::err_many_braces_around_scalar_init)
365 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000366 hadError = true;
367 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000368 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000369 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000370 } else if (isa<DesignatedInitExpr>(expr)) {
371 SemaRef->Diag(expr->getSourceRange().getBegin(),
372 diag::err_designator_for_scalar_init)
373 << DeclType << expr->getSourceRange();
374 hadError = true;
375 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000376 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000377 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000378 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000379
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000380 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000381 if (SemaRef->CheckSingleInitializer(expr, DeclType, false))
Eli Friedmanbb504d32008-05-19 20:12:18 +0000382 hadError = true; // types weren't compatible.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000383 else if (savExpr != expr) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000384 // The type was promoted, update initializer list.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000385 IList->setInit(Index, expr);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000386 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000387 if (hadError)
388 ++StructuredIndex;
389 else
390 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000391 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000392 } else {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000393 SemaRef->Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
394 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000395 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000396 ++Index;
397 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000398 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000399 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000400}
401
402void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000403 unsigned &Index,
404 InitListExpr *StructuredList,
405 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000406 if (Index < IList->getNumInits()) {
407 const VectorType *VT = DeclType->getAsVectorType();
408 int maxElements = VT->getNumElements();
409 QualType elementType = VT->getElementType();
410
411 for (int i = 0; i < maxElements; ++i) {
412 // Don't attempt to go past the end of the init list
413 if (Index >= IList->getNumInits())
414 break;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000415 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000416 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000417 }
418 }
419}
420
421void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000422 llvm::APSInt elementIndex,
423 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000424 unsigned &Index,
425 InitListExpr *StructuredList,
426 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000427 // Check for the special-case of initializing an array with a string.
428 if (Index < IList->getNumInits()) {
429 if (StringLiteral *lit =
430 SemaRef->IsStringLiteralInit(IList->getInit(Index), DeclType)) {
431 SemaRef->CheckStringLiteralInit(lit, DeclType);
Douglas Gregor4c678342009-01-28 21:54:33 +0000432 // We place the string literal directly into the resulting
433 // initializer list. This is the only place where the structure
434 // of the structured initializer list doesn't match exactly,
435 // because doing so would involve allocating one character
436 // constant for each string.
437 UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
438 StructuredList->resizeInits(SemaRef->Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000439 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000440 return;
441 }
442 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000443 if (const VariableArrayType *VAT =
444 SemaRef->Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000445 // Check for VLAs; in standard C it would be possible to check this
446 // earlier, but I don't know where clang accepts VLAs (gcc accepts
447 // them in all sorts of strange places).
448 SemaRef->Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000449 diag::err_variable_object_no_init)
450 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000451 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000452 ++Index;
453 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000454 return;
455 }
456
Douglas Gregor05c13a32009-01-22 00:58:24 +0000457 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000458 llvm::APSInt maxElements(elementIndex.getBitWidth(),
459 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000460 bool maxElementsKnown = false;
461 if (const ConstantArrayType *CAT =
462 SemaRef->Context.getAsConstantArrayType(DeclType)) {
463 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000464 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000465 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000466 maxElementsKnown = true;
467 }
468
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000469 QualType elementType = SemaRef->Context.getAsArrayType(DeclType)
470 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000471 while (Index < IList->getNumInits()) {
472 Expr *Init = IList->getInit(Index);
473 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000474 // If we're not the subobject that matches up with the '{' for
475 // the designator, we shouldn't be handling the
476 // designator. Return immediately.
477 if (!SubobjectIsDesignatorContext)
478 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000479
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000480 // Handle this designated initializer. elementIndex will be
481 // updated to be the next array element we'll initialize.
482 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000483 DeclType, 0, &elementIndex, Index,
484 StructuredList, StructuredIndex)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000485 hadError = true;
486 continue;
487 }
488
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000489 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
490 maxElements.extend(elementIndex.getBitWidth());
491 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
492 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000493 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000494
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000495 // If the array is of incomplete type, keep track of the number of
496 // elements in the initializer.
497 if (!maxElementsKnown && elementIndex > maxElements)
498 maxElements = elementIndex;
499
Douglas Gregor05c13a32009-01-22 00:58:24 +0000500 continue;
501 }
502
503 // If we know the maximum number of elements, and we've already
504 // hit it, stop consuming elements in the initializer list.
505 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +0000506 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000507
508 // Check this element.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000509 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000510 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000511 ++elementIndex;
512
513 // If the array is of incomplete type, keep track of the number of
514 // elements in the initializer.
515 if (!maxElementsKnown && elementIndex > maxElements)
516 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +0000517 }
518 if (DeclType->isIncompleteArrayType()) {
519 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000520 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000521 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000522 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000523 // Sizing an array implicitly to zero is not allowed by ISO C,
524 // but is supported by GNU.
Steve Naroff0cca7492008-05-01 22:18:59 +0000525 SemaRef->Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000526 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +0000527 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000528
Douglas Gregor05c13a32009-01-22 00:58:24 +0000529 DeclType = SemaRef->Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000530 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +0000531 }
532}
533
534void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
535 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000536 RecordDecl::field_iterator Field,
537 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000538 unsigned &Index,
539 InitListExpr *StructuredList,
540 unsigned &StructuredIndex) {
Eli Friedmanb85f7072008-05-19 19:16:24 +0000541 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroff0cca7492008-05-01 22:18:59 +0000542
Eli Friedmanb85f7072008-05-19 19:16:24 +0000543 // If the record is invalid, some of it's members are invalid. To avoid
544 // confusion, we forgo checking the intializer for the entire record.
545 if (structDecl->isInvalidDecl()) {
546 hadError = true;
547 return;
548 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000549
550 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
551 // Value-initialize the first named member of the union.
552 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
553 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
554 Field != FieldEnd; ++Field) {
555 if (Field->getDeclName()) {
556 StructuredList->setInitializedFieldInUnion(*Field);
557 break;
558 }
559 }
560 return;
561 }
562
563
564
Douglas Gregor05c13a32009-01-22 00:58:24 +0000565 // If structDecl is a forward declaration, this loop won't do
566 // anything except look at designated initializers; That's okay,
567 // because an error should get printed out elsewhere. It might be
568 // worthwhile to skip over the rest of the initializer, though.
Douglas Gregor44b43212008-12-11 16:49:14 +0000569 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000570 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000571 while (Index < IList->getNumInits()) {
572 Expr *Init = IList->getInit(Index);
573
574 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000575 // If we're not the subobject that matches up with the '{' for
576 // the designator, we shouldn't be handling the
577 // designator. Return immediately.
578 if (!SubobjectIsDesignatorContext)
579 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000580
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000581 // Handle this designated initializer. Field will be updated to
582 // the next field that we'll be initializing.
583 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000584 DeclType, &Field, 0, Index,
585 StructuredList, StructuredIndex))
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000586 hadError = true;
587
Douglas Gregor0bb76892009-01-29 16:53:55 +0000588 // Abort early for unions: the designator handled the
589 // initialization of the appropriate field.
590 if (DeclType->isUnionType())
591 break;
592
Douglas Gregor05c13a32009-01-22 00:58:24 +0000593 continue;
594 }
595
596 if (Field == FieldEnd) {
597 // We've run out of fields. We're done.
598 break;
599 }
600
Douglas Gregor44b43212008-12-11 16:49:14 +0000601 // If we've hit the flexible array member at the end, we're done.
602 if (Field->getType()->isIncompleteArrayType())
603 break;
604
Douglas Gregor0bb76892009-01-29 16:53:55 +0000605 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000606 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +0000607 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000608 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +0000609 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000610
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000611 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000612 StructuredList, StructuredIndex);
Douglas Gregor0bb76892009-01-29 16:53:55 +0000613
614 if (DeclType->isUnionType()) {
615 // Initialize the first field within the union.
616 StructuredList->setInitializedFieldInUnion(*Field);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000617 break;
Douglas Gregor0bb76892009-01-29 16:53:55 +0000618 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000619
620 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +0000621 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000622
Eli Friedmanb85f7072008-05-19 19:16:24 +0000623 // FIXME: Implement flexible array initialization GCC extension (it's a
624 // really messy extension to implement, unfortunately...the necessary
625 // information isn't actually even here!)
Steve Naroff0cca7492008-05-01 22:18:59 +0000626}
Steve Naroff0cca7492008-05-01 22:18:59 +0000627
Douglas Gregor05c13a32009-01-22 00:58:24 +0000628/// @brief Check the well-formedness of a C99 designated initializer.
629///
630/// Determines whether the designated initializer @p DIE, which
631/// resides at the given @p Index within the initializer list @p
632/// IList, is well-formed for a current object of type @p DeclType
633/// (C99 6.7.8). The actual subobject that this designator refers to
634/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +0000635/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +0000636///
637/// @param IList The initializer list in which this designated
638/// initializer occurs.
639///
640/// @param DIE The designated initializer and its initialization
641/// expression.
642///
643/// @param DeclType The type of the "current object" (C99 6.7.8p17),
644/// into which the designation in @p DIE should refer.
645///
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000646/// @param NextField If non-NULL and the first designator in @p DIE is
647/// a field, this will be set to the field declaration corresponding
648/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000649///
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000650/// @param NextElementIndex If non-NULL and the first designator in @p
651/// DIE is an array designator or GNU array-range designator, this
652/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000653///
654/// @param Index Index into @p IList where the designated initializer
655/// @p DIE occurs.
656///
Douglas Gregor4c678342009-01-28 21:54:33 +0000657/// @param StructuredList The initializer list expression that
658/// describes all of the subobject initializers in the order they'll
659/// actually be initialized.
660///
Douglas Gregor05c13a32009-01-22 00:58:24 +0000661/// @returns true if there was an error, false otherwise.
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000662bool
663InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
664 DesignatedInitExpr *DIE,
665 DesignatedInitExpr::designators_iterator D,
666 QualType &CurrentObjectType,
667 RecordDecl::field_iterator *NextField,
668 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000669 unsigned &Index,
670 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +0000671 unsigned &StructuredIndex,
672 bool FinishSubobjectInit) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000673 if (D == DIE->designators_end()) {
674 // Check the actual initialization for the designated object type.
675 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000676
677 // Temporarily remove the designator expression from the
678 // initializer list that the child calls see, so that we don't try
679 // to re-process the designator.
680 unsigned OldIndex = Index;
681 IList->setInit(OldIndex, DIE->getInit());
682
683 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000684 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000685
686 // Restore the designated initializer expression in the syntactic
687 // form of the initializer list.
688 if (IList->getInit(OldIndex) != DIE->getInit())
689 DIE->setInit(IList->getInit(OldIndex));
690 IList->setInit(OldIndex, DIE);
691
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000692 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000693 }
694
Douglas Gregor4c678342009-01-28 21:54:33 +0000695 bool IsFirstDesignator = (D == DIE->designators_begin());
696 assert((IsFirstDesignator || StructuredList) &&
697 "Need a non-designated initializer list to start from");
698
699 // Determine the structural initializer list that corresponds to the
700 // current subobject.
701 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
702 : getStructuredSubobjectInit(IList, Index, CurrentObjectType, StructuredList,
703 StructuredIndex,
704 SourceRange(D->getStartLocation(),
705 DIE->getSourceRange().getEnd()));
706 assert(StructuredList && "Expected a structured initializer list");
707
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000708 if (D->isFieldDesignator()) {
709 // C99 6.7.8p7:
710 //
711 // If a designator has the form
712 //
713 // . identifier
714 //
715 // then the current object (defined below) shall have
716 // structure or union type and the identifier shall be the
717 // name of a member of that type.
718 const RecordType *RT = CurrentObjectType->getAsRecordType();
719 if (!RT) {
720 SourceLocation Loc = D->getDotLoc();
721 if (Loc.isInvalid())
722 Loc = D->getFieldLoc();
723 SemaRef->Diag(Loc, diag::err_field_designator_non_aggr)
724 << SemaRef->getLangOptions().CPlusPlus << CurrentObjectType;
725 ++Index;
726 return true;
727 }
728
Douglas Gregor4c678342009-01-28 21:54:33 +0000729 // Note: we perform a linear search of the fields here, despite
730 // the fact that we have a faster lookup method, because we always
731 // need to compute the field's index.
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000732 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +0000733 unsigned FieldIndex = 0;
734 RecordDecl::field_iterator Field = RT->getDecl()->field_begin(),
735 FieldEnd = RT->getDecl()->field_end();
736 for (; Field != FieldEnd; ++Field) {
737 if (Field->isUnnamedBitfield())
738 continue;
739
740 if (Field->getIdentifier() == FieldName)
741 break;
742
743 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000744 }
745
Douglas Gregor4c678342009-01-28 21:54:33 +0000746 if (Field == FieldEnd) {
747 // We did not find the field we're looking for. Produce a
748 // suitable diagnostic and return a failure.
749 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
750 if (Lookup.first == Lookup.second) {
751 // Name lookup didn't find anything.
752 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
753 << FieldName << CurrentObjectType;
754 } else {
755 // Name lookup found something, but it wasn't a field.
756 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
757 << FieldName;
758 SemaRef->Diag((*Lookup.first)->getLocation(),
759 diag::note_field_designator_found);
760 }
761
762 ++Index;
763 return true;
764 } else if (cast<RecordDecl>((*Field)->getDeclContext())
765 ->isAnonymousStructOrUnion()) {
766 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_anon_class)
767 << FieldName
768 << (cast<RecordDecl>((*Field)->getDeclContext())->isUnion()? 2 :
769 (int)SemaRef->getLangOptions().CPlusPlus);
770 SemaRef->Diag((*Field)->getLocation(), diag::note_field_designator_found);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000771 ++Index;
772 return true;
773 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000774
775 // All of the fields of a union are located at the same place in
776 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +0000777 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000778 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +0000779 StructuredList->setInitializedFieldInUnion(*Field);
780 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000781
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000782 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +0000783 D->setField(*Field);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000784
Douglas Gregor4c678342009-01-28 21:54:33 +0000785 // Make sure that our non-designated initializer list has space
786 // for a subobject corresponding to this field.
787 if (FieldIndex >= StructuredList->getNumInits())
788 StructuredList->resizeInits(SemaRef->Context, FieldIndex + 1);
789
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000790 // Recurse to check later designated subobjects.
Douglas Gregor4c678342009-01-28 21:54:33 +0000791 QualType FieldType = (*Field)->getType();
792 unsigned newStructuredIndex = FieldIndex;
793 if (CheckDesignatedInitializer(IList, DIE, ++D, FieldType, 0, 0, Index,
794 StructuredList, newStructuredIndex))
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000795 return true;
796
797 // Find the position of the next field to be initialized in this
798 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000799 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +0000800 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000801
802 // If this the first designator, our caller will continue checking
803 // the rest of this struct/class/union subobject.
804 if (IsFirstDesignator) {
805 if (NextField)
806 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +0000807 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000808 return false;
809 }
810
Douglas Gregor34e79462009-01-28 23:36:17 +0000811 if (!FinishSubobjectInit)
812 return false;
813
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000814 // Check the remaining fields within this class/struct/union subobject.
815 bool prevHadError = hadError;
Douglas Gregor4c678342009-01-28 21:54:33 +0000816 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
817 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000818 return hadError && !prevHadError;
819 }
820
821 // C99 6.7.8p6:
822 //
823 // If a designator has the form
824 //
825 // [ constant-expression ]
826 //
827 // then the current object (defined below) shall have array
828 // type and the expression shall be an integer constant
829 // expression. If the array is of unknown size, any
830 // nonnegative value is valid.
831 //
832 // Additionally, cope with the GNU extension that permits
833 // designators of the form
834 //
835 // [ constant-expression ... constant-expression ]
836 const ArrayType *AT = SemaRef->Context.getAsArrayType(CurrentObjectType);
837 if (!AT) {
838 SemaRef->Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
839 << CurrentObjectType;
840 ++Index;
841 return true;
842 }
843
844 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +0000845 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
846 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000847 IndexExpr = DIE->getArrayIndex(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +0000848
849 bool ConstExpr
850 = IndexExpr->isIntegerConstantExpr(DesignatedStartIndex, SemaRef->Context);
851 assert(ConstExpr && "Expression must be constant"); (void)ConstExpr;
852
853 DesignatedEndIndex = DesignatedStartIndex;
854 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000855 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +0000856
857 bool StartConstExpr
858 = DIE->getArrayRangeStart(*D)->isIntegerConstantExpr(DesignatedStartIndex,
859 SemaRef->Context);
860 assert(StartConstExpr && "Expression must be constant"); (void)StartConstExpr;
861
862 bool EndConstExpr
863 = DIE->getArrayRangeEnd(*D)->isIntegerConstantExpr(DesignatedEndIndex,
864 SemaRef->Context);
865 assert(EndConstExpr && "Expression must be constant"); (void)EndConstExpr;
866
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000867 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +0000868
869 if (DesignatedStartIndex.getZExtValue() != DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +0000870 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000871 }
872
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000873 if (isa<ConstantArrayType>(AT)) {
874 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +0000875 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
876 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
877 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
878 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
879 if (DesignatedEndIndex >= MaxElements) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000880 SemaRef->Diag(IndexExpr->getSourceRange().getBegin(),
881 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +0000882 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000883 << IndexExpr->getSourceRange();
884 ++Index;
885 return true;
886 }
Douglas Gregor34e79462009-01-28 23:36:17 +0000887 } else {
888 // Make sure the bit-widths and signedness match.
889 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
890 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
891 else if (DesignatedStartIndex.getBitWidth() < DesignatedEndIndex.getBitWidth())
892 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
893 DesignatedStartIndex.setIsUnsigned(true);
894 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000895 }
896
Douglas Gregor4c678342009-01-28 21:54:33 +0000897 // Make sure that our non-designated initializer list has space
898 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +0000899 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
900 StructuredList->resizeInits(SemaRef->Context,
901 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +0000902
Douglas Gregor34e79462009-01-28 23:36:17 +0000903 // Repeatedly perform subobject initializations in the range
904 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000905
Douglas Gregor34e79462009-01-28 23:36:17 +0000906 // Move to the next designator
907 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
908 unsigned OldIndex = Index;
909 ++D;
910 while (DesignatedStartIndex <= DesignatedEndIndex) {
911 // Recurse to check later designated subobjects.
912 QualType ElementType = AT->getElementType();
913 Index = OldIndex;
914 if (CheckDesignatedInitializer(IList, DIE, D, ElementType, 0, 0, Index,
915 StructuredList, ElementIndex,
916 (DesignatedStartIndex == DesignatedEndIndex)))
917 return true;
918
919 // Move to the next index in the array that we'll be initializing.
920 ++DesignatedStartIndex;
921 ElementIndex = DesignatedStartIndex.getZExtValue();
922 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000923
924 // If this the first designator, our caller will continue checking
925 // the rest of this array subobject.
926 if (IsFirstDesignator) {
927 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +0000928 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +0000929 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000930 return false;
931 }
Douglas Gregor34e79462009-01-28 23:36:17 +0000932
933 if (!FinishSubobjectInit)
934 return false;
935
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000936 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000937 bool prevHadError = hadError;
Douglas Gregor34e79462009-01-28 23:36:17 +0000938 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, true, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000939 StructuredList, ElementIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000940 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000941}
942
Douglas Gregor4c678342009-01-28 21:54:33 +0000943// Get the structured initializer list for a subobject of type
944// @p CurrentObjectType.
945InitListExpr *
946InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
947 QualType CurrentObjectType,
948 InitListExpr *StructuredList,
949 unsigned StructuredIndex,
950 SourceRange InitRange) {
951 Expr *ExistingInit = 0;
952 if (!StructuredList)
953 ExistingInit = SyntacticToSemantic[IList];
954 else if (StructuredIndex < StructuredList->getNumInits())
955 ExistingInit = StructuredList->getInit(StructuredIndex);
956
957 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
958 return Result;
959
960 if (ExistingInit) {
961 // We are creating an initializer list that initializes the
962 // subobjects of the current object, but there was already an
963 // initialization that completely initialized the current
964 // subobject, e.g., by a compound literal:
965 //
966 // struct X { int a, b; };
967 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
968 //
969 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
970 // designated initializer re-initializes the whole
971 // subobject [0], overwriting previous initializers.
972 SemaRef->Diag(InitRange.getBegin(), diag::warn_subobject_initializer_overrides)
973 << InitRange;
974 SemaRef->Diag(ExistingInit->getSourceRange().getBegin(),
975 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +0000976 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +0000977 << ExistingInit->getSourceRange();
978 }
979
980 InitListExpr *Result
981 = new (SemaRef->Context) InitListExpr(SourceLocation(), 0, 0,
982 SourceLocation());
983 Result->setType(CurrentObjectType);
984
985 // Link this new initializer list into the structured initializer
986 // lists.
987 if (StructuredList)
988 StructuredList->updateInit(StructuredIndex, Result);
989 else {
990 Result->setSyntacticForm(IList);
991 SyntacticToSemantic[IList] = Result;
992 }
993
994 return Result;
995}
996
997/// Update the initializer at index @p StructuredIndex within the
998/// structured initializer list to the value @p expr.
999void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1000 unsigned &StructuredIndex,
1001 Expr *expr) {
1002 // No structured initializer list to update
1003 if (!StructuredList)
1004 return;
1005
1006 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1007 // This initializer overwrites a previous initializer. Warn.
1008 SemaRef->Diag(expr->getSourceRange().getBegin(),
1009 diag::warn_initializer_overrides)
1010 << expr->getSourceRange();
1011 SemaRef->Diag(PrevInit->getSourceRange().getBegin(),
1012 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001013 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001014 << PrevInit->getSourceRange();
1015 }
1016
1017 ++StructuredIndex;
1018}
1019
Douglas Gregor05c13a32009-01-22 00:58:24 +00001020/// Check that the given Index expression is a valid array designator
1021/// value. This is essentailly just a wrapper around
1022/// Expr::isIntegerConstantExpr that also checks for negative values
1023/// and produces a reasonable diagnostic if there is a
1024/// failure. Returns true if there was an error, false otherwise. If
1025/// everything went okay, Value will receive the value of the constant
1026/// expression.
1027static bool
1028CheckArrayDesignatorExpr(Sema &Self, Expr *Index, llvm::APSInt &Value) {
1029 SourceLocation Loc = Index->getSourceRange().getBegin();
1030
1031 // Make sure this is an integer constant expression.
1032 if (!Index->isIntegerConstantExpr(Value, Self.Context, &Loc))
1033 return Self.Diag(Loc, diag::err_array_designator_nonconstant)
1034 << Index->getSourceRange();
1035
1036 // Make sure this constant expression is non-negative.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001037 llvm::APSInt Zero(llvm::APSInt::getNullValue(Value.getBitWidth()),
1038 Value.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001039 if (Value < Zero)
1040 return Self.Diag(Loc, diag::err_array_designator_negative)
1041 << Value.toString(10) << Index->getSourceRange();
1042
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001043 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001044 return false;
1045}
1046
1047Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1048 SourceLocation Loc,
1049 bool UsedColonSyntax,
1050 OwningExprResult Init) {
1051 typedef DesignatedInitExpr::Designator ASTDesignator;
1052
1053 bool Invalid = false;
1054 llvm::SmallVector<ASTDesignator, 32> Designators;
1055 llvm::SmallVector<Expr *, 32> InitExpressions;
1056
1057 // Build designators and check array designator expressions.
1058 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1059 const Designator &D = Desig.getDesignator(Idx);
1060 switch (D.getKind()) {
1061 case Designator::FieldDesignator:
1062 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1063 D.getFieldLoc()));
1064 break;
1065
1066 case Designator::ArrayDesignator: {
1067 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1068 llvm::APSInt IndexValue;
1069 if (CheckArrayDesignatorExpr(*this, Index, IndexValue))
1070 Invalid = true;
1071 else {
1072 Designators.push_back(ASTDesignator(InitExpressions.size(),
1073 D.getLBracketLoc(),
1074 D.getRBracketLoc()));
1075 InitExpressions.push_back(Index);
1076 }
1077 break;
1078 }
1079
1080 case Designator::ArrayRangeDesignator: {
1081 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1082 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1083 llvm::APSInt StartValue;
1084 llvm::APSInt EndValue;
1085 if (CheckArrayDesignatorExpr(*this, StartIndex, StartValue) ||
1086 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))
1087 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001088 else {
1089 // Make sure we're comparing values with the same bit width.
1090 if (StartValue.getBitWidth() > EndValue.getBitWidth())
1091 EndValue.extend(StartValue.getBitWidth());
1092 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1093 StartValue.extend(EndValue.getBitWidth());
1094
1095 if (EndValue < StartValue) {
1096 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1097 << StartValue.toString(10) << EndValue.toString(10)
1098 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1099 Invalid = true;
1100 } else {
1101 Designators.push_back(ASTDesignator(InitExpressions.size(),
1102 D.getLBracketLoc(),
1103 D.getEllipsisLoc(),
1104 D.getRBracketLoc()));
1105 InitExpressions.push_back(StartIndex);
1106 InitExpressions.push_back(EndIndex);
1107 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001108 }
1109 break;
1110 }
1111 }
1112 }
1113
1114 if (Invalid || Init.isInvalid())
1115 return ExprError();
1116
1117 // Clear out the expressions within the designation.
1118 Desig.ClearExprs(*this);
1119
1120 DesignatedInitExpr *DIE
1121 = DesignatedInitExpr::Create(Context, &Designators[0], Designators.size(),
1122 &InitExpressions[0], InitExpressions.size(),
1123 Loc, UsedColonSyntax,
1124 static_cast<Expr *>(Init.release()));
1125 return Owned(DIE);
1126}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001127
1128bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
1129 InitListChecker CheckInitList(this, InitList, DeclType);
1130 if (!CheckInitList.HadError())
1131 InitList = CheckInitList.getFullyStructuredList();
1132
1133 return CheckInitList.HadError();
1134}