blob: 8bc3496a19fba93b799ee031b89223ce9862b47e [file] [log] [blame]
Steve Naroffc4d4a482008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Douglas Gregoraaa20962009-01-29 01:05:33 +000010// This file implements semantic analysis for initializers. The entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
Steve Naroffc4d4a482008-05-01 22:18:59 +000013//
14//===----------------------------------------------------------------------===//
15
16#include "Sema.h"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +000017#include "clang/Parse/Designator.h"
Steve Naroffc4d4a482008-05-01 22:18:59 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
Douglas Gregor849afc32009-01-29 00:45:39 +000020#include <map>
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +000021using namespace clang;
Steve Naroffc4d4a482008-05-01 22:18:59 +000022
Douglas Gregoraaa20962009-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 Lattner1aa25a72009-01-29 05:10:57 +000050namespace clang {
Douglas Gregor849afc32009-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 Gregoraaa20962009-01-29 01:05:33 +000058 unsigned &Index, InitListExpr *StructuredList,
59 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000060 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregoraaa20962009-01-29 01:05:33 +000061 unsigned &Index, InitListExpr *StructuredList,
62 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000063 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
64 bool SubobjectIsDesignatorContext,
65 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +000066 InitListExpr *StructuredList,
67 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000068 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
69 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +000070 InitListExpr *StructuredList,
71 unsigned &StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +000072 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor849afc32009-01-29 00:45:39 +000073 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +000074 InitListExpr *StructuredList,
75 unsigned &StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +000076 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
77 unsigned &Index,
78 InitListExpr *StructuredList,
79 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000080 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +000081 InitListExpr *StructuredList,
82 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000083 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
84 RecordDecl::field_iterator Field,
85 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +000086 InitListExpr *StructuredList,
87 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000088 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
89 llvm::APSInt elementIndex,
90 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +000091 InitListExpr *StructuredList,
92 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000093 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
94 DesignatedInitExpr::designators_iterator D,
95 QualType &CurrentObjectType,
96 RecordDecl::field_iterator *NextField,
97 llvm::APSInt *NextElementIndex,
98 unsigned &Index,
99 InitListExpr *StructuredList,
100 unsigned &StructuredIndex,
101 bool FinishSubobjectInit = true);
102 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
103 QualType CurrentObjectType,
104 InitListExpr *StructuredList,
105 unsigned StructuredIndex,
106 SourceRange InitRange);
Douglas Gregoraaa20962009-01-29 01:05:33 +0000107 void UpdateStructuredListElement(InitListExpr *StructuredList,
108 unsigned &StructuredIndex,
Douglas Gregor849afc32009-01-29 00:45:39 +0000109 Expr *expr);
110 int numArrayElements(QualType DeclType);
111 int numStructUnionElements(QualType DeclType);
Douglas Gregord45210d2009-01-30 22:09:00 +0000112
113 void FillInValueInitializations(InitListExpr *ILE);
Douglas Gregor849afc32009-01-29 00:45:39 +0000114public:
115 InitListChecker(Sema *S, InitListExpr *IL, QualType &T);
116 bool HadError() { return hadError; }
117
118 // @brief Retrieves the fully-structured initializer list used for
119 // semantic analysis and code generation.
120 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
121};
Chris Lattner1aa25a72009-01-29 05:10:57 +0000122}
123
Douglas Gregorf603b472009-01-28 21:54:33 +0000124/// Recursively replaces NULL values within the given initializer list
125/// with expressions that perform value-initialization of the
126/// appropriate type.
Douglas Gregord45210d2009-01-30 22:09:00 +0000127void InitListChecker::FillInValueInitializations(InitListExpr *ILE) {
128 assert((ILE->getType() != SemaRef->Context.VoidTy) &&
129 "Should not have void type");
Douglas Gregor538a4c22009-02-02 17:43:21 +0000130 SourceLocation Loc = ILE->getSourceRange().getBegin();
131 if (ILE->getSyntacticForm())
132 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
133
Douglas Gregorf603b472009-01-28 21:54:33 +0000134 if (const RecordType *RType = ILE->getType()->getAsRecordType()) {
135 unsigned Init = 0, NumInits = ILE->getNumInits();
136 for (RecordDecl::field_iterator Field = RType->getDecl()->field_begin(),
137 FieldEnd = RType->getDecl()->field_end();
138 Field != FieldEnd; ++Field) {
139 if (Field->isUnnamedBitfield())
140 continue;
141
Douglas Gregor538a4c22009-02-02 17:43:21 +0000142 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000143 if (Field->getType()->isReferenceType()) {
144 // C++ [dcl.init.aggr]p9:
145 // If an incomplete or empty initializer-list leaves a
146 // member of reference type uninitialized, the program is
147 // ill-formed.
Douglas Gregor538a4c22009-02-02 17:43:21 +0000148 SemaRef->Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregord45210d2009-01-30 22:09:00 +0000149 << Field->getType()
150 << ILE->getSyntacticForm()->getSourceRange();
151 SemaRef->Diag(Field->getLocation(),
152 diag::note_uninit_reference_member);
153 hadError = true;
Douglas Gregor538a4c22009-02-02 17:43:21 +0000154 return;
155 } else if (SemaRef->CheckValueInitialization(Field->getType(), Loc)) {
156 hadError = true;
157 return;
Douglas Gregord45210d2009-01-30 22:09:00 +0000158 }
Douglas Gregor538a4c22009-02-02 17:43:21 +0000159
160 // FIXME: If value-initialization involves calling a
161 // constructor, should we make that call explicit in the
162 // representation (even when it means extending the
163 // initializer list)?
164 if (Init < NumInits && !hadError)
165 ILE->setInit(Init,
166 new (SemaRef->Context) ImplicitValueInitExpr(Field->getType()));
167 } else if (InitListExpr *InnerILE
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000168 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregord45210d2009-01-30 22:09:00 +0000169 FillInValueInitializations(InnerILE);
Douglas Gregorf603b472009-01-28 21:54:33 +0000170 ++Init;
Douglas Gregord45210d2009-01-30 22:09:00 +0000171
172 // Only look at the first initialization of a union.
173 if (RType->getDecl()->isUnion())
174 break;
Douglas Gregorf603b472009-01-28 21:54:33 +0000175 }
176
177 return;
178 }
179
180 QualType ElementType;
181
Douglas Gregor538a4c22009-02-02 17:43:21 +0000182 unsigned NumInits = ILE->getNumInits();
183 unsigned NumElements = NumInits;
184 if (const ArrayType *AType = SemaRef->Context.getAsArrayType(ILE->getType())) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000185 ElementType = AType->getElementType();
Douglas Gregor538a4c22009-02-02 17:43:21 +0000186 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
187 NumElements = CAType->getSize().getZExtValue();
188 } else if (const VectorType *VType = ILE->getType()->getAsVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000189 ElementType = VType->getElementType();
Douglas Gregor538a4c22009-02-02 17:43:21 +0000190 NumElements = VType->getNumElements();
191 } else
Douglas Gregorf603b472009-01-28 21:54:33 +0000192 ElementType = ILE->getType();
193
Douglas Gregor538a4c22009-02-02 17:43:21 +0000194 for (unsigned Init = 0; Init != NumElements; ++Init) {
195 if (Init >= NumInits || !ILE->getInit(Init)) {
196 if (SemaRef->CheckValueInitialization(ElementType, Loc)) {
197 hadError = true;
198 return;
199 }
200
201 // FIXME: If value-initialization involves calling a
202 // constructor, should we make that call explicit in the
203 // representation (even when it means extending the
204 // initializer list)?
205 if (Init < NumInits && !hadError)
206 ILE->setInit(Init,
207 new (SemaRef->Context) ImplicitValueInitExpr(ElementType));
208 }
Chris Lattner1aa25a72009-01-29 05:10:57 +0000209 else if (InitListExpr *InnerILE =dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregord45210d2009-01-30 22:09:00 +0000210 FillInValueInitializations(InnerILE);
Douglas Gregorf603b472009-01-28 21:54:33 +0000211 }
212}
213
Chris Lattner1aa25a72009-01-29 05:10:57 +0000214
Steve Naroffc4d4a482008-05-01 22:18:59 +0000215InitListChecker::InitListChecker(Sema *S, InitListExpr *IL, QualType &T) {
216 hadError = false;
217 SemaRef = S;
Eli Friedmand8535af2008-05-19 20:00:43 +0000218
Eli Friedman683cedf2008-05-19 19:16:24 +0000219 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000220 unsigned newStructuredIndex = 0;
221 FullyStructuredList
222 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, SourceRange());
223 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000224
Douglas Gregord45210d2009-01-30 22:09:00 +0000225 if (!hadError)
226 FillInValueInitializations(FullyStructuredList);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000227}
228
229int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman46f81662008-05-25 13:22:35 +0000230 // FIXME: use a proper constant
231 int maxElements = 0x7FFFFFFF;
Chris Lattnera1923f62008-08-04 07:31:14 +0000232 if (const ConstantArrayType *CAT =
233 SemaRef->Context.getAsConstantArrayType(DeclType)) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000234 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
235 }
236 return maxElements;
237}
238
239int InitListChecker::numStructUnionElements(QualType DeclType) {
240 RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl();
Douglas Gregorf603b472009-01-28 21:54:33 +0000241 int InitializableMembers = 0;
242 for (RecordDecl::field_iterator Field = structDecl->field_begin(),
243 FieldEnd = structDecl->field_end();
244 Field != FieldEnd; ++Field) {
245 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
246 ++InitializableMembers;
247 }
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000248 if (structDecl->isUnion())
Eli Friedman9f5250b2008-05-25 14:03:31 +0000249 return std::min(InitializableMembers, 1);
250 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000251}
252
253void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregorf603b472009-01-28 21:54:33 +0000254 QualType T, unsigned &Index,
255 InitListExpr *StructuredList,
256 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000257 int maxElements = 0;
258
259 if (T->isArrayType())
260 maxElements = numArrayElements(T);
261 else if (T->isStructureType() || T->isUnionType())
262 maxElements = numStructUnionElements(T);
Eli Friedman683cedf2008-05-19 19:16:24 +0000263 else if (T->isVectorType())
264 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000265 else
266 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman683cedf2008-05-19 19:16:24 +0000267
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000268 if (maxElements == 0) {
269 SemaRef->Diag(ParentIList->getInit(Index)->getLocStart(),
270 diag::err_implicit_empty_initializer);
Douglas Gregorf603b472009-01-28 21:54:33 +0000271 ++Index;
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000272 hadError = true;
273 return;
274 }
275
Douglas Gregorf603b472009-01-28 21:54:33 +0000276 // Build a structured initializer list corresponding to this subobject.
277 InitListExpr *StructuredSubobjectInitList
278 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
279 StructuredIndex,
280 ParentIList->getInit(Index)->getSourceRange());
281 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman683cedf2008-05-19 19:16:24 +0000282
Douglas Gregorf603b472009-01-28 21:54:33 +0000283 // Check the element types and build the structural subobject.
Douglas Gregor538a4c22009-02-02 17:43:21 +0000284 unsigned StartIndex = Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000285 CheckListElementTypes(ParentIList, T, false, Index,
286 StructuredSubobjectInitList,
287 StructuredSubobjectInitIndex);
Douglas Gregor538a4c22009-02-02 17:43:21 +0000288 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
289
290 // Update the structured sub-object initialize so that it's ending
291 // range corresponds with the end of the last initializer it used.
292 if (EndIndex < ParentIList->getNumInits()) {
293 SourceLocation EndLoc
294 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
295 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
296 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000297}
298
Steve Naroff56099522008-05-06 00:23:44 +0000299void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregorf603b472009-01-28 21:54:33 +0000300 unsigned &Index,
301 InitListExpr *StructuredList,
302 unsigned &StructuredIndex) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000303 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregorf603b472009-01-28 21:54:33 +0000304 SyntacticToSemantic[IList] = StructuredList;
305 StructuredList->setSyntacticForm(IList);
306 CheckListElementTypes(IList, T, true, Index, StructuredList,
307 StructuredIndex);
Steve Naroff56099522008-05-06 00:23:44 +0000308 IList->setType(T);
Douglas Gregorf603b472009-01-28 21:54:33 +0000309 StructuredList->setType(T);
Eli Friedman46f81662008-05-25 13:22:35 +0000310 if (hadError)
311 return;
Eli Friedmand8535af2008-05-19 20:00:43 +0000312
Eli Friedman46f81662008-05-25 13:22:35 +0000313 if (Index < IList->getNumInits()) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000314 // We have leftover initializers
315 if (IList->getNumInits() > 0 &&
316 SemaRef->IsStringLiteralInit(IList->getInit(Index), T)) {
Eli Friedman71de9eb2008-05-19 20:12:18 +0000317 // Special-case
Eli Friedmand8535af2008-05-19 20:00:43 +0000318 SemaRef->Diag(IList->getInit(Index)->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000319 diag::err_excess_initializers_in_char_array_initializer)
320 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000321 hadError = true;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000322 } else if (!T->isIncompleteType()) {
Douglas Gregor09f078c2009-01-30 22:26:29 +0000323 // Don't complain for incomplete types, since we'll get an error
324 // elsewhere
Eli Friedmand8535af2008-05-19 20:00:43 +0000325 SemaRef->Diag(IList->getInit(Index)->getLocStart(),
Douglas Gregor09f078c2009-01-30 22:26:29 +0000326 diag::err_excess_initializers)
Chris Lattner9d2cf082008-11-19 05:27:50 +0000327 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000328 }
329 }
Eli Friedman455f7622008-05-19 20:20:43 +0000330
Eli Friedman46f81662008-05-25 13:22:35 +0000331 if (T->isScalarType())
Chris Lattner9d2cf082008-11-19 05:27:50 +0000332 SemaRef->Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
333 << IList->getSourceRange();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000334}
335
Eli Friedman683cedf2008-05-19 19:16:24 +0000336void InitListChecker::CheckListElementTypes(InitListExpr *IList,
337 QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000338 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000339 unsigned &Index,
340 InitListExpr *StructuredList,
341 unsigned &StructuredIndex) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000342 if (DeclType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000343 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000344 } else if (DeclType->isVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000345 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregore7ef5002009-01-30 17:31:00 +0000346 } else if (DeclType->isAggregateType()) {
347 if (DeclType->isRecordType()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000348 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
349 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000350 SubobjectIsDesignatorContext, Index,
351 StructuredList, StructuredIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000352 } else if (DeclType->isArrayType()) {
Douglas Gregor5a203a62009-01-23 16:54:12 +0000353 llvm::APSInt Zero(
354 SemaRef->Context.getTypeSize(SemaRef->Context.getSizeType()),
355 false);
Douglas Gregorf603b472009-01-28 21:54:33 +0000356 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
357 StructuredList, StructuredIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000358 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000359 else
Douglas Gregorf603b472009-01-28 21:54:33 +0000360 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffff5b3a82008-08-10 16:05:48 +0000361 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
362 // This type is invalid, issue a diagnostic.
Douglas Gregorf603b472009-01-28 21:54:33 +0000363 ++Index;
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000364 SemaRef->Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000365 << DeclType;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000366 hadError = true;
Douglas Gregord45210d2009-01-30 22:09:00 +0000367 } else if (DeclType->isRecordType()) {
368 // C++ [dcl.init]p14:
369 // [...] If the class is an aggregate (8.5.1), and the initializer
370 // is a brace-enclosed list, see 8.5.1.
371 //
372 // Note: 8.5.1 is handled below; here, we diagnose the case where
373 // we have an initializer list and a destination type that is not
374 // an aggregate.
375 // FIXME: In C++0x, this is yet another form of initialization.
376 SemaRef->Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
377 << DeclType << IList->getSourceRange();
378 hadError = true;
379 } else if (DeclType->isReferenceType()) {
380 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000381 } else {
382 // In C, all types are either scalars or aggregates, but
383 // additional handling is needed here for C++ (and possibly others?).
384 assert(0 && "Unsupported initializer type");
385 }
386}
387
Eli Friedman683cedf2008-05-19 19:16:24 +0000388void InitListChecker::CheckSubElementType(InitListExpr *IList,
389 QualType ElemType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000390 unsigned &Index,
391 InitListExpr *StructuredList,
392 unsigned &StructuredIndex) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000393 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000394 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
395 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000396 unsigned newStructuredIndex = 0;
397 InitListExpr *newStructuredList
398 = getStructuredSubobjectInit(IList, Index, ElemType,
399 StructuredList, StructuredIndex,
400 SubInitList->getSourceRange());
401 CheckExplicitInitList(SubInitList, ElemType, newIndex,
402 newStructuredList, newStructuredIndex);
403 ++StructuredIndex;
404 ++Index;
Eli Friedman683cedf2008-05-19 19:16:24 +0000405 } else if (StringLiteral *lit =
406 SemaRef->IsStringLiteralInit(expr, ElemType)) {
407 SemaRef->CheckStringLiteralInit(lit, ElemType);
Douglas Gregorf603b472009-01-28 21:54:33 +0000408 UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
409 ++Index;
Eli Friedmand8535af2008-05-19 20:00:43 +0000410 } else if (ElemType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000411 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000412 } else if (ElemType->isReferenceType()) {
413 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedman683cedf2008-05-19 19:16:24 +0000414 } else {
Douglas Gregord45210d2009-01-30 22:09:00 +0000415 if (SemaRef->getLangOptions().CPlusPlus) {
416 // C++ [dcl.init.aggr]p12:
417 // All implicit type conversions (clause 4) are considered when
418 // initializing the aggregate member with an ini- tializer from
419 // an initializer-list. If the initializer can initialize a
420 // member, the member is initialized. [...]
421 ImplicitConversionSequence ICS
422 = SemaRef->TryCopyInitialization(expr, ElemType);
423 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
424 if (SemaRef->PerformImplicitConversion(expr, ElemType, ICS,
425 "initializing"))
426 hadError = true;
427 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
428 ++Index;
429 return;
430 }
431
432 // Fall through for subaggregate initialization
433 } else {
434 // C99 6.7.8p13:
435 //
436 // The initializer for a structure or union object that has
437 // automatic storage duration shall be either an initializer
438 // list as described below, or a single expression that has
439 // compatible structure or union type. In the latter case, the
440 // initial value of the object, including unnamed members, is
441 // that of the expression.
442 QualType ExprType = SemaRef->Context.getCanonicalType(expr->getType());
443 QualType ElemTypeCanon = SemaRef->Context.getCanonicalType(ElemType);
444 if (SemaRef->Context.typesAreCompatible(ExprType.getUnqualifiedType(),
445 ElemTypeCanon.getUnqualifiedType())) {
446 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
447 ++Index;
448 return;
449 }
450
451 // Fall through for subaggregate initialization
452 }
453
454 // C++ [dcl.init.aggr]p12:
455 //
456 // [...] Otherwise, if the member is itself a non-empty
457 // subaggregate, brace elision is assumed and the initializer is
458 // considered for the initialization of the first member of
459 // the subaggregate.
460 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
461 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
462 StructuredIndex);
463 ++StructuredIndex;
464 } else {
465 // We cannot initialize this element, so let
466 // PerformCopyInitialization produce the appropriate diagnostic.
467 SemaRef->PerformCopyInitialization(expr, ElemType, "initializing");
468 hadError = true;
469 ++Index;
470 ++StructuredIndex;
471 }
472 }
Eli Friedman683cedf2008-05-19 19:16:24 +0000473}
474
Douglas Gregord45210d2009-01-30 22:09:00 +0000475void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor36859eb2009-01-29 00:39:20 +0000476 unsigned &Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000477 InitListExpr *StructuredList,
478 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000479 if (Index < IList->getNumInits()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000480 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000481 if (isa<InitListExpr>(expr)) {
Eli Friedman71de9eb2008-05-19 20:12:18 +0000482 SemaRef->Diag(IList->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000483 diag::err_many_braces_around_scalar_init)
484 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000485 hadError = true;
486 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000487 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000488 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000489 } else if (isa<DesignatedInitExpr>(expr)) {
490 SemaRef->Diag(expr->getSourceRange().getBegin(),
491 diag::err_designator_for_scalar_init)
492 << DeclType << expr->getSourceRange();
493 hadError = true;
494 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000495 ++StructuredIndex;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000496 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000497 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000498
Eli Friedmand8535af2008-05-19 20:00:43 +0000499 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000500 if (SemaRef->CheckSingleInitializer(expr, DeclType, false))
Eli Friedman71de9eb2008-05-19 20:12:18 +0000501 hadError = true; // types weren't compatible.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000502 else if (savExpr != expr) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000503 // The type was promoted, update initializer list.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000504 IList->setInit(Index, expr);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000505 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000506 if (hadError)
507 ++StructuredIndex;
508 else
509 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000510 ++Index;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000511 } else {
Chris Lattner9d2cf082008-11-19 05:27:50 +0000512 SemaRef->Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
513 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000514 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000515 ++Index;
516 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000517 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000518 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000519}
520
Douglas Gregord45210d2009-01-30 22:09:00 +0000521void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
522 unsigned &Index,
523 InitListExpr *StructuredList,
524 unsigned &StructuredIndex) {
525 if (Index < IList->getNumInits()) {
526 Expr *expr = IList->getInit(Index);
527 if (isa<InitListExpr>(expr)) {
528 SemaRef->Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
529 << DeclType << IList->getSourceRange();
530 hadError = true;
531 ++Index;
532 ++StructuredIndex;
533 return;
534 }
535
536 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
537 if (SemaRef->CheckReferenceInit(expr, DeclType))
538 hadError = true;
539 else if (savExpr != expr) {
540 // The type was promoted, update initializer list.
541 IList->setInit(Index, expr);
542 }
543 if (hadError)
544 ++StructuredIndex;
545 else
546 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
547 ++Index;
548 } else {
549 // FIXME: It would be wonderful if we could point at the actual
550 // member. In general, it would be useful to pass location
551 // information down the stack, so that we know the location (or
552 // decl) of the "current object" being initialized.
553 SemaRef->Diag(IList->getLocStart(),
554 diag::err_init_reference_member_uninitialized)
555 << DeclType
556 << IList->getSourceRange();
557 hadError = true;
558 ++Index;
559 ++StructuredIndex;
560 return;
561 }
562}
563
Steve Naroffc4d4a482008-05-01 22:18:59 +0000564void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000565 unsigned &Index,
566 InitListExpr *StructuredList,
567 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000568 if (Index < IList->getNumInits()) {
569 const VectorType *VT = DeclType->getAsVectorType();
570 int maxElements = VT->getNumElements();
571 QualType elementType = VT->getElementType();
572
573 for (int i = 0; i < maxElements; ++i) {
574 // Don't attempt to go past the end of the init list
575 if (Index >= IList->getNumInits())
576 break;
Douglas Gregor36859eb2009-01-29 00:39:20 +0000577 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000578 StructuredList, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000579 }
580 }
581}
582
583void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000584 llvm::APSInt elementIndex,
585 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000586 unsigned &Index,
587 InitListExpr *StructuredList,
588 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000589 // Check for the special-case of initializing an array with a string.
590 if (Index < IList->getNumInits()) {
591 if (StringLiteral *lit =
592 SemaRef->IsStringLiteralInit(IList->getInit(Index), DeclType)) {
593 SemaRef->CheckStringLiteralInit(lit, DeclType);
Douglas Gregorf603b472009-01-28 21:54:33 +0000594 // We place the string literal directly into the resulting
595 // initializer list. This is the only place where the structure
596 // of the structured initializer list doesn't match exactly,
597 // because doing so would involve allocating one character
598 // constant for each string.
599 UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
600 StructuredList->resizeInits(SemaRef->Context, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000601 ++Index;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000602 return;
603 }
604 }
Chris Lattnera1923f62008-08-04 07:31:14 +0000605 if (const VariableArrayType *VAT =
606 SemaRef->Context.getAsVariableArrayType(DeclType)) {
Eli Friedman46f81662008-05-25 13:22:35 +0000607 // Check for VLAs; in standard C it would be possible to check this
608 // earlier, but I don't know where clang accepts VLAs (gcc accepts
609 // them in all sorts of strange places).
610 SemaRef->Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000611 diag::err_variable_object_no_init)
612 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman46f81662008-05-25 13:22:35 +0000613 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000614 ++Index;
615 ++StructuredIndex;
Eli Friedman46f81662008-05-25 13:22:35 +0000616 return;
617 }
618
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000619 // We might know the maximum number of elements in advance.
Douglas Gregorf603b472009-01-28 21:54:33 +0000620 llvm::APSInt maxElements(elementIndex.getBitWidth(),
621 elementIndex.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000622 bool maxElementsKnown = false;
623 if (const ConstantArrayType *CAT =
624 SemaRef->Context.getAsConstantArrayType(DeclType)) {
625 maxElements = CAT->getSize();
Douglas Gregor5a203a62009-01-23 16:54:12 +0000626 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000627 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000628 maxElementsKnown = true;
629 }
630
Chris Lattnera1923f62008-08-04 07:31:14 +0000631 QualType elementType = SemaRef->Context.getAsArrayType(DeclType)
632 ->getElementType();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000633 while (Index < IList->getNumInits()) {
634 Expr *Init = IList->getInit(Index);
635 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000636 // If we're not the subobject that matches up with the '{' for
637 // the designator, we shouldn't be handling the
638 // designator. Return immediately.
639 if (!SubobjectIsDesignatorContext)
640 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000641
Douglas Gregor710f6d42009-01-22 23:26:18 +0000642 // Handle this designated initializer. elementIndex will be
643 // updated to be the next array element we'll initialize.
644 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000645 DeclType, 0, &elementIndex, Index,
646 StructuredList, StructuredIndex)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000647 hadError = true;
648 continue;
649 }
650
Douglas Gregor5a203a62009-01-23 16:54:12 +0000651 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
652 maxElements.extend(elementIndex.getBitWidth());
653 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
654 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000655 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor5a203a62009-01-23 16:54:12 +0000656
Douglas Gregor710f6d42009-01-22 23:26:18 +0000657 // If the array is of incomplete type, keep track of the number of
658 // elements in the initializer.
659 if (!maxElementsKnown && elementIndex > maxElements)
660 maxElements = elementIndex;
661
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000662 continue;
663 }
664
665 // If we know the maximum number of elements, and we've already
666 // hit it, stop consuming elements in the initializer list.
667 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000668 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000669
670 // Check this element.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000671 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000672 StructuredList, StructuredIndex);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000673 ++elementIndex;
674
675 // If the array is of incomplete type, keep track of the number of
676 // elements in the initializer.
677 if (!maxElementsKnown && elementIndex > maxElements)
678 maxElements = elementIndex;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000679 }
680 if (DeclType->isIncompleteArrayType()) {
681 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000682 // be calculated here.
Douglas Gregor69722702009-01-23 18:58:42 +0000683 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000684 if (maxElements == Zero) {
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000685 // Sizing an array implicitly to zero is not allowed by ISO C,
686 // but is supported by GNU.
Steve Naroffc4d4a482008-05-01 22:18:59 +0000687 SemaRef->Diag(IList->getLocStart(),
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000688 diag::ext_typecheck_zero_array_size);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000689 }
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000690
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000691 DeclType = SemaRef->Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000692 ArrayType::Normal, 0);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000693 }
694}
695
696void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
697 QualType DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000698 RecordDecl::field_iterator Field,
699 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000700 unsigned &Index,
701 InitListExpr *StructuredList,
702 unsigned &StructuredIndex) {
Eli Friedman683cedf2008-05-19 19:16:24 +0000703 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000704
Eli Friedman683cedf2008-05-19 19:16:24 +0000705 // If the record is invalid, some of it's members are invalid. To avoid
706 // confusion, we forgo checking the intializer for the entire record.
707 if (structDecl->isInvalidDecl()) {
708 hadError = true;
709 return;
710 }
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000711
712 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
713 // Value-initialize the first named member of the union.
714 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
715 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
716 Field != FieldEnd; ++Field) {
717 if (Field->getDeclName()) {
718 StructuredList->setInitializedFieldInUnion(*Field);
719 break;
720 }
721 }
722 return;
723 }
724
725
726
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000727 // If structDecl is a forward declaration, this loop won't do
728 // anything except look at designated initializers; That's okay,
729 // because an error should get printed out elsewhere. It might be
730 // worthwhile to skip over the rest of the initializer, though.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000731 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor710f6d42009-01-22 23:26:18 +0000732 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000733 while (Index < IList->getNumInits()) {
734 Expr *Init = IList->getInit(Index);
735
736 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000737 // If we're not the subobject that matches up with the '{' for
738 // the designator, we shouldn't be handling the
739 // designator. Return immediately.
740 if (!SubobjectIsDesignatorContext)
741 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000742
Douglas Gregor710f6d42009-01-22 23:26:18 +0000743 // Handle this designated initializer. Field will be updated to
744 // the next field that we'll be initializing.
745 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000746 DeclType, &Field, 0, Index,
747 StructuredList, StructuredIndex))
Douglas Gregor710f6d42009-01-22 23:26:18 +0000748 hadError = true;
749
Douglas Gregor82462762009-01-29 16:53:55 +0000750 // Abort early for unions: the designator handled the
751 // initialization of the appropriate field.
752 if (DeclType->isUnionType())
753 break;
754
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000755 continue;
756 }
757
758 if (Field == FieldEnd) {
759 // We've run out of fields. We're done.
760 break;
761 }
762
Douglas Gregor8acb7272008-12-11 16:49:14 +0000763 // If we've hit the flexible array member at the end, we're done.
764 if (Field->getType()->isIncompleteArrayType())
765 break;
766
Douglas Gregor82462762009-01-29 16:53:55 +0000767 if (Field->isUnnamedBitfield()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000768 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000769 ++Field;
Eli Friedman683cedf2008-05-19 19:16:24 +0000770 continue;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000771 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000772
Douglas Gregor36859eb2009-01-29 00:39:20 +0000773 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000774 StructuredList, StructuredIndex);
Douglas Gregor82462762009-01-29 16:53:55 +0000775
776 if (DeclType->isUnionType()) {
777 // Initialize the first field within the union.
778 StructuredList->setInitializedFieldInUnion(*Field);
Eli Friedman683cedf2008-05-19 19:16:24 +0000779 break;
Douglas Gregor82462762009-01-29 16:53:55 +0000780 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000781
782 ++Field;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000783 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000784
Eli Friedman683cedf2008-05-19 19:16:24 +0000785 // FIXME: Implement flexible array initialization GCC extension (it's a
786 // really messy extension to implement, unfortunately...the necessary
787 // information isn't actually even here!)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000788}
Steve Naroffc4d4a482008-05-01 22:18:59 +0000789
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000790/// @brief Check the well-formedness of a C99 designated initializer.
791///
792/// Determines whether the designated initializer @p DIE, which
793/// resides at the given @p Index within the initializer list @p
794/// IList, is well-formed for a current object of type @p DeclType
795/// (C99 6.7.8). The actual subobject that this designator refers to
796/// within the current subobject is returned in either
Douglas Gregorf603b472009-01-28 21:54:33 +0000797/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000798///
799/// @param IList The initializer list in which this designated
800/// initializer occurs.
801///
802/// @param DIE The designated initializer and its initialization
803/// expression.
804///
805/// @param DeclType The type of the "current object" (C99 6.7.8p17),
806/// into which the designation in @p DIE should refer.
807///
Douglas Gregor710f6d42009-01-22 23:26:18 +0000808/// @param NextField If non-NULL and the first designator in @p DIE is
809/// a field, this will be set to the field declaration corresponding
810/// to the field named by the designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000811///
Douglas Gregor710f6d42009-01-22 23:26:18 +0000812/// @param NextElementIndex If non-NULL and the first designator in @p
813/// DIE is an array designator or GNU array-range designator, this
814/// will be set to the last index initialized by this designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000815///
816/// @param Index Index into @p IList where the designated initializer
817/// @p DIE occurs.
818///
Douglas Gregorf603b472009-01-28 21:54:33 +0000819/// @param StructuredList The initializer list expression that
820/// describes all of the subobject initializers in the order they'll
821/// actually be initialized.
822///
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000823/// @returns true if there was an error, false otherwise.
Douglas Gregor710f6d42009-01-22 23:26:18 +0000824bool
825InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
826 DesignatedInitExpr *DIE,
827 DesignatedInitExpr::designators_iterator D,
828 QualType &CurrentObjectType,
829 RecordDecl::field_iterator *NextField,
830 llvm::APSInt *NextElementIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +0000831 unsigned &Index,
832 InitListExpr *StructuredList,
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000833 unsigned &StructuredIndex,
834 bool FinishSubobjectInit) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000835 if (D == DIE->designators_end()) {
836 // Check the actual initialization for the designated object type.
837 bool prevHadError = hadError;
Douglas Gregor36859eb2009-01-29 00:39:20 +0000838
839 // Temporarily remove the designator expression from the
840 // initializer list that the child calls see, so that we don't try
841 // to re-process the designator.
842 unsigned OldIndex = Index;
843 IList->setInit(OldIndex, DIE->getInit());
844
845 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000846 StructuredList, StructuredIndex);
Douglas Gregor36859eb2009-01-29 00:39:20 +0000847
848 // Restore the designated initializer expression in the syntactic
849 // form of the initializer list.
850 if (IList->getInit(OldIndex) != DIE->getInit())
851 DIE->setInit(IList->getInit(OldIndex));
852 IList->setInit(OldIndex, DIE);
853
Douglas Gregor710f6d42009-01-22 23:26:18 +0000854 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000855 }
856
Douglas Gregorf603b472009-01-28 21:54:33 +0000857 bool IsFirstDesignator = (D == DIE->designators_begin());
858 assert((IsFirstDesignator || StructuredList) &&
859 "Need a non-designated initializer list to start from");
860
861 // Determine the structural initializer list that corresponds to the
862 // current subobject.
863 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
864 : getStructuredSubobjectInit(IList, Index, CurrentObjectType, StructuredList,
865 StructuredIndex,
866 SourceRange(D->getStartLocation(),
867 DIE->getSourceRange().getEnd()));
868 assert(StructuredList && "Expected a structured initializer list");
869
Douglas Gregor710f6d42009-01-22 23:26:18 +0000870 if (D->isFieldDesignator()) {
871 // C99 6.7.8p7:
872 //
873 // If a designator has the form
874 //
875 // . identifier
876 //
877 // then the current object (defined below) shall have
878 // structure or union type and the identifier shall be the
879 // name of a member of that type.
880 const RecordType *RT = CurrentObjectType->getAsRecordType();
881 if (!RT) {
882 SourceLocation Loc = D->getDotLoc();
883 if (Loc.isInvalid())
884 Loc = D->getFieldLoc();
885 SemaRef->Diag(Loc, diag::err_field_designator_non_aggr)
886 << SemaRef->getLangOptions().CPlusPlus << CurrentObjectType;
887 ++Index;
888 return true;
889 }
890
Douglas Gregorf603b472009-01-28 21:54:33 +0000891 // Note: we perform a linear search of the fields here, despite
892 // the fact that we have a faster lookup method, because we always
893 // need to compute the field's index.
Douglas Gregor710f6d42009-01-22 23:26:18 +0000894 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregorf603b472009-01-28 21:54:33 +0000895 unsigned FieldIndex = 0;
896 RecordDecl::field_iterator Field = RT->getDecl()->field_begin(),
897 FieldEnd = RT->getDecl()->field_end();
898 for (; Field != FieldEnd; ++Field) {
899 if (Field->isUnnamedBitfield())
900 continue;
901
902 if (Field->getIdentifier() == FieldName)
903 break;
904
905 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000906 }
907
Douglas Gregorf603b472009-01-28 21:54:33 +0000908 if (Field == FieldEnd) {
909 // We did not find the field we're looking for. Produce a
910 // suitable diagnostic and return a failure.
911 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
912 if (Lookup.first == Lookup.second) {
913 // Name lookup didn't find anything.
914 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
915 << FieldName << CurrentObjectType;
916 } else {
917 // Name lookup found something, but it wasn't a field.
918 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
919 << FieldName;
920 SemaRef->Diag((*Lookup.first)->getLocation(),
921 diag::note_field_designator_found);
922 }
923
924 ++Index;
925 return true;
926 } else if (cast<RecordDecl>((*Field)->getDeclContext())
927 ->isAnonymousStructOrUnion()) {
928 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_anon_class)
929 << FieldName
930 << (cast<RecordDecl>((*Field)->getDeclContext())->isUnion()? 2 :
931 (int)SemaRef->getLangOptions().CPlusPlus);
932 SemaRef->Diag((*Field)->getLocation(), diag::note_field_designator_found);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000933 ++Index;
934 return true;
935 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000936
937 // All of the fields of a union are located at the same place in
938 // the initializer list.
Douglas Gregor82462762009-01-29 16:53:55 +0000939 if (RT->getDecl()->isUnion()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000940 FieldIndex = 0;
Douglas Gregor82462762009-01-29 16:53:55 +0000941 StructuredList->setInitializedFieldInUnion(*Field);
942 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000943
Douglas Gregor710f6d42009-01-22 23:26:18 +0000944 // Update the designator with the field declaration.
Douglas Gregorf603b472009-01-28 21:54:33 +0000945 D->setField(*Field);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000946
Douglas Gregorf603b472009-01-28 21:54:33 +0000947 // Make sure that our non-designated initializer list has space
948 // for a subobject corresponding to this field.
949 if (FieldIndex >= StructuredList->getNumInits())
950 StructuredList->resizeInits(SemaRef->Context, FieldIndex + 1);
951
Douglas Gregor710f6d42009-01-22 23:26:18 +0000952 // Recurse to check later designated subobjects.
Douglas Gregorf603b472009-01-28 21:54:33 +0000953 QualType FieldType = (*Field)->getType();
954 unsigned newStructuredIndex = FieldIndex;
955 if (CheckDesignatedInitializer(IList, DIE, ++D, FieldType, 0, 0, Index,
956 StructuredList, newStructuredIndex))
Douglas Gregor710f6d42009-01-22 23:26:18 +0000957 return true;
958
959 // Find the position of the next field to be initialized in this
960 // subobject.
Douglas Gregor710f6d42009-01-22 23:26:18 +0000961 ++Field;
Douglas Gregorf603b472009-01-28 21:54:33 +0000962 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000963
964 // If this the first designator, our caller will continue checking
965 // the rest of this struct/class/union subobject.
966 if (IsFirstDesignator) {
967 if (NextField)
968 *NextField = Field;
Douglas Gregorf603b472009-01-28 21:54:33 +0000969 StructuredIndex = FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000970 return false;
971 }
972
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000973 if (!FinishSubobjectInit)
974 return false;
975
Douglas Gregor710f6d42009-01-22 23:26:18 +0000976 // Check the remaining fields within this class/struct/union subobject.
977 bool prevHadError = hadError;
Douglas Gregorf603b472009-01-28 21:54:33 +0000978 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
979 StructuredList, FieldIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000980 return hadError && !prevHadError;
981 }
982
983 // C99 6.7.8p6:
984 //
985 // If a designator has the form
986 //
987 // [ constant-expression ]
988 //
989 // then the current object (defined below) shall have array
990 // type and the expression shall be an integer constant
991 // expression. If the array is of unknown size, any
992 // nonnegative value is valid.
993 //
994 // Additionally, cope with the GNU extension that permits
995 // designators of the form
996 //
997 // [ constant-expression ... constant-expression ]
998 const ArrayType *AT = SemaRef->Context.getAsArrayType(CurrentObjectType);
999 if (!AT) {
1000 SemaRef->Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1001 << CurrentObjectType;
1002 ++Index;
1003 return true;
1004 }
1005
1006 Expr *IndexExpr = 0;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001007 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1008 if (D->isArrayDesignator()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001009 IndexExpr = DIE->getArrayIndex(*D);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001010
1011 bool ConstExpr
1012 = IndexExpr->isIntegerConstantExpr(DesignatedStartIndex, SemaRef->Context);
1013 assert(ConstExpr && "Expression must be constant"); (void)ConstExpr;
1014
1015 DesignatedEndIndex = DesignatedStartIndex;
1016 } else {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001017 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001018
1019 bool StartConstExpr
1020 = DIE->getArrayRangeStart(*D)->isIntegerConstantExpr(DesignatedStartIndex,
1021 SemaRef->Context);
1022 assert(StartConstExpr && "Expression must be constant"); (void)StartConstExpr;
1023
1024 bool EndConstExpr
1025 = DIE->getArrayRangeEnd(*D)->isIntegerConstantExpr(DesignatedEndIndex,
1026 SemaRef->Context);
1027 assert(EndConstExpr && "Expression must be constant"); (void)EndConstExpr;
1028
Douglas Gregor710f6d42009-01-22 23:26:18 +00001029 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001030
1031 if (DesignatedStartIndex.getZExtValue() != DesignatedEndIndex.getZExtValue())
Douglas Gregor9fddded2009-01-29 19:42:23 +00001032 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001033 }
1034
Douglas Gregor710f6d42009-01-22 23:26:18 +00001035 if (isa<ConstantArrayType>(AT)) {
1036 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001037 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1038 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1039 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1040 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1041 if (DesignatedEndIndex >= MaxElements) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001042 SemaRef->Diag(IndexExpr->getSourceRange().getBegin(),
1043 diag::err_array_designator_too_large)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001044 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor710f6d42009-01-22 23:26:18 +00001045 << IndexExpr->getSourceRange();
1046 ++Index;
1047 return true;
1048 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001049 } else {
1050 // Make sure the bit-widths and signedness match.
1051 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1052 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
1053 else if (DesignatedStartIndex.getBitWidth() < DesignatedEndIndex.getBitWidth())
1054 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1055 DesignatedStartIndex.setIsUnsigned(true);
1056 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001057 }
1058
Douglas Gregorf603b472009-01-28 21:54:33 +00001059 // Make sure that our non-designated initializer list has space
1060 // for a subobject corresponding to this array element.
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001061 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
1062 StructuredList->resizeInits(SemaRef->Context,
1063 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +00001064
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001065 // Repeatedly perform subobject initializations in the range
1066 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor710f6d42009-01-22 23:26:18 +00001067
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001068 // Move to the next designator
1069 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1070 unsigned OldIndex = Index;
1071 ++D;
1072 while (DesignatedStartIndex <= DesignatedEndIndex) {
1073 // Recurse to check later designated subobjects.
1074 QualType ElementType = AT->getElementType();
1075 Index = OldIndex;
1076 if (CheckDesignatedInitializer(IList, DIE, D, ElementType, 0, 0, Index,
1077 StructuredList, ElementIndex,
1078 (DesignatedStartIndex == DesignatedEndIndex)))
1079 return true;
1080
1081 // Move to the next index in the array that we'll be initializing.
1082 ++DesignatedStartIndex;
1083 ElementIndex = DesignatedStartIndex.getZExtValue();
1084 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001085
1086 // If this the first designator, our caller will continue checking
1087 // the rest of this array subobject.
1088 if (IsFirstDesignator) {
1089 if (NextElementIndex)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001090 *NextElementIndex = DesignatedStartIndex;
Douglas Gregorf603b472009-01-28 21:54:33 +00001091 StructuredIndex = ElementIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001092 return false;
1093 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001094
1095 if (!FinishSubobjectInit)
1096 return false;
1097
Douglas Gregor710f6d42009-01-22 23:26:18 +00001098 // Check the remaining elements within this array subobject.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001099 bool prevHadError = hadError;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001100 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, true, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001101 StructuredList, ElementIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001102 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001103}
1104
Douglas Gregorf603b472009-01-28 21:54:33 +00001105// Get the structured initializer list for a subobject of type
1106// @p CurrentObjectType.
1107InitListExpr *
1108InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1109 QualType CurrentObjectType,
1110 InitListExpr *StructuredList,
1111 unsigned StructuredIndex,
1112 SourceRange InitRange) {
1113 Expr *ExistingInit = 0;
1114 if (!StructuredList)
1115 ExistingInit = SyntacticToSemantic[IList];
1116 else if (StructuredIndex < StructuredList->getNumInits())
1117 ExistingInit = StructuredList->getInit(StructuredIndex);
1118
1119 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1120 return Result;
1121
1122 if (ExistingInit) {
1123 // We are creating an initializer list that initializes the
1124 // subobjects of the current object, but there was already an
1125 // initialization that completely initialized the current
1126 // subobject, e.g., by a compound literal:
1127 //
1128 // struct X { int a, b; };
1129 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1130 //
1131 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1132 // designated initializer re-initializes the whole
1133 // subobject [0], overwriting previous initializers.
1134 SemaRef->Diag(InitRange.getBegin(), diag::warn_subobject_initializer_overrides)
1135 << InitRange;
1136 SemaRef->Diag(ExistingInit->getSourceRange().getBegin(),
1137 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001138 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001139 << ExistingInit->getSourceRange();
1140 }
1141
Douglas Gregor538a4c22009-02-02 17:43:21 +00001142 SourceLocation StartLoc;
1143 if (Index < IList->getNumInits())
1144 StartLoc = IList->getInit(Index)->getSourceRange().getBegin();
Douglas Gregorf603b472009-01-28 21:54:33 +00001145 InitListExpr *Result
Douglas Gregor538a4c22009-02-02 17:43:21 +00001146 = new (SemaRef->Context) InitListExpr(StartLoc, 0, 0,
1147 IList->getSourceRange().getEnd());
Douglas Gregorf603b472009-01-28 21:54:33 +00001148 Result->setType(CurrentObjectType);
1149
1150 // Link this new initializer list into the structured initializer
1151 // lists.
1152 if (StructuredList)
1153 StructuredList->updateInit(StructuredIndex, Result);
1154 else {
1155 Result->setSyntacticForm(IList);
1156 SyntacticToSemantic[IList] = Result;
1157 }
1158
1159 return Result;
1160}
1161
1162/// Update the initializer at index @p StructuredIndex within the
1163/// structured initializer list to the value @p expr.
1164void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1165 unsigned &StructuredIndex,
1166 Expr *expr) {
1167 // No structured initializer list to update
1168 if (!StructuredList)
1169 return;
1170
1171 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1172 // This initializer overwrites a previous initializer. Warn.
1173 SemaRef->Diag(expr->getSourceRange().getBegin(),
1174 diag::warn_initializer_overrides)
1175 << expr->getSourceRange();
1176 SemaRef->Diag(PrevInit->getSourceRange().getBegin(),
1177 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001178 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001179 << PrevInit->getSourceRange();
1180 }
1181
1182 ++StructuredIndex;
1183}
1184
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001185/// Check that the given Index expression is a valid array designator
1186/// value. This is essentailly just a wrapper around
1187/// Expr::isIntegerConstantExpr that also checks for negative values
1188/// and produces a reasonable diagnostic if there is a
1189/// failure. Returns true if there was an error, false otherwise. If
1190/// everything went okay, Value will receive the value of the constant
1191/// expression.
1192static bool
1193CheckArrayDesignatorExpr(Sema &Self, Expr *Index, llvm::APSInt &Value) {
1194 SourceLocation Loc = Index->getSourceRange().getBegin();
1195
1196 // Make sure this is an integer constant expression.
1197 if (!Index->isIntegerConstantExpr(Value, Self.Context, &Loc))
1198 return Self.Diag(Loc, diag::err_array_designator_nonconstant)
1199 << Index->getSourceRange();
1200
1201 // Make sure this constant expression is non-negative.
Douglas Gregor69722702009-01-23 18:58:42 +00001202 llvm::APSInt Zero(llvm::APSInt::getNullValue(Value.getBitWidth()),
1203 Value.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001204 if (Value < Zero)
1205 return Self.Diag(Loc, diag::err_array_designator_negative)
1206 << Value.toString(10) << Index->getSourceRange();
1207
Douglas Gregore498e372009-01-23 21:04:18 +00001208 Value.setIsUnsigned(true);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001209 return false;
1210}
1211
1212Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1213 SourceLocation Loc,
1214 bool UsedColonSyntax,
1215 OwningExprResult Init) {
1216 typedef DesignatedInitExpr::Designator ASTDesignator;
1217
1218 bool Invalid = false;
1219 llvm::SmallVector<ASTDesignator, 32> Designators;
1220 llvm::SmallVector<Expr *, 32> InitExpressions;
1221
1222 // Build designators and check array designator expressions.
1223 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1224 const Designator &D = Desig.getDesignator(Idx);
1225 switch (D.getKind()) {
1226 case Designator::FieldDesignator:
1227 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1228 D.getFieldLoc()));
1229 break;
1230
1231 case Designator::ArrayDesignator: {
1232 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1233 llvm::APSInt IndexValue;
1234 if (CheckArrayDesignatorExpr(*this, Index, IndexValue))
1235 Invalid = true;
1236 else {
1237 Designators.push_back(ASTDesignator(InitExpressions.size(),
1238 D.getLBracketLoc(),
1239 D.getRBracketLoc()));
1240 InitExpressions.push_back(Index);
1241 }
1242 break;
1243 }
1244
1245 case Designator::ArrayRangeDesignator: {
1246 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1247 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1248 llvm::APSInt StartValue;
1249 llvm::APSInt EndValue;
1250 if (CheckArrayDesignatorExpr(*this, StartIndex, StartValue) ||
1251 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))
1252 Invalid = true;
Douglas Gregorea0528d2009-01-23 22:22:29 +00001253 else {
1254 // Make sure we're comparing values with the same bit width.
1255 if (StartValue.getBitWidth() > EndValue.getBitWidth())
1256 EndValue.extend(StartValue.getBitWidth());
1257 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1258 StartValue.extend(EndValue.getBitWidth());
1259
1260 if (EndValue < StartValue) {
1261 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1262 << StartValue.toString(10) << EndValue.toString(10)
1263 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1264 Invalid = true;
1265 } else {
1266 Designators.push_back(ASTDesignator(InitExpressions.size(),
1267 D.getLBracketLoc(),
1268 D.getEllipsisLoc(),
1269 D.getRBracketLoc()));
1270 InitExpressions.push_back(StartIndex);
1271 InitExpressions.push_back(EndIndex);
1272 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001273 }
1274 break;
1275 }
1276 }
1277 }
1278
1279 if (Invalid || Init.isInvalid())
1280 return ExprError();
1281
1282 // Clear out the expressions within the designation.
1283 Desig.ClearExprs(*this);
1284
1285 DesignatedInitExpr *DIE
1286 = DesignatedInitExpr::Create(Context, &Designators[0], Designators.size(),
1287 &InitExpressions[0], InitExpressions.size(),
1288 Loc, UsedColonSyntax,
1289 static_cast<Expr *>(Init.release()));
1290 return Owned(DIE);
1291}
Douglas Gregor849afc32009-01-29 00:45:39 +00001292
1293bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
1294 InitListChecker CheckInitList(this, InitList, DeclType);
1295 if (!CheckInitList.HadError())
1296 InitList = CheckInitList.getFullyStructuredList();
1297
1298 return CheckInitList.HadError();
1299}
Douglas Gregor538a4c22009-02-02 17:43:21 +00001300
1301/// \brief Diagnose any semantic errors with value-initialization of
1302/// the given type.
1303///
1304/// Value-initialization effectively zero-initializes any types
1305/// without user-declared constructors, and calls the default
1306/// constructor for a for any type that has a user-declared
1307/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1308/// a type with a user-declared constructor does not have an
1309/// accessible, non-deleted default constructor. In C, everything can
1310/// be value-initialized, which corresponds to C's notion of
1311/// initializing objects with static storage duration when no
1312/// initializer is provided for that object.
1313///
1314/// \returns true if there was an error, false otherwise.
1315bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1316 // C++ [dcl.init]p5:
1317 //
1318 // To value-initialize an object of type T means:
1319
1320 // -- if T is an array type, then each element is value-initialized;
1321 if (const ArrayType *AT = Context.getAsArrayType(Type))
1322 return CheckValueInitialization(AT->getElementType(), Loc);
1323
1324 if (const RecordType *RT = Type->getAsRecordType()) {
1325 if (const CXXRecordType *CXXRec = dyn_cast<CXXRecordType>(RT)) {
1326 // -- if T is a class type (clause 9) with a user-declared
1327 // constructor (12.1), then the default constructor for T is
1328 // called (and the initialization is ill-formed if T has no
1329 // accessible default constructor);
1330 if (CXXRec->getDecl()->hasUserDeclaredConstructor())
1331 // FIXME: Eventually, we'll need to put the constructor decl
1332 // into the AST.
1333 return PerformInitializationByConstructor(Type, 0, 0, Loc,
1334 SourceRange(Loc),
1335 DeclarationName(),
1336 IK_Direct);
1337 }
1338 }
1339
1340 if (Type->isReferenceType()) {
1341 // C++ [dcl.init]p5:
1342 // [...] A program that calls for default-initialization or
1343 // value-initialization of an entity of reference type is
1344 // ill-formed. [...]
1345 }
1346
1347 return false;
1348}