blob: a622ef3796f9bb4991fd2ced792bc76ca5b22605 [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//
Chris Lattnerdd8e0062009-02-24 22:27:37 +000010// This file implements semantic analysis for initializers. The main entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
13//
Chris Lattner8b419b92009-02-24 22:48:58 +000014// This file also implements Sema::CheckInitializerTypes.
Steve Naroff0cca7492008-05-01 22:18:59 +000015//
16//===----------------------------------------------------------------------===//
17
18#include "Sema.h"
Douglas Gregor05c13a32009-01-22 00:58:24 +000019#include "clang/Parse/Designator.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000020#include "clang/AST/ASTContext.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000021#include "clang/AST/ExprObjC.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000022#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000023using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000024
Chris Lattnerdd8e0062009-02-24 22:27:37 +000025//===----------------------------------------------------------------------===//
26// Sema Initialization Checking
27//===----------------------------------------------------------------------===//
28
Chris Lattner79e079d2009-02-24 23:10:27 +000029static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattner8879e3b2009-02-26 23:26:43 +000030 const ArrayType *AT = Context.getAsArrayType(DeclType);
31 if (!AT) return 0;
32
33 // See if this is a string literal or @encode.
34 Init = Init->IgnoreParens();
35
36 // Handle @encode, which is a narrow string.
37 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
38 return Init;
39
40 // Otherwise we can only handle string literals.
41 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000042 if (SL == 0) return 0;
Chris Lattner8879e3b2009-02-26 23:26:43 +000043
44 // char array can be initialized with a narrow string.
45 // Only allow char x[] = "foo"; not char x[] = L"foo";
46 if (!SL->isWide())
47 return AT->getElementType()->isCharType() ? Init : 0;
48
49 // wchar_t array can be initialized with a wide string: C99 6.7.8p15:
50 // "An array with element type compatible with wchar_t may be initialized by a
51 // wide string literal, optionally enclosed in braces."
Chris Lattner19753cf2009-02-26 23:36:02 +000052 if (Context.typesAreCompatible(Context.getWCharType(), AT->getElementType()))
Chris Lattner8879e3b2009-02-26 23:26:43 +000053 // Only allow wchar_t x[] = L"foo"; not wchar_t x[] = "foo";
54 return Init;
55
Chris Lattnerdd8e0062009-02-24 22:27:37 +000056 return 0;
57}
58
Chris Lattner95e8d652009-02-24 22:46:58 +000059static bool CheckSingleInitializer(Expr *&Init, QualType DeclType,
60 bool DirectInit, Sema &S) {
Chris Lattnerdd8e0062009-02-24 22:27:37 +000061 // Get the type before calling CheckSingleAssignmentConstraints(), since
62 // it can promote the expression.
63 QualType InitType = Init->getType();
64
Chris Lattner95e8d652009-02-24 22:46:58 +000065 if (S.getLangOptions().CPlusPlus) {
Chris Lattnerdd8e0062009-02-24 22:27:37 +000066 // FIXME: I dislike this error message. A lot.
Chris Lattner95e8d652009-02-24 22:46:58 +000067 if (S.PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
68 return S.Diag(Init->getSourceRange().getBegin(),
69 diag::err_typecheck_convert_incompatible)
70 << DeclType << Init->getType() << "initializing"
71 << Init->getSourceRange();
Chris Lattnerdd8e0062009-02-24 22:27:37 +000072 return false;
73 }
74
Chris Lattner95e8d652009-02-24 22:46:58 +000075 Sema::AssignConvertType ConvTy =
76 S.CheckSingleAssignmentConstraints(DeclType, Init);
77 return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
Chris Lattnerdd8e0062009-02-24 22:27:37 +000078 InitType, Init, "initializing");
79}
80
Chris Lattner79e079d2009-02-24 23:10:27 +000081static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
82 // Get the length of the string as parsed.
83 uint64_t StrLength =
84 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
85
Chris Lattnerdd8e0062009-02-24 22:27:37 +000086
Chris Lattner79e079d2009-02-24 23:10:27 +000087 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +000088 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
89 // C99 6.7.8p14. We have an array of character type with unknown size
90 // being initialized to a string literal.
91 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +000092 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000093 // Return a new array type (C99 6.7.8p22).
Chris Lattnerf71ae8d2009-02-24 22:41:04 +000094 DeclT = S.Context.getConstantArrayType(IAT->getElementType(), ConstVal,
95 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +000096 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000097 }
Chris Lattner19da8cd2009-02-24 23:01:39 +000098
99 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
100
101 // C99 6.7.8p14. We have an array of character type with known size. However,
102 // the size may be smaller or larger than the string we are initializing.
103 // FIXME: Avoid truncation for 64-bit length strings.
Chris Lattner79e079d2009-02-24 23:10:27 +0000104 if (StrLength-1 > CAT->getSize().getZExtValue())
Chris Lattner19da8cd2009-02-24 23:01:39 +0000105 S.Diag(Str->getSourceRange().getBegin(),
106 diag::warn_initializer_string_for_char_array_too_long)
107 << Str->getSourceRange();
108
109 // Set the type to the actual size that we are initializing. If we have
110 // something like:
111 // char x[1] = "foo";
112 // then this will set the string literal's type to char[1].
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000113 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000114}
115
116bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
117 SourceLocation InitLoc,
118 DeclarationName InitEntity,
119 bool DirectInit) {
120 if (DeclType->isDependentType() || Init->isTypeDependent())
121 return false;
122
123 // C++ [dcl.init.ref]p1:
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000124 // A variable declared to be a T& or T&&, that is "reference to type T"
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000125 // (8.3.2), shall be initialized by an object, or function, of
126 // type T or by an object that can be converted into a T.
127 if (DeclType->isReferenceType())
128 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
129
130 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
131 // of unknown size ("[]") or an object type that is not a variable array type.
132 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
133 return Diag(InitLoc, diag::err_variable_object_no_init)
134 << VAT->getSizeExpr()->getSourceRange();
135
136 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
137 if (!InitList) {
138 // FIXME: Handle wide strings
Chris Lattner79e079d2009-02-24 23:10:27 +0000139 if (Expr *Str = IsStringInit(Init, DeclType, Context)) {
140 CheckStringInit(Str, DeclType, *this);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000141 return false;
142 }
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000143
144 // C++ [dcl.init]p14:
145 // -- If the destination type is a (possibly cv-qualified) class
146 // type:
147 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
148 QualType DeclTypeC = Context.getCanonicalType(DeclType);
149 QualType InitTypeC = Context.getCanonicalType(Init->getType());
150
151 // -- If the initialization is direct-initialization, or if it is
152 // copy-initialization where the cv-unqualified version of the
153 // source type is the same class as, or a derived class of, the
154 // class of the destination, constructors are considered.
155 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
156 IsDerivedFrom(InitTypeC, DeclTypeC)) {
157 CXXConstructorDecl *Constructor
158 = PerformInitializationByConstructor(DeclType, &Init, 1,
159 InitLoc, Init->getSourceRange(),
160 InitEntity,
161 DirectInit? IK_Direct : IK_Copy);
162 return Constructor == 0;
163 }
164
165 // -- Otherwise (i.e., for the remaining copy-initialization
166 // cases), user-defined conversion sequences that can
167 // convert from the source type to the destination type or
168 // (when a conversion function is used) to a derived class
169 // thereof are enumerated as described in 13.3.1.4, and the
170 // best one is chosen through overload resolution
171 // (13.3). If the conversion cannot be done or is
172 // ambiguous, the initialization is ill-formed. The
173 // function selected is called with the initializer
174 // expression as its argument; if the function is a
175 // constructor, the call initializes a temporary of the
176 // destination type.
177 // FIXME: We're pretending to do copy elision here; return to
178 // this when we have ASTs for such things.
179 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
180 return false;
181
182 if (InitEntity)
183 return Diag(InitLoc, diag::err_cannot_initialize_decl)
184 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
185 << Init->getType() << Init->getSourceRange();
186 else
187 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
188 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
189 << Init->getType() << Init->getSourceRange();
190 }
191
192 // C99 6.7.8p16.
193 if (DeclType->isArrayType())
194 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
195 << Init->getSourceRange();
196
Chris Lattner95e8d652009-02-24 22:46:58 +0000197 return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000198 }
199
200 bool hadError = CheckInitList(InitList, DeclType);
201 Init = InitList;
202 return hadError;
203}
204
205//===----------------------------------------------------------------------===//
206// Semantic checking for initializer lists.
207//===----------------------------------------------------------------------===//
208
Douglas Gregor9e80f722009-01-29 01:05:33 +0000209/// @brief Semantic checking for initializer lists.
210///
211/// The InitListChecker class contains a set of routines that each
212/// handle the initialization of a certain kind of entity, e.g.,
213/// arrays, vectors, struct/union types, scalars, etc. The
214/// InitListChecker itself performs a recursive walk of the subobject
215/// structure of the type to be initialized, while stepping through
216/// the initializer list one element at a time. The IList and Index
217/// parameters to each of the Check* routines contain the active
218/// (syntactic) initializer list and the index into that initializer
219/// list that represents the current initializer. Each routine is
220/// responsible for moving that Index forward as it consumes elements.
221///
222/// Each Check* routine also has a StructuredList/StructuredIndex
223/// arguments, which contains the current the "structured" (semantic)
224/// initializer list and the index into that initializer list where we
225/// are copying initializers as we map them over to the semantic
226/// list. Once we have completed our recursive walk of the subobject
227/// structure, we will have constructed a full semantic initializer
228/// list.
229///
230/// C99 designators cause changes in the initializer list traversal,
231/// because they make the initialization "jump" into a specific
232/// subobject and then continue the initialization from that
233/// point. CheckDesignatedInitializer() recursively steps into the
234/// designated subobject and manages backing out the recursion to
235/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000236namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000237class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000238 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000239 bool hadError;
240 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
241 InitListExpr *FullyStructuredList;
242
243 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000244 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000245 unsigned &StructuredIndex,
246 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000247 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000248 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000249 unsigned &StructuredIndex,
250 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000251 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
252 bool SubobjectIsDesignatorContext,
253 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000254 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000255 unsigned &StructuredIndex,
256 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000257 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
258 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000259 InitListExpr *StructuredList,
260 unsigned &StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000261 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000262 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000263 InitListExpr *StructuredList,
264 unsigned &StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000265 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
266 unsigned &Index,
267 InitListExpr *StructuredList,
268 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000269 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000270 InitListExpr *StructuredList,
271 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000272 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
273 RecordDecl::field_iterator Field,
274 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000275 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000276 unsigned &StructuredIndex,
277 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000278 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
279 llvm::APSInt elementIndex,
280 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000281 InitListExpr *StructuredList,
282 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000283 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000284 unsigned DesigIdx,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000285 QualType &CurrentObjectType,
286 RecordDecl::field_iterator *NextField,
287 llvm::APSInt *NextElementIndex,
288 unsigned &Index,
289 InitListExpr *StructuredList,
290 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000291 bool FinishSubobjectInit,
292 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000293 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
294 QualType CurrentObjectType,
295 InitListExpr *StructuredList,
296 unsigned StructuredIndex,
297 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000298 void UpdateStructuredListElement(InitListExpr *StructuredList,
299 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000300 Expr *expr);
301 int numArrayElements(QualType DeclType);
302 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000303
304 void FillInValueInitializations(InitListExpr *ILE);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000305public:
Chris Lattner08202542009-02-24 22:50:46 +0000306 InitListChecker(Sema &S, InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000307 bool HadError() { return hadError; }
308
309 // @brief Retrieves the fully-structured initializer list used for
310 // semantic analysis and code generation.
311 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
312};
Chris Lattner8b419b92009-02-24 22:48:58 +0000313} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000314
Douglas Gregor4c678342009-01-28 21:54:33 +0000315/// Recursively replaces NULL values within the given initializer list
316/// with expressions that perform value-initialization of the
317/// appropriate type.
Douglas Gregor930d8b52009-01-30 22:09:00 +0000318void InitListChecker::FillInValueInitializations(InitListExpr *ILE) {
Chris Lattner08202542009-02-24 22:50:46 +0000319 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000320 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000321 SourceLocation Loc = ILE->getSourceRange().getBegin();
322 if (ILE->getSyntacticForm())
323 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
324
Douglas Gregor4c678342009-01-28 21:54:33 +0000325 if (const RecordType *RType = ILE->getType()->getAsRecordType()) {
326 unsigned Init = 0, NumInits = ILE->getNumInits();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000327 for (RecordDecl::field_iterator
328 Field = RType->getDecl()->field_begin(SemaRef.Context),
329 FieldEnd = RType->getDecl()->field_end(SemaRef.Context);
Douglas Gregor4c678342009-01-28 21:54:33 +0000330 Field != FieldEnd; ++Field) {
331 if (Field->isUnnamedBitfield())
332 continue;
333
Douglas Gregor87fd7032009-02-02 17:43:21 +0000334 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000335 if (Field->getType()->isReferenceType()) {
336 // C++ [dcl.init.aggr]p9:
337 // If an incomplete or empty initializer-list leaves a
338 // member of reference type uninitialized, the program is
339 // ill-formed.
Chris Lattner08202542009-02-24 22:50:46 +0000340 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000341 << Field->getType()
342 << ILE->getSyntacticForm()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +0000343 SemaRef.Diag(Field->getLocation(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000344 diag::note_uninit_reference_member);
345 hadError = true;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000346 return;
Chris Lattner08202542009-02-24 22:50:46 +0000347 } else if (SemaRef.CheckValueInitialization(Field->getType(), Loc)) {
Douglas Gregor87fd7032009-02-02 17:43:21 +0000348 hadError = true;
349 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000350 }
Douglas Gregor87fd7032009-02-02 17:43:21 +0000351
352 // FIXME: If value-initialization involves calling a
353 // constructor, should we make that call explicit in the
354 // representation (even when it means extending the
355 // initializer list)?
356 if (Init < NumInits && !hadError)
357 ILE->setInit(Init,
Chris Lattner08202542009-02-24 22:50:46 +0000358 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()));
Douglas Gregor87fd7032009-02-02 17:43:21 +0000359 } else if (InitListExpr *InnerILE
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000360 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000361 FillInValueInitializations(InnerILE);
Douglas Gregor4c678342009-01-28 21:54:33 +0000362 ++Init;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000363
364 // Only look at the first initialization of a union.
365 if (RType->getDecl()->isUnion())
366 break;
Douglas Gregor4c678342009-01-28 21:54:33 +0000367 }
368
369 return;
370 }
371
372 QualType ElementType;
373
Douglas Gregor87fd7032009-02-02 17:43:21 +0000374 unsigned NumInits = ILE->getNumInits();
375 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000376 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000377 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000378 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
379 NumElements = CAType->getSize().getZExtValue();
380 } else if (const VectorType *VType = ILE->getType()->getAsVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000381 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000382 NumElements = VType->getNumElements();
383 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000384 ElementType = ILE->getType();
385
Douglas Gregor87fd7032009-02-02 17:43:21 +0000386 for (unsigned Init = 0; Init != NumElements; ++Init) {
387 if (Init >= NumInits || !ILE->getInit(Init)) {
Chris Lattner08202542009-02-24 22:50:46 +0000388 if (SemaRef.CheckValueInitialization(ElementType, Loc)) {
Douglas Gregor87fd7032009-02-02 17:43:21 +0000389 hadError = true;
390 return;
391 }
392
393 // FIXME: If value-initialization involves calling a
394 // constructor, should we make that call explicit in the
395 // representation (even when it means extending the
396 // initializer list)?
397 if (Init < NumInits && !hadError)
398 ILE->setInit(Init,
Chris Lattner08202542009-02-24 22:50:46 +0000399 new (SemaRef.Context) ImplicitValueInitExpr(ElementType));
Douglas Gregor87fd7032009-02-02 17:43:21 +0000400 }
Chris Lattner68355a52009-01-29 05:10:57 +0000401 else if (InitListExpr *InnerILE =dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000402 FillInValueInitializations(InnerILE);
Douglas Gregor4c678342009-01-28 21:54:33 +0000403 }
404}
405
Chris Lattner68355a52009-01-29 05:10:57 +0000406
Chris Lattner08202542009-02-24 22:50:46 +0000407InitListChecker::InitListChecker(Sema &S, InitListExpr *IL, QualType &T)
408 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000409 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000410
Eli Friedmanb85f7072008-05-19 19:16:24 +0000411 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000412 unsigned newStructuredIndex = 0;
413 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000414 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000415 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
416 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000417
Douglas Gregor930d8b52009-01-30 22:09:00 +0000418 if (!hadError)
419 FillInValueInitializations(FullyStructuredList);
Steve Naroff0cca7492008-05-01 22:18:59 +0000420}
421
422int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000423 // FIXME: use a proper constant
424 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000425 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000426 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000427 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
428 }
429 return maxElements;
430}
431
432int InitListChecker::numStructUnionElements(QualType DeclType) {
433 RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000434 int InitializableMembers = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000435 for (RecordDecl::field_iterator
436 Field = structDecl->field_begin(SemaRef.Context),
437 FieldEnd = structDecl->field_end(SemaRef.Context);
Douglas Gregor4c678342009-01-28 21:54:33 +0000438 Field != FieldEnd; ++Field) {
439 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
440 ++InitializableMembers;
441 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000442 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000443 return std::min(InitializableMembers, 1);
444 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000445}
446
447void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000448 QualType T, unsigned &Index,
449 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000450 unsigned &StructuredIndex,
451 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000452 int maxElements = 0;
453
454 if (T->isArrayType())
455 maxElements = numArrayElements(T);
456 else if (T->isStructureType() || T->isUnionType())
457 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000458 else if (T->isVectorType())
459 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000460 else
461 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000462
Eli Friedman402256f2008-05-25 13:49:22 +0000463 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000464 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000465 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000466 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000467 hadError = true;
468 return;
469 }
470
Douglas Gregor4c678342009-01-28 21:54:33 +0000471 // Build a structured initializer list corresponding to this subobject.
472 InitListExpr *StructuredSubobjectInitList
473 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
474 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000475 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
476 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000477 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000478
Douglas Gregor4c678342009-01-28 21:54:33 +0000479 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000480 unsigned StartIndex = Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000481 CheckListElementTypes(ParentIList, T, false, Index,
482 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000483 StructuredSubobjectInitIndex,
484 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000485 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000486 StructuredSubobjectInitList->setType(T);
487
Douglas Gregored8a93d2009-03-01 17:12:46 +0000488 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000489 // range corresponds with the end of the last initializer it used.
490 if (EndIndex < ParentIList->getNumInits()) {
491 SourceLocation EndLoc
492 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
493 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
494 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000495}
496
Steve Naroffa647caa2008-05-06 00:23:44 +0000497void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000498 unsigned &Index,
499 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000500 unsigned &StructuredIndex,
501 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000502 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000503 SyntacticToSemantic[IList] = StructuredList;
504 StructuredList->setSyntacticForm(IList);
505 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000506 StructuredIndex, TopLevelObject);
Steve Naroffa647caa2008-05-06 00:23:44 +0000507 IList->setType(T);
Douglas Gregor4c678342009-01-28 21:54:33 +0000508 StructuredList->setType(T);
Eli Friedman638e1442008-05-25 13:22:35 +0000509 if (hadError)
510 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000511
Eli Friedman638e1442008-05-25 13:22:35 +0000512 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000513 // We have leftover initializers
514 if (IList->getNumInits() > 0 &&
Chris Lattner08202542009-02-24 22:50:46 +0000515 IsStringInit(IList->getInit(Index), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000516 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Chris Lattner08202542009-02-24 22:50:46 +0000517 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000518 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000519 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000520 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000521 << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000522 hadError = true;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000523 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000524 // Don't complain for incomplete types, since we'll get an error
525 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000526 QualType CurrentObjectType = StructuredList->getType();
527 int initKind =
528 CurrentObjectType->isArrayType()? 0 :
529 CurrentObjectType->isVectorType()? 1 :
530 CurrentObjectType->isScalarType()? 2 :
531 CurrentObjectType->isUnionType()? 3 :
532 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000533
534 unsigned DK = diag::warn_excess_initializers;
Chris Lattner08202542009-02-24 22:50:46 +0000535 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000536 DK = diag::err_excess_initializers;
537
Chris Lattner08202542009-02-24 22:50:46 +0000538 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000539 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000540 }
541 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000542
Eli Friedman638e1442008-05-25 13:22:35 +0000543 if (T->isScalarType())
Chris Lattner08202542009-02-24 22:50:46 +0000544 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000545 << IList->getSourceRange()
546 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocStart()))
547 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocEnd()));
Steve Naroff0cca7492008-05-01 22:18:59 +0000548}
549
Eli Friedmanb85f7072008-05-19 19:16:24 +0000550void InitListChecker::CheckListElementTypes(InitListExpr *IList,
551 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000552 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000553 unsigned &Index,
554 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000555 unsigned &StructuredIndex,
556 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000557 if (DeclType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000558 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000559 } else if (DeclType->isVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000560 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000561 } else if (DeclType->isAggregateType()) {
562 if (DeclType->isRecordType()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000563 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000564 CheckStructUnionTypes(IList, DeclType, RD->field_begin(SemaRef.Context),
Douglas Gregor4c678342009-01-28 21:54:33 +0000565 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000566 StructuredList, StructuredIndex,
567 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000568 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000569 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000570 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000571 false);
Douglas Gregor4c678342009-01-28 21:54:33 +0000572 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
573 StructuredList, StructuredIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000574 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000575 else
Douglas Gregor4c678342009-01-28 21:54:33 +0000576 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000577 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
578 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000579 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000580 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000581 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000582 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000583 } else if (DeclType->isRecordType()) {
584 // C++ [dcl.init]p14:
585 // [...] If the class is an aggregate (8.5.1), and the initializer
586 // is a brace-enclosed list, see 8.5.1.
587 //
588 // Note: 8.5.1 is handled below; here, we diagnose the case where
589 // we have an initializer list and a destination type that is not
590 // an aggregate.
591 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000592 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000593 << DeclType << IList->getSourceRange();
594 hadError = true;
595 } else if (DeclType->isReferenceType()) {
596 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000597 } else {
598 // In C, all types are either scalars or aggregates, but
599 // additional handling is needed here for C++ (and possibly others?).
600 assert(0 && "Unsupported initializer type");
601 }
602}
603
Eli Friedmanb85f7072008-05-19 19:16:24 +0000604void InitListChecker::CheckSubElementType(InitListExpr *IList,
605 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000606 unsigned &Index,
607 InitListExpr *StructuredList,
608 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000609 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000610 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
611 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000612 unsigned newStructuredIndex = 0;
613 InitListExpr *newStructuredList
614 = getStructuredSubobjectInit(IList, Index, ElemType,
615 StructuredList, StructuredIndex,
616 SubInitList->getSourceRange());
617 CheckExplicitInitList(SubInitList, ElemType, newIndex,
618 newStructuredList, newStructuredIndex);
619 ++StructuredIndex;
620 ++Index;
Chris Lattner79e079d2009-02-24 23:10:27 +0000621 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
622 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000623 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000624 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000625 } else if (ElemType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000626 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000627 } else if (ElemType->isReferenceType()) {
628 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000629 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000630 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000631 // C++ [dcl.init.aggr]p12:
632 // All implicit type conversions (clause 4) are considered when
633 // initializing the aggregate member with an ini- tializer from
634 // an initializer-list. If the initializer can initialize a
635 // member, the member is initialized. [...]
636 ImplicitConversionSequence ICS
Chris Lattner08202542009-02-24 22:50:46 +0000637 = SemaRef.TryCopyInitialization(expr, ElemType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000638 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Chris Lattner08202542009-02-24 22:50:46 +0000639 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000640 "initializing"))
641 hadError = true;
642 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
643 ++Index;
644 return;
645 }
646
647 // Fall through for subaggregate initialization
648 } else {
649 // C99 6.7.8p13:
650 //
651 // The initializer for a structure or union object that has
652 // automatic storage duration shall be either an initializer
653 // list as described below, or a single expression that has
654 // compatible structure or union type. In the latter case, the
655 // initial value of the object, including unnamed members, is
656 // that of the expression.
Chris Lattner08202542009-02-24 22:50:46 +0000657 QualType ExprType = SemaRef.Context.getCanonicalType(expr->getType());
658 QualType ElemTypeCanon = SemaRef.Context.getCanonicalType(ElemType);
659 if (SemaRef.Context.typesAreCompatible(ExprType.getUnqualifiedType(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000660 ElemTypeCanon.getUnqualifiedType())) {
661 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
662 ++Index;
663 return;
664 }
665
666 // Fall through for subaggregate initialization
667 }
668
669 // C++ [dcl.init.aggr]p12:
670 //
671 // [...] Otherwise, if the member is itself a non-empty
672 // subaggregate, brace elision is assumed and the initializer is
673 // considered for the initialization of the first member of
674 // the subaggregate.
675 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
676 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
677 StructuredIndex);
678 ++StructuredIndex;
679 } else {
680 // We cannot initialize this element, so let
681 // PerformCopyInitialization produce the appropriate diagnostic.
Chris Lattner08202542009-02-24 22:50:46 +0000682 SemaRef.PerformCopyInitialization(expr, ElemType, "initializing");
Douglas Gregor930d8b52009-01-30 22:09:00 +0000683 hadError = true;
684 ++Index;
685 ++StructuredIndex;
686 }
687 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000688}
689
Douglas Gregor930d8b52009-01-30 22:09:00 +0000690void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000691 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000692 InitListExpr *StructuredList,
693 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000694 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000695 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000696 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000697 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000698 diag::err_many_braces_around_scalar_init)
699 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000700 hadError = true;
701 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000702 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000703 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000704 } else if (isa<DesignatedInitExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000705 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor05c13a32009-01-22 00:58:24 +0000706 diag::err_designator_for_scalar_init)
707 << DeclType << expr->getSourceRange();
708 hadError = true;
709 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000710 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000711 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000712 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000713
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000714 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner08202542009-02-24 22:50:46 +0000715 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedmanbb504d32008-05-19 20:12:18 +0000716 hadError = true; // types weren't compatible.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000717 else if (savExpr != expr) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000718 // The type was promoted, update initializer list.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000719 IList->setInit(Index, expr);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000720 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000721 if (hadError)
722 ++StructuredIndex;
723 else
724 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000725 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000726 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000727 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000728 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000729 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000730 ++Index;
731 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000732 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000733 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000734}
735
Douglas Gregor930d8b52009-01-30 22:09:00 +0000736void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
737 unsigned &Index,
738 InitListExpr *StructuredList,
739 unsigned &StructuredIndex) {
740 if (Index < IList->getNumInits()) {
741 Expr *expr = IList->getInit(Index);
742 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000743 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000744 << DeclType << IList->getSourceRange();
745 hadError = true;
746 ++Index;
747 ++StructuredIndex;
748 return;
749 }
750
751 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner08202542009-02-24 22:50:46 +0000752 if (SemaRef.CheckReferenceInit(expr, DeclType))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000753 hadError = true;
754 else if (savExpr != expr) {
755 // The type was promoted, update initializer list.
756 IList->setInit(Index, expr);
757 }
758 if (hadError)
759 ++StructuredIndex;
760 else
761 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
762 ++Index;
763 } else {
764 // FIXME: It would be wonderful if we could point at the actual
765 // member. In general, it would be useful to pass location
766 // information down the stack, so that we know the location (or
767 // decl) of the "current object" being initialized.
Chris Lattner08202542009-02-24 22:50:46 +0000768 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000769 diag::err_init_reference_member_uninitialized)
770 << DeclType
771 << IList->getSourceRange();
772 hadError = true;
773 ++Index;
774 ++StructuredIndex;
775 return;
776 }
777}
778
Steve Naroff0cca7492008-05-01 22:18:59 +0000779void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000780 unsigned &Index,
781 InitListExpr *StructuredList,
782 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000783 if (Index < IList->getNumInits()) {
784 const VectorType *VT = DeclType->getAsVectorType();
785 int maxElements = VT->getNumElements();
786 QualType elementType = VT->getElementType();
787
788 for (int i = 0; i < maxElements; ++i) {
789 // Don't attempt to go past the end of the init list
790 if (Index >= IList->getNumInits())
791 break;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000792 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000793 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000794 }
795 }
796}
797
798void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000799 llvm::APSInt elementIndex,
800 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000801 unsigned &Index,
802 InitListExpr *StructuredList,
803 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000804 // Check for the special-case of initializing an array with a string.
805 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000806 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
807 SemaRef.Context)) {
808 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +0000809 // We place the string literal directly into the resulting
810 // initializer list. This is the only place where the structure
811 // of the structured initializer list doesn't match exactly,
812 // because doing so would involve allocating one character
813 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000814 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +0000815 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000816 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000817 return;
818 }
819 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000820 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +0000821 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000822 // Check for VLAs; in standard C it would be possible to check this
823 // earlier, but I don't know where clang accepts VLAs (gcc accepts
824 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +0000825 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000826 diag::err_variable_object_no_init)
827 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000828 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000829 ++Index;
830 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000831 return;
832 }
833
Douglas Gregor05c13a32009-01-22 00:58:24 +0000834 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000835 llvm::APSInt maxElements(elementIndex.getBitWidth(),
836 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000837 bool maxElementsKnown = false;
838 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000839 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000840 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000841 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000842 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000843 maxElementsKnown = true;
844 }
845
Chris Lattner08202542009-02-24 22:50:46 +0000846 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000847 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000848 while (Index < IList->getNumInits()) {
849 Expr *Init = IList->getInit(Index);
850 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000851 // If we're not the subobject that matches up with the '{' for
852 // the designator, we shouldn't be handling the
853 // designator. Return immediately.
854 if (!SubobjectIsDesignatorContext)
855 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000856
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000857 // Handle this designated initializer. elementIndex will be
858 // updated to be the next array element we'll initialize.
Douglas Gregor71199712009-04-15 04:56:10 +0000859 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +0000860 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000861 StructuredList, StructuredIndex, true,
862 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000863 hadError = true;
864 continue;
865 }
866
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000867 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
868 maxElements.extend(elementIndex.getBitWidth());
869 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
870 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000871 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000872
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000873 // If the array is of incomplete type, keep track of the number of
874 // elements in the initializer.
875 if (!maxElementsKnown && elementIndex > maxElements)
876 maxElements = elementIndex;
877
Douglas Gregor05c13a32009-01-22 00:58:24 +0000878 continue;
879 }
880
881 // If we know the maximum number of elements, and we've already
882 // hit it, stop consuming elements in the initializer list.
883 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +0000884 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000885
886 // Check this element.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000887 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000888 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000889 ++elementIndex;
890
891 // If the array is of incomplete type, keep track of the number of
892 // elements in the initializer.
893 if (!maxElementsKnown && elementIndex > maxElements)
894 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +0000895 }
896 if (DeclType->isIncompleteArrayType()) {
897 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000898 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000899 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000900 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000901 // Sizing an array implicitly to zero is not allowed by ISO C,
902 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +0000903 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000904 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +0000905 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000906
Chris Lattner08202542009-02-24 22:50:46 +0000907 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000908 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +0000909 }
910}
911
912void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
913 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000914 RecordDecl::field_iterator Field,
915 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000916 unsigned &Index,
917 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000918 unsigned &StructuredIndex,
919 bool TopLevelObject) {
Eli Friedmanb85f7072008-05-19 19:16:24 +0000920 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroff0cca7492008-05-01 22:18:59 +0000921
Eli Friedmanb85f7072008-05-19 19:16:24 +0000922 // If the record is invalid, some of it's members are invalid. To avoid
923 // confusion, we forgo checking the intializer for the entire record.
924 if (structDecl->isInvalidDecl()) {
925 hadError = true;
926 return;
927 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000928
929 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
930 // Value-initialize the first named member of the union.
931 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000932 for (RecordDecl::field_iterator FieldEnd = RD->field_end(SemaRef.Context);
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000933 Field != FieldEnd; ++Field) {
934 if (Field->getDeclName()) {
935 StructuredList->setInitializedFieldInUnion(*Field);
936 break;
937 }
938 }
939 return;
940 }
941
Douglas Gregor05c13a32009-01-22 00:58:24 +0000942 // If structDecl is a forward declaration, this loop won't do
943 // anything except look at designated initializers; That's okay,
944 // because an error should get printed out elsewhere. It might be
945 // worthwhile to skip over the rest of the initializer, though.
Douglas Gregor44b43212008-12-11 16:49:14 +0000946 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000947 RecordDecl::field_iterator FieldEnd = RD->field_end(SemaRef.Context);
Douglas Gregordfb5e592009-02-12 19:00:39 +0000948 bool InitializedSomething = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000949 while (Index < IList->getNumInits()) {
950 Expr *Init = IList->getInit(Index);
951
952 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000953 // If we're not the subobject that matches up with the '{' for
954 // the designator, we shouldn't be handling the
955 // designator. Return immediately.
956 if (!SubobjectIsDesignatorContext)
957 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000958
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000959 // Handle this designated initializer. Field will be updated to
960 // the next field that we'll be initializing.
Douglas Gregor71199712009-04-15 04:56:10 +0000961 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +0000962 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000963 StructuredList, StructuredIndex,
964 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000965 hadError = true;
966
Douglas Gregordfb5e592009-02-12 19:00:39 +0000967 InitializedSomething = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000968 continue;
969 }
970
971 if (Field == FieldEnd) {
972 // We've run out of fields. We're done.
973 break;
974 }
975
Douglas Gregordfb5e592009-02-12 19:00:39 +0000976 // We've already initialized a member of a union. We're done.
977 if (InitializedSomething && DeclType->isUnionType())
978 break;
979
Douglas Gregor44b43212008-12-11 16:49:14 +0000980 // If we've hit the flexible array member at the end, we're done.
981 if (Field->getType()->isIncompleteArrayType())
982 break;
983
Douglas Gregor0bb76892009-01-29 16:53:55 +0000984 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000985 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +0000986 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000987 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +0000988 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000989
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000990 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000991 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +0000992 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +0000993
994 if (DeclType->isUnionType()) {
995 // Initialize the first field within the union.
996 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +0000997 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000998
999 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001000 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001001
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001002 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001003 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001004 return;
1005
1006 // Handle GNU flexible array initializers.
1007 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001008 (!isa<InitListExpr>(IList->getInit(Index)) ||
1009 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Chris Lattner08202542009-02-24 22:50:46 +00001010 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001011 diag::err_flexible_array_init_nonempty)
1012 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001013 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001014 << *Field;
1015 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001016 ++Index;
1017 return;
1018 } else {
1019 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
1020 diag::ext_flexible_array_init)
1021 << IList->getInit(Index)->getSourceRange().getBegin();
1022 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1023 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001024 }
1025
Douglas Gregora6457962009-03-20 00:32:56 +00001026 if (isa<InitListExpr>(IList->getInit(Index)))
1027 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1028 StructuredIndex);
1029 else
1030 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1031 StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001032}
Steve Naroff0cca7492008-05-01 22:18:59 +00001033
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001034/// \brief Expand a field designator that refers to a member of an
1035/// anonymous struct or union into a series of field designators that
1036/// refers to the field within the appropriate subobject.
1037///
1038/// Field/FieldIndex will be updated to point to the (new)
1039/// currently-designated field.
1040static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1041 DesignatedInitExpr *DIE,
1042 unsigned DesigIdx,
1043 FieldDecl *Field,
1044 RecordDecl::field_iterator &FieldIter,
1045 unsigned &FieldIndex) {
1046 typedef DesignatedInitExpr::Designator Designator;
1047
1048 // Build the path from the current object to the member of the
1049 // anonymous struct/union (backwards).
1050 llvm::SmallVector<FieldDecl *, 4> Path;
1051 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
1052
1053 // Build the replacement designators.
1054 llvm::SmallVector<Designator, 4> Replacements;
1055 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1056 FI = Path.rbegin(), FIEnd = Path.rend();
1057 FI != FIEnd; ++FI) {
1058 if (FI + 1 == FIEnd)
1059 Replacements.push_back(Designator((IdentifierInfo *)0,
1060 DIE->getDesignator(DesigIdx)->getDotLoc(),
1061 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1062 else
1063 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1064 SourceLocation()));
1065 Replacements.back().setField(*FI);
1066 }
1067
1068 // Expand the current designator into the set of replacement
1069 // designators, so we have a full subobject path down to where the
1070 // member of the anonymous struct/union is actually stored.
1071 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
1072 &Replacements[0] + Replacements.size());
1073
1074 // Update FieldIter/FieldIndex;
1075 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
1076 FieldIter = Record->field_begin(SemaRef.Context);
1077 FieldIndex = 0;
1078 for (RecordDecl::field_iterator FEnd = Record->field_end(SemaRef.Context);
1079 FieldIter != FEnd; ++FieldIter) {
1080 if (FieldIter->isUnnamedBitfield())
1081 continue;
1082
1083 if (*FieldIter == Path.back())
1084 return;
1085
1086 ++FieldIndex;
1087 }
1088
1089 assert(false && "Unable to find anonymous struct/union field");
1090}
1091
Douglas Gregor05c13a32009-01-22 00:58:24 +00001092/// @brief Check the well-formedness of a C99 designated initializer.
1093///
1094/// Determines whether the designated initializer @p DIE, which
1095/// resides at the given @p Index within the initializer list @p
1096/// IList, is well-formed for a current object of type @p DeclType
1097/// (C99 6.7.8). The actual subobject that this designator refers to
1098/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001099/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001100///
1101/// @param IList The initializer list in which this designated
1102/// initializer occurs.
1103///
Douglas Gregor71199712009-04-15 04:56:10 +00001104/// @param DIE The designated initializer expression.
1105///
1106/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001107///
1108/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1109/// into which the designation in @p DIE should refer.
1110///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001111/// @param NextField If non-NULL and the first designator in @p DIE is
1112/// a field, this will be set to the field declaration corresponding
1113/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001114///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001115/// @param NextElementIndex If non-NULL and the first designator in @p
1116/// DIE is an array designator or GNU array-range designator, this
1117/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001118///
1119/// @param Index Index into @p IList where the designated initializer
1120/// @p DIE occurs.
1121///
Douglas Gregor4c678342009-01-28 21:54:33 +00001122/// @param StructuredList The initializer list expression that
1123/// describes all of the subobject initializers in the order they'll
1124/// actually be initialized.
1125///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001126/// @returns true if there was an error, false otherwise.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001127bool
1128InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
1129 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001130 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001131 QualType &CurrentObjectType,
1132 RecordDecl::field_iterator *NextField,
1133 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001134 unsigned &Index,
1135 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001136 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001137 bool FinishSubobjectInit,
1138 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001139 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001140 // Check the actual initialization for the designated object type.
1141 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001142
1143 // Temporarily remove the designator expression from the
1144 // initializer list that the child calls see, so that we don't try
1145 // to re-process the designator.
1146 unsigned OldIndex = Index;
1147 IList->setInit(OldIndex, DIE->getInit());
1148
1149 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001150 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001151
1152 // Restore the designated initializer expression in the syntactic
1153 // form of the initializer list.
1154 if (IList->getInit(OldIndex) != DIE->getInit())
1155 DIE->setInit(IList->getInit(OldIndex));
1156 IList->setInit(OldIndex, DIE);
1157
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001158 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001159 }
1160
Douglas Gregor71199712009-04-15 04:56:10 +00001161 bool IsFirstDesignator = (DesigIdx == 0);
Douglas Gregor4c678342009-01-28 21:54:33 +00001162 assert((IsFirstDesignator || StructuredList) &&
1163 "Need a non-designated initializer list to start from");
1164
Douglas Gregor71199712009-04-15 04:56:10 +00001165 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001166 // Determine the structural initializer list that corresponds to the
1167 // current subobject.
1168 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Douglas Gregored8a93d2009-03-01 17:12:46 +00001169 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1170 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001171 SourceRange(D->getStartLocation(),
1172 DIE->getSourceRange().getEnd()));
1173 assert(StructuredList && "Expected a structured initializer list");
1174
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001175 if (D->isFieldDesignator()) {
1176 // C99 6.7.8p7:
1177 //
1178 // If a designator has the form
1179 //
1180 // . identifier
1181 //
1182 // then the current object (defined below) shall have
1183 // structure or union type and the identifier shall be the
1184 // name of a member of that type.
1185 const RecordType *RT = CurrentObjectType->getAsRecordType();
1186 if (!RT) {
1187 SourceLocation Loc = D->getDotLoc();
1188 if (Loc.isInvalid())
1189 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001190 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1191 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001192 ++Index;
1193 return true;
1194 }
1195
Douglas Gregor4c678342009-01-28 21:54:33 +00001196 // Note: we perform a linear search of the fields here, despite
1197 // the fact that we have a faster lookup method, because we always
1198 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001199 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001200 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001201 unsigned FieldIndex = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001202 RecordDecl::field_iterator
1203 Field = RT->getDecl()->field_begin(SemaRef.Context),
1204 FieldEnd = RT->getDecl()->field_end(SemaRef.Context);
Douglas Gregor4c678342009-01-28 21:54:33 +00001205 for (; Field != FieldEnd; ++Field) {
1206 if (Field->isUnnamedBitfield())
1207 continue;
1208
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001209 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor4c678342009-01-28 21:54:33 +00001210 break;
1211
1212 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001213 }
1214
Douglas Gregor4c678342009-01-28 21:54:33 +00001215 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001216 // There was no normal field in the struct with the designated
1217 // name. Perform another lookup for this name, which may find
1218 // something that we can't designate (e.g., a member function),
1219 // may find nothing, or may find a member of an anonymous
1220 // struct/union.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001221 DeclContext::lookup_result Lookup
1222 = RT->getDecl()->lookup(SemaRef.Context, FieldName);
Douglas Gregor4c678342009-01-28 21:54:33 +00001223 if (Lookup.first == Lookup.second) {
1224 // Name lookup didn't find anything.
Chris Lattner08202542009-02-24 22:50:46 +00001225 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregor4c678342009-01-28 21:54:33 +00001226 << FieldName << CurrentObjectType;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001227 ++Index;
1228 return true;
1229 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1230 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1231 ->isAnonymousStructOrUnion()) {
1232 // Handle an field designator that refers to a member of an
1233 // anonymous struct or union.
1234 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1235 cast<FieldDecl>(*Lookup.first),
1236 Field, FieldIndex);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001237 D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001238 } else {
1239 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001240 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001241 << FieldName;
Chris Lattner08202542009-02-24 22:50:46 +00001242 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001243 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001244 ++Index;
1245 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001246 }
1247 } else if (!KnownField &&
1248 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor4c678342009-01-28 21:54:33 +00001249 ->isAnonymousStructOrUnion()) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001250 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1251 Field, FieldIndex);
1252 D = DIE->getDesignator(DesigIdx);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001253 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001254
1255 // All of the fields of a union are located at the same place in
1256 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001257 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001258 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001259 StructuredList->setInitializedFieldInUnion(*Field);
1260 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001261
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001262 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001263 D->setField(*Field);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001264
Douglas Gregor4c678342009-01-28 21:54:33 +00001265 // Make sure that our non-designated initializer list has space
1266 // for a subobject corresponding to this field.
1267 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001268 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001269
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001270 // This designator names a flexible array member.
1271 if (Field->getType()->isIncompleteArrayType()) {
1272 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001273 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001274 // We can't designate an object within the flexible array
1275 // member (because GCC doesn't allow it).
Douglas Gregor71199712009-04-15 04:56:10 +00001276 DesignatedInitExpr::Designator *NextD
1277 = DIE->getDesignator(DesigIdx + 1);
Chris Lattner08202542009-02-24 22:50:46 +00001278 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001279 diag::err_designator_into_flexible_array_member)
1280 << SourceRange(NextD->getStartLocation(),
1281 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001282 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001283 << *Field;
1284 Invalid = true;
1285 }
1286
1287 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1288 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001289 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001290 diag::err_flexible_array_init_needs_braces)
1291 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001292 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001293 << *Field;
1294 Invalid = true;
1295 }
1296
1297 // Handle GNU flexible array initializers.
1298 if (!Invalid && !TopLevelObject &&
1299 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Chris Lattner08202542009-02-24 22:50:46 +00001300 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001301 diag::err_flexible_array_init_nonempty)
1302 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001303 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001304 << *Field;
1305 Invalid = true;
1306 }
1307
1308 if (Invalid) {
1309 ++Index;
1310 return true;
1311 }
1312
1313 // Initialize the array.
1314 bool prevHadError = hadError;
1315 unsigned newStructuredIndex = FieldIndex;
1316 unsigned OldIndex = Index;
1317 IList->setInit(Index, DIE->getInit());
1318 CheckSubElementType(IList, Field->getType(), Index,
1319 StructuredList, newStructuredIndex);
1320 IList->setInit(OldIndex, DIE);
1321 if (hadError && !prevHadError) {
1322 ++Field;
1323 ++FieldIndex;
1324 if (NextField)
1325 *NextField = Field;
1326 StructuredIndex = FieldIndex;
1327 return true;
1328 }
1329 } else {
1330 // Recurse to check later designated subobjects.
1331 QualType FieldType = (*Field)->getType();
1332 unsigned newStructuredIndex = FieldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001333 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1334 Index, StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001335 true, false))
1336 return true;
1337 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001338
1339 // Find the position of the next field to be initialized in this
1340 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001341 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001342 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001343
1344 // If this the first designator, our caller will continue checking
1345 // the rest of this struct/class/union subobject.
1346 if (IsFirstDesignator) {
1347 if (NextField)
1348 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001349 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001350 return false;
1351 }
1352
Douglas Gregor34e79462009-01-28 23:36:17 +00001353 if (!FinishSubobjectInit)
1354 return false;
1355
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001356 // We've already initialized something in the union; we're done.
1357 if (RT->getDecl()->isUnion())
1358 return hadError;
1359
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001360 // Check the remaining fields within this class/struct/union subobject.
1361 bool prevHadError = hadError;
Douglas Gregor4c678342009-01-28 21:54:33 +00001362 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1363 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001364 return hadError && !prevHadError;
1365 }
1366
1367 // C99 6.7.8p6:
1368 //
1369 // If a designator has the form
1370 //
1371 // [ constant-expression ]
1372 //
1373 // then the current object (defined below) shall have array
1374 // type and the expression shall be an integer constant
1375 // expression. If the array is of unknown size, any
1376 // nonnegative value is valid.
1377 //
1378 // Additionally, cope with the GNU extension that permits
1379 // designators of the form
1380 //
1381 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001382 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001383 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001384 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001385 << CurrentObjectType;
1386 ++Index;
1387 return true;
1388 }
1389
1390 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001391 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1392 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001393 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001394 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001395 DesignatedEndIndex = DesignatedStartIndex;
1396 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001397 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001398
Douglas Gregor34e79462009-01-28 23:36:17 +00001399
Chris Lattner3bf68932009-04-25 21:59:05 +00001400 DesignatedStartIndex =
1401 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
1402 DesignatedEndIndex =
1403 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001404 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001405
Chris Lattner3bf68932009-04-25 21:59:05 +00001406 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001407 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001408 }
1409
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001410 if (isa<ConstantArrayType>(AT)) {
1411 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001412 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1413 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1414 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1415 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1416 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001417 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001418 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001419 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001420 << IndexExpr->getSourceRange();
1421 ++Index;
1422 return true;
1423 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001424 } else {
1425 // Make sure the bit-widths and signedness match.
1426 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1427 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001428 else if (DesignatedStartIndex.getBitWidth() <
1429 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001430 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1431 DesignatedStartIndex.setIsUnsigned(true);
1432 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001433 }
1434
Douglas Gregor4c678342009-01-28 21:54:33 +00001435 // Make sure that our non-designated initializer list has space
1436 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001437 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001438 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001439 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001440
Douglas Gregor34e79462009-01-28 23:36:17 +00001441 // Repeatedly perform subobject initializations in the range
1442 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001443
Douglas Gregor34e79462009-01-28 23:36:17 +00001444 // Move to the next designator
1445 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1446 unsigned OldIndex = Index;
Douglas Gregor34e79462009-01-28 23:36:17 +00001447 while (DesignatedStartIndex <= DesignatedEndIndex) {
1448 // Recurse to check later designated subobjects.
1449 QualType ElementType = AT->getElementType();
1450 Index = OldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001451 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1452 Index, StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001453 (DesignatedStartIndex == DesignatedEndIndex),
1454 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001455 return true;
1456
1457 // Move to the next index in the array that we'll be initializing.
1458 ++DesignatedStartIndex;
1459 ElementIndex = DesignatedStartIndex.getZExtValue();
1460 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001461
1462 // If this the first designator, our caller will continue checking
1463 // the rest of this array subobject.
1464 if (IsFirstDesignator) {
1465 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001466 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001467 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001468 return false;
1469 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001470
1471 if (!FinishSubobjectInit)
1472 return false;
1473
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001474 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001475 bool prevHadError = hadError;
Douglas Gregorfdf55692009-02-09 19:45:19 +00001476 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001477 StructuredList, ElementIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001478 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001479}
1480
Douglas Gregor4c678342009-01-28 21:54:33 +00001481// Get the structured initializer list for a subobject of type
1482// @p CurrentObjectType.
1483InitListExpr *
1484InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1485 QualType CurrentObjectType,
1486 InitListExpr *StructuredList,
1487 unsigned StructuredIndex,
1488 SourceRange InitRange) {
1489 Expr *ExistingInit = 0;
1490 if (!StructuredList)
1491 ExistingInit = SyntacticToSemantic[IList];
1492 else if (StructuredIndex < StructuredList->getNumInits())
1493 ExistingInit = StructuredList->getInit(StructuredIndex);
1494
1495 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1496 return Result;
1497
1498 if (ExistingInit) {
1499 // We are creating an initializer list that initializes the
1500 // subobjects of the current object, but there was already an
1501 // initialization that completely initialized the current
1502 // subobject, e.g., by a compound literal:
1503 //
1504 // struct X { int a, b; };
1505 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1506 //
1507 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1508 // designated initializer re-initializes the whole
1509 // subobject [0], overwriting previous initializers.
Douglas Gregored8a93d2009-03-01 17:12:46 +00001510 SemaRef.Diag(InitRange.getBegin(),
1511 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001512 << InitRange;
Chris Lattner08202542009-02-24 22:50:46 +00001513 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001514 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001515 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001516 << ExistingInit->getSourceRange();
1517 }
1518
1519 InitListExpr *Result
Douglas Gregored8a93d2009-03-01 17:12:46 +00001520 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
1521 InitRange.getEnd());
1522
Douglas Gregor4c678342009-01-28 21:54:33 +00001523 Result->setType(CurrentObjectType);
1524
Douglas Gregorfa219202009-03-20 23:58:33 +00001525 // Pre-allocate storage for the structured initializer list.
1526 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001527 unsigned NumInits = 0;
1528 if (!StructuredList)
1529 NumInits = IList->getNumInits();
1530 else if (Index < IList->getNumInits()) {
1531 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1532 NumInits = SubList->getNumInits();
1533 }
1534
Douglas Gregorfa219202009-03-20 23:58:33 +00001535 if (const ArrayType *AType
1536 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1537 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1538 NumElements = CAType->getSize().getZExtValue();
1539 // Simple heuristic so that we don't allocate a very large
1540 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001541 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001542 NumElements = 0;
1543 }
1544 } else if (const VectorType *VType = CurrentObjectType->getAsVectorType())
1545 NumElements = VType->getNumElements();
1546 else if (const RecordType *RType = CurrentObjectType->getAsRecordType()) {
1547 RecordDecl *RDecl = RType->getDecl();
1548 if (RDecl->isUnion())
1549 NumElements = 1;
1550 else
Douglas Gregor6ab35242009-04-09 21:40:53 +00001551 NumElements = std::distance(RDecl->field_begin(SemaRef.Context),
1552 RDecl->field_end(SemaRef.Context));
Douglas Gregorfa219202009-03-20 23:58:33 +00001553 }
1554
Douglas Gregor08457732009-03-21 18:13:52 +00001555 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001556 NumElements = IList->getNumInits();
1557
1558 Result->reserveInits(NumElements);
1559
Douglas Gregor4c678342009-01-28 21:54:33 +00001560 // Link this new initializer list into the structured initializer
1561 // lists.
1562 if (StructuredList)
1563 StructuredList->updateInit(StructuredIndex, Result);
1564 else {
1565 Result->setSyntacticForm(IList);
1566 SyntacticToSemantic[IList] = Result;
1567 }
1568
1569 return Result;
1570}
1571
1572/// Update the initializer at index @p StructuredIndex within the
1573/// structured initializer list to the value @p expr.
1574void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1575 unsigned &StructuredIndex,
1576 Expr *expr) {
1577 // No structured initializer list to update
1578 if (!StructuredList)
1579 return;
1580
1581 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1582 // This initializer overwrites a previous initializer. Warn.
Chris Lattner08202542009-02-24 22:50:46 +00001583 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001584 diag::warn_initializer_overrides)
1585 << expr->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001586 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001587 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001588 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001589 << PrevInit->getSourceRange();
1590 }
1591
1592 ++StructuredIndex;
1593}
1594
Douglas Gregor05c13a32009-01-22 00:58:24 +00001595/// Check that the given Index expression is a valid array designator
1596/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001597/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001598/// and produces a reasonable diagnostic if there is a
1599/// failure. Returns true if there was an error, false otherwise. If
1600/// everything went okay, Value will receive the value of the constant
1601/// expression.
1602static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001603CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001604 SourceLocation Loc = Index->getSourceRange().getBegin();
1605
1606 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001607 if (S.VerifyIntegerConstantExpression(Index, &Value))
1608 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001609
Chris Lattner3bf68932009-04-25 21:59:05 +00001610 if (Value.isSigned() && Value.isNegative())
1611 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001612 << Value.toString(10) << Index->getSourceRange();
1613
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001614 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001615 return false;
1616}
1617
1618Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1619 SourceLocation Loc,
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001620 bool GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001621 OwningExprResult Init) {
1622 typedef DesignatedInitExpr::Designator ASTDesignator;
1623
1624 bool Invalid = false;
1625 llvm::SmallVector<ASTDesignator, 32> Designators;
1626 llvm::SmallVector<Expr *, 32> InitExpressions;
1627
1628 // Build designators and check array designator expressions.
1629 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1630 const Designator &D = Desig.getDesignator(Idx);
1631 switch (D.getKind()) {
1632 case Designator::FieldDesignator:
1633 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1634 D.getFieldLoc()));
1635 break;
1636
1637 case Designator::ArrayDesignator: {
1638 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1639 llvm::APSInt IndexValue;
1640 if (CheckArrayDesignatorExpr(*this, Index, IndexValue))
1641 Invalid = true;
1642 else {
1643 Designators.push_back(ASTDesignator(InitExpressions.size(),
1644 D.getLBracketLoc(),
1645 D.getRBracketLoc()));
1646 InitExpressions.push_back(Index);
1647 }
1648 break;
1649 }
1650
1651 case Designator::ArrayRangeDesignator: {
1652 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1653 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1654 llvm::APSInt StartValue;
1655 llvm::APSInt EndValue;
1656 if (CheckArrayDesignatorExpr(*this, StartIndex, StartValue) ||
1657 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))
1658 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001659 else {
1660 // Make sure we're comparing values with the same bit width.
1661 if (StartValue.getBitWidth() > EndValue.getBitWidth())
1662 EndValue.extend(StartValue.getBitWidth());
1663 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1664 StartValue.extend(EndValue.getBitWidth());
1665
1666 if (EndValue < StartValue) {
1667 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1668 << StartValue.toString(10) << EndValue.toString(10)
1669 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1670 Invalid = true;
1671 } else {
1672 Designators.push_back(ASTDesignator(InitExpressions.size(),
1673 D.getLBracketLoc(),
1674 D.getEllipsisLoc(),
1675 D.getRBracketLoc()));
1676 InitExpressions.push_back(StartIndex);
1677 InitExpressions.push_back(EndIndex);
1678 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001679 }
1680 break;
1681 }
1682 }
1683 }
1684
1685 if (Invalid || Init.isInvalid())
1686 return ExprError();
1687
1688 // Clear out the expressions within the designation.
1689 Desig.ClearExprs(*this);
1690
1691 DesignatedInitExpr *DIE
1692 = DesignatedInitExpr::Create(Context, &Designators[0], Designators.size(),
1693 &InitExpressions[0], InitExpressions.size(),
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001694 Loc, GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001695 static_cast<Expr *>(Init.release()));
1696 return Owned(DIE);
1697}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001698
1699bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
Chris Lattner08202542009-02-24 22:50:46 +00001700 InitListChecker CheckInitList(*this, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001701 if (!CheckInitList.HadError())
1702 InitList = CheckInitList.getFullyStructuredList();
1703
1704 return CheckInitList.HadError();
1705}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001706
1707/// \brief Diagnose any semantic errors with value-initialization of
1708/// the given type.
1709///
1710/// Value-initialization effectively zero-initializes any types
1711/// without user-declared constructors, and calls the default
1712/// constructor for a for any type that has a user-declared
1713/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1714/// a type with a user-declared constructor does not have an
1715/// accessible, non-deleted default constructor. In C, everything can
1716/// be value-initialized, which corresponds to C's notion of
1717/// initializing objects with static storage duration when no
1718/// initializer is provided for that object.
1719///
1720/// \returns true if there was an error, false otherwise.
1721bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1722 // C++ [dcl.init]p5:
1723 //
1724 // To value-initialize an object of type T means:
1725
1726 // -- if T is an array type, then each element is value-initialized;
1727 if (const ArrayType *AT = Context.getAsArrayType(Type))
1728 return CheckValueInitialization(AT->getElementType(), Loc);
1729
1730 if (const RecordType *RT = Type->getAsRecordType()) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001731 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Douglas Gregor87fd7032009-02-02 17:43:21 +00001732 // -- if T is a class type (clause 9) with a user-declared
1733 // constructor (12.1), then the default constructor for T is
1734 // called (and the initialization is ill-formed if T has no
1735 // accessible default constructor);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001736 if (ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor87fd7032009-02-02 17:43:21 +00001737 // FIXME: Eventually, we'll need to put the constructor decl
1738 // into the AST.
1739 return PerformInitializationByConstructor(Type, 0, 0, Loc,
1740 SourceRange(Loc),
1741 DeclarationName(),
1742 IK_Direct);
1743 }
1744 }
1745
1746 if (Type->isReferenceType()) {
1747 // C++ [dcl.init]p5:
1748 // [...] A program that calls for default-initialization or
1749 // value-initialization of an entity of reference type is
1750 // ill-formed. [...]
Douglas Gregord8635172009-02-02 21:35:47 +00001751 // FIXME: Once we have code that goes through this path, add an
1752 // actual diagnostic :)
Douglas Gregor87fd7032009-02-02 17:43:21 +00001753 }
1754
1755 return false;
1756}