blob: fbf3ae2a78525686ebafaf667a4396c1391439e0 [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,
284 DesignatedInitExpr::designators_iterator D,
285 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();
327 for (RecordDecl::field_iterator Field = RType->getDecl()->field_begin(),
328 FieldEnd = RType->getDecl()->field_end();
329 Field != FieldEnd; ++Field) {
330 if (Field->isUnnamedBitfield())
331 continue;
332
Douglas Gregor87fd7032009-02-02 17:43:21 +0000333 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000334 if (Field->getType()->isReferenceType()) {
335 // C++ [dcl.init.aggr]p9:
336 // If an incomplete or empty initializer-list leaves a
337 // member of reference type uninitialized, the program is
338 // ill-formed.
Chris Lattner08202542009-02-24 22:50:46 +0000339 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000340 << Field->getType()
341 << ILE->getSyntacticForm()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +0000342 SemaRef.Diag(Field->getLocation(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000343 diag::note_uninit_reference_member);
344 hadError = true;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000345 return;
Chris Lattner08202542009-02-24 22:50:46 +0000346 } else if (SemaRef.CheckValueInitialization(Field->getType(), Loc)) {
Douglas Gregor87fd7032009-02-02 17:43:21 +0000347 hadError = true;
348 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000349 }
Douglas Gregor87fd7032009-02-02 17:43:21 +0000350
351 // FIXME: If value-initialization involves calling a
352 // constructor, should we make that call explicit in the
353 // representation (even when it means extending the
354 // initializer list)?
355 if (Init < NumInits && !hadError)
356 ILE->setInit(Init,
Chris Lattner08202542009-02-24 22:50:46 +0000357 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()));
Douglas Gregor87fd7032009-02-02 17:43:21 +0000358 } else if (InitListExpr *InnerILE
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000359 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000360 FillInValueInitializations(InnerILE);
Douglas Gregor4c678342009-01-28 21:54:33 +0000361 ++Init;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000362
363 // Only look at the first initialization of a union.
364 if (RType->getDecl()->isUnion())
365 break;
Douglas Gregor4c678342009-01-28 21:54:33 +0000366 }
367
368 return;
369 }
370
371 QualType ElementType;
372
Douglas Gregor87fd7032009-02-02 17:43:21 +0000373 unsigned NumInits = ILE->getNumInits();
374 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000375 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000376 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000377 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
378 NumElements = CAType->getSize().getZExtValue();
379 } else if (const VectorType *VType = ILE->getType()->getAsVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000380 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000381 NumElements = VType->getNumElements();
382 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000383 ElementType = ILE->getType();
384
Douglas Gregor87fd7032009-02-02 17:43:21 +0000385 for (unsigned Init = 0; Init != NumElements; ++Init) {
386 if (Init >= NumInits || !ILE->getInit(Init)) {
Chris Lattner08202542009-02-24 22:50:46 +0000387 if (SemaRef.CheckValueInitialization(ElementType, Loc)) {
Douglas Gregor87fd7032009-02-02 17:43:21 +0000388 hadError = true;
389 return;
390 }
391
392 // FIXME: If value-initialization involves calling a
393 // constructor, should we make that call explicit in the
394 // representation (even when it means extending the
395 // initializer list)?
396 if (Init < NumInits && !hadError)
397 ILE->setInit(Init,
Chris Lattner08202542009-02-24 22:50:46 +0000398 new (SemaRef.Context) ImplicitValueInitExpr(ElementType));
Douglas Gregor87fd7032009-02-02 17:43:21 +0000399 }
Chris Lattner68355a52009-01-29 05:10:57 +0000400 else if (InitListExpr *InnerILE =dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000401 FillInValueInitializations(InnerILE);
Douglas Gregor4c678342009-01-28 21:54:33 +0000402 }
403}
404
Chris Lattner68355a52009-01-29 05:10:57 +0000405
Chris Lattner08202542009-02-24 22:50:46 +0000406InitListChecker::InitListChecker(Sema &S, InitListExpr *IL, QualType &T)
407 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000408 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000409
Eli Friedmanb85f7072008-05-19 19:16:24 +0000410 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000411 unsigned newStructuredIndex = 0;
412 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000413 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000414 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
415 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000416
Douglas Gregor930d8b52009-01-30 22:09:00 +0000417 if (!hadError)
418 FillInValueInitializations(FullyStructuredList);
Steve Naroff0cca7492008-05-01 22:18:59 +0000419}
420
421int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000422 // FIXME: use a proper constant
423 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000424 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000425 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000426 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
427 }
428 return maxElements;
429}
430
431int InitListChecker::numStructUnionElements(QualType DeclType) {
432 RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000433 int InitializableMembers = 0;
434 for (RecordDecl::field_iterator Field = structDecl->field_begin(),
435 FieldEnd = structDecl->field_end();
436 Field != FieldEnd; ++Field) {
437 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
438 ++InitializableMembers;
439 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000440 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000441 return std::min(InitializableMembers, 1);
442 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000443}
444
445void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000446 QualType T, unsigned &Index,
447 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000448 unsigned &StructuredIndex,
449 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000450 int maxElements = 0;
451
452 if (T->isArrayType())
453 maxElements = numArrayElements(T);
454 else if (T->isStructureType() || T->isUnionType())
455 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000456 else if (T->isVectorType())
457 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000458 else
459 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000460
Eli Friedman402256f2008-05-25 13:49:22 +0000461 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000462 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000463 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000464 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000465 hadError = true;
466 return;
467 }
468
Douglas Gregor4c678342009-01-28 21:54:33 +0000469 // Build a structured initializer list corresponding to this subobject.
470 InitListExpr *StructuredSubobjectInitList
471 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
472 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000473 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
474 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000475 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000476
Douglas Gregor4c678342009-01-28 21:54:33 +0000477 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000478 unsigned StartIndex = Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000479 CheckListElementTypes(ParentIList, T, false, Index,
480 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000481 StructuredSubobjectInitIndex,
482 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000483 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000484 StructuredSubobjectInitList->setType(T);
485
Douglas Gregored8a93d2009-03-01 17:12:46 +0000486 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000487 // range corresponds with the end of the last initializer it used.
488 if (EndIndex < ParentIList->getNumInits()) {
489 SourceLocation EndLoc
490 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
491 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
492 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000493}
494
Steve Naroffa647caa2008-05-06 00:23:44 +0000495void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000496 unsigned &Index,
497 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000498 unsigned &StructuredIndex,
499 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000500 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000501 SyntacticToSemantic[IList] = StructuredList;
502 StructuredList->setSyntacticForm(IList);
503 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000504 StructuredIndex, TopLevelObject);
Steve Naroffa647caa2008-05-06 00:23:44 +0000505 IList->setType(T);
Douglas Gregor4c678342009-01-28 21:54:33 +0000506 StructuredList->setType(T);
Eli Friedman638e1442008-05-25 13:22:35 +0000507 if (hadError)
508 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000509
Eli Friedman638e1442008-05-25 13:22:35 +0000510 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000511 // We have leftover initializers
512 if (IList->getNumInits() > 0 &&
Chris Lattner08202542009-02-24 22:50:46 +0000513 IsStringInit(IList->getInit(Index), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000514 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Chris Lattner08202542009-02-24 22:50:46 +0000515 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000516 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000517 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000518 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000519 << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000520 hadError = true;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000521 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000522 // Don't complain for incomplete types, since we'll get an error
523 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000524 QualType CurrentObjectType = StructuredList->getType();
525 int initKind =
526 CurrentObjectType->isArrayType()? 0 :
527 CurrentObjectType->isVectorType()? 1 :
528 CurrentObjectType->isScalarType()? 2 :
529 CurrentObjectType->isUnionType()? 3 :
530 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000531
532 unsigned DK = diag::warn_excess_initializers;
Chris Lattner08202542009-02-24 22:50:46 +0000533 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000534 DK = diag::err_excess_initializers;
535
Chris Lattner08202542009-02-24 22:50:46 +0000536 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000537 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000538 }
539 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000540
Eli Friedman638e1442008-05-25 13:22:35 +0000541 if (T->isScalarType())
Chris Lattner08202542009-02-24 22:50:46 +0000542 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000543 << IList->getSourceRange();
Steve Naroff0cca7492008-05-01 22:18:59 +0000544}
545
Eli Friedmanb85f7072008-05-19 19:16:24 +0000546void InitListChecker::CheckListElementTypes(InitListExpr *IList,
547 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000548 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000549 unsigned &Index,
550 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000551 unsigned &StructuredIndex,
552 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000553 if (DeclType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000554 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000555 } else if (DeclType->isVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000556 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000557 } else if (DeclType->isAggregateType()) {
558 if (DeclType->isRecordType()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000559 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
560 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000561 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000562 StructuredList, StructuredIndex,
563 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000564 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000565 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000566 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000567 false);
Douglas Gregor4c678342009-01-28 21:54:33 +0000568 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
569 StructuredList, StructuredIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000570 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000571 else
Douglas Gregor4c678342009-01-28 21:54:33 +0000572 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000573 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
574 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000575 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000576 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000577 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000578 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000579 } else if (DeclType->isRecordType()) {
580 // C++ [dcl.init]p14:
581 // [...] If the class is an aggregate (8.5.1), and the initializer
582 // is a brace-enclosed list, see 8.5.1.
583 //
584 // Note: 8.5.1 is handled below; here, we diagnose the case where
585 // we have an initializer list and a destination type that is not
586 // an aggregate.
587 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000588 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000589 << DeclType << IList->getSourceRange();
590 hadError = true;
591 } else if (DeclType->isReferenceType()) {
592 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000593 } else {
594 // In C, all types are either scalars or aggregates, but
595 // additional handling is needed here for C++ (and possibly others?).
596 assert(0 && "Unsupported initializer type");
597 }
598}
599
Eli Friedmanb85f7072008-05-19 19:16:24 +0000600void InitListChecker::CheckSubElementType(InitListExpr *IList,
601 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000602 unsigned &Index,
603 InitListExpr *StructuredList,
604 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000605 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000606 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
607 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000608 unsigned newStructuredIndex = 0;
609 InitListExpr *newStructuredList
610 = getStructuredSubobjectInit(IList, Index, ElemType,
611 StructuredList, StructuredIndex,
612 SubInitList->getSourceRange());
613 CheckExplicitInitList(SubInitList, ElemType, newIndex,
614 newStructuredList, newStructuredIndex);
615 ++StructuredIndex;
616 ++Index;
Chris Lattner79e079d2009-02-24 23:10:27 +0000617 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
618 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000619 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000620 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000621 } else if (ElemType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000622 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000623 } else if (ElemType->isReferenceType()) {
624 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000625 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000626 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000627 // C++ [dcl.init.aggr]p12:
628 // All implicit type conversions (clause 4) are considered when
629 // initializing the aggregate member with an ini- tializer from
630 // an initializer-list. If the initializer can initialize a
631 // member, the member is initialized. [...]
632 ImplicitConversionSequence ICS
Chris Lattner08202542009-02-24 22:50:46 +0000633 = SemaRef.TryCopyInitialization(expr, ElemType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000634 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Chris Lattner08202542009-02-24 22:50:46 +0000635 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000636 "initializing"))
637 hadError = true;
638 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
639 ++Index;
640 return;
641 }
642
643 // Fall through for subaggregate initialization
644 } else {
645 // C99 6.7.8p13:
646 //
647 // The initializer for a structure or union object that has
648 // automatic storage duration shall be either an initializer
649 // list as described below, or a single expression that has
650 // compatible structure or union type. In the latter case, the
651 // initial value of the object, including unnamed members, is
652 // that of the expression.
Chris Lattner08202542009-02-24 22:50:46 +0000653 QualType ExprType = SemaRef.Context.getCanonicalType(expr->getType());
654 QualType ElemTypeCanon = SemaRef.Context.getCanonicalType(ElemType);
655 if (SemaRef.Context.typesAreCompatible(ExprType.getUnqualifiedType(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000656 ElemTypeCanon.getUnqualifiedType())) {
657 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
658 ++Index;
659 return;
660 }
661
662 // Fall through for subaggregate initialization
663 }
664
665 // C++ [dcl.init.aggr]p12:
666 //
667 // [...] Otherwise, if the member is itself a non-empty
668 // subaggregate, brace elision is assumed and the initializer is
669 // considered for the initialization of the first member of
670 // the subaggregate.
671 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
672 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
673 StructuredIndex);
674 ++StructuredIndex;
675 } else {
676 // We cannot initialize this element, so let
677 // PerformCopyInitialization produce the appropriate diagnostic.
Chris Lattner08202542009-02-24 22:50:46 +0000678 SemaRef.PerformCopyInitialization(expr, ElemType, "initializing");
Douglas Gregor930d8b52009-01-30 22:09:00 +0000679 hadError = true;
680 ++Index;
681 ++StructuredIndex;
682 }
683 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000684}
685
Douglas Gregor930d8b52009-01-30 22:09:00 +0000686void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000687 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000688 InitListExpr *StructuredList,
689 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000690 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000691 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000692 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000693 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000694 diag::err_many_braces_around_scalar_init)
695 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000696 hadError = true;
697 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000698 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000699 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000700 } else if (isa<DesignatedInitExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000701 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor05c13a32009-01-22 00:58:24 +0000702 diag::err_designator_for_scalar_init)
703 << DeclType << expr->getSourceRange();
704 hadError = true;
705 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000706 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000707 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000708 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000709
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000710 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner08202542009-02-24 22:50:46 +0000711 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedmanbb504d32008-05-19 20:12:18 +0000712 hadError = true; // types weren't compatible.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000713 else if (savExpr != expr) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000714 // The type was promoted, update initializer list.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000715 IList->setInit(Index, expr);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000716 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000717 if (hadError)
718 ++StructuredIndex;
719 else
720 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000721 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000722 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000723 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000724 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000725 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000726 ++Index;
727 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000728 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000729 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000730}
731
Douglas Gregor930d8b52009-01-30 22:09:00 +0000732void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
733 unsigned &Index,
734 InitListExpr *StructuredList,
735 unsigned &StructuredIndex) {
736 if (Index < IList->getNumInits()) {
737 Expr *expr = IList->getInit(Index);
738 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000739 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000740 << DeclType << IList->getSourceRange();
741 hadError = true;
742 ++Index;
743 ++StructuredIndex;
744 return;
745 }
746
747 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner08202542009-02-24 22:50:46 +0000748 if (SemaRef.CheckReferenceInit(expr, DeclType))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000749 hadError = true;
750 else if (savExpr != expr) {
751 // The type was promoted, update initializer list.
752 IList->setInit(Index, expr);
753 }
754 if (hadError)
755 ++StructuredIndex;
756 else
757 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
758 ++Index;
759 } else {
760 // FIXME: It would be wonderful if we could point at the actual
761 // member. In general, it would be useful to pass location
762 // information down the stack, so that we know the location (or
763 // decl) of the "current object" being initialized.
Chris Lattner08202542009-02-24 22:50:46 +0000764 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000765 diag::err_init_reference_member_uninitialized)
766 << DeclType
767 << IList->getSourceRange();
768 hadError = true;
769 ++Index;
770 ++StructuredIndex;
771 return;
772 }
773}
774
Steve Naroff0cca7492008-05-01 22:18:59 +0000775void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000776 unsigned &Index,
777 InitListExpr *StructuredList,
778 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000779 if (Index < IList->getNumInits()) {
780 const VectorType *VT = DeclType->getAsVectorType();
781 int maxElements = VT->getNumElements();
782 QualType elementType = VT->getElementType();
783
784 for (int i = 0; i < maxElements; ++i) {
785 // Don't attempt to go past the end of the init list
786 if (Index >= IList->getNumInits())
787 break;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000788 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000789 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000790 }
791 }
792}
793
794void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000795 llvm::APSInt elementIndex,
796 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000797 unsigned &Index,
798 InitListExpr *StructuredList,
799 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000800 // Check for the special-case of initializing an array with a string.
801 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000802 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
803 SemaRef.Context)) {
804 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +0000805 // We place the string literal directly into the resulting
806 // initializer list. This is the only place where the structure
807 // of the structured initializer list doesn't match exactly,
808 // because doing so would involve allocating one character
809 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000810 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +0000811 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000812 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000813 return;
814 }
815 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000816 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +0000817 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000818 // Check for VLAs; in standard C it would be possible to check this
819 // earlier, but I don't know where clang accepts VLAs (gcc accepts
820 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +0000821 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000822 diag::err_variable_object_no_init)
823 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000824 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000825 ++Index;
826 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000827 return;
828 }
829
Douglas Gregor05c13a32009-01-22 00:58:24 +0000830 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000831 llvm::APSInt maxElements(elementIndex.getBitWidth(),
832 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000833 bool maxElementsKnown = false;
834 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000835 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000836 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000837 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000838 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000839 maxElementsKnown = true;
840 }
841
Chris Lattner08202542009-02-24 22:50:46 +0000842 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000843 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000844 while (Index < IList->getNumInits()) {
845 Expr *Init = IList->getInit(Index);
846 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000847 // If we're not the subobject that matches up with the '{' for
848 // the designator, we shouldn't be handling the
849 // designator. Return immediately.
850 if (!SubobjectIsDesignatorContext)
851 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000852
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000853 // Handle this designated initializer. elementIndex will be
854 // updated to be the next array element we'll initialize.
855 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000856 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000857 StructuredList, StructuredIndex, true,
858 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000859 hadError = true;
860 continue;
861 }
862
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000863 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
864 maxElements.extend(elementIndex.getBitWidth());
865 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
866 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000867 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000868
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000869 // If the array is of incomplete type, keep track of the number of
870 // elements in the initializer.
871 if (!maxElementsKnown && elementIndex > maxElements)
872 maxElements = elementIndex;
873
Douglas Gregor05c13a32009-01-22 00:58:24 +0000874 continue;
875 }
876
877 // If we know the maximum number of elements, and we've already
878 // hit it, stop consuming elements in the initializer list.
879 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +0000880 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000881
882 // Check this element.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000883 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000884 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000885 ++elementIndex;
886
887 // If the array is of incomplete type, keep track of the number of
888 // elements in the initializer.
889 if (!maxElementsKnown && elementIndex > maxElements)
890 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +0000891 }
892 if (DeclType->isIncompleteArrayType()) {
893 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000894 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000895 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000896 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000897 // Sizing an array implicitly to zero is not allowed by ISO C,
898 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +0000899 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000900 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +0000901 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000902
Chris Lattner08202542009-02-24 22:50:46 +0000903 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000904 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +0000905 }
906}
907
908void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
909 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000910 RecordDecl::field_iterator Field,
911 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000912 unsigned &Index,
913 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000914 unsigned &StructuredIndex,
915 bool TopLevelObject) {
Eli Friedmanb85f7072008-05-19 19:16:24 +0000916 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroff0cca7492008-05-01 22:18:59 +0000917
Eli Friedmanb85f7072008-05-19 19:16:24 +0000918 // If the record is invalid, some of it's members are invalid. To avoid
919 // confusion, we forgo checking the intializer for the entire record.
920 if (structDecl->isInvalidDecl()) {
921 hadError = true;
922 return;
923 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000924
925 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
926 // Value-initialize the first named member of the union.
927 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
928 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
929 Field != FieldEnd; ++Field) {
930 if (Field->getDeclName()) {
931 StructuredList->setInitializedFieldInUnion(*Field);
932 break;
933 }
934 }
935 return;
936 }
937
Douglas Gregor05c13a32009-01-22 00:58:24 +0000938 // If structDecl is a forward declaration, this loop won't do
939 // anything except look at designated initializers; That's okay,
940 // because an error should get printed out elsewhere. It might be
941 // worthwhile to skip over the rest of the initializer, though.
Douglas Gregor44b43212008-12-11 16:49:14 +0000942 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000943 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +0000944 bool InitializedSomething = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000945 while (Index < IList->getNumInits()) {
946 Expr *Init = IList->getInit(Index);
947
948 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000949 // If we're not the subobject that matches up with the '{' for
950 // the designator, we shouldn't be handling the
951 // designator. Return immediately.
952 if (!SubobjectIsDesignatorContext)
953 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000954
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000955 // Handle this designated initializer. Field will be updated to
956 // the next field that we'll be initializing.
957 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000958 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000959 StructuredList, StructuredIndex,
960 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000961 hadError = true;
962
Douglas Gregordfb5e592009-02-12 19:00:39 +0000963 InitializedSomething = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000964 continue;
965 }
966
967 if (Field == FieldEnd) {
968 // We've run out of fields. We're done.
969 break;
970 }
971
Douglas Gregordfb5e592009-02-12 19:00:39 +0000972 // We've already initialized a member of a union. We're done.
973 if (InitializedSomething && DeclType->isUnionType())
974 break;
975
Douglas Gregor44b43212008-12-11 16:49:14 +0000976 // If we've hit the flexible array member at the end, we're done.
977 if (Field->getType()->isIncompleteArrayType())
978 break;
979
Douglas Gregor0bb76892009-01-29 16:53:55 +0000980 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000981 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +0000982 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000983 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +0000984 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000985
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000986 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000987 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +0000988 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +0000989
990 if (DeclType->isUnionType()) {
991 // Initialize the first field within the union.
992 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +0000993 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000994
995 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +0000996 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000997
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000998 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +0000999 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001000 return;
1001
1002 // Handle GNU flexible array initializers.
1003 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001004 (!isa<InitListExpr>(IList->getInit(Index)) ||
1005 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Chris Lattner08202542009-02-24 22:50:46 +00001006 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001007 diag::err_flexible_array_init_nonempty)
1008 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001009 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001010 << *Field;
1011 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001012 ++Index;
1013 return;
1014 } else {
1015 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
1016 diag::ext_flexible_array_init)
1017 << IList->getInit(Index)->getSourceRange().getBegin();
1018 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1019 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001020 }
1021
Douglas Gregora6457962009-03-20 00:32:56 +00001022 if (isa<InitListExpr>(IList->getInit(Index)))
1023 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1024 StructuredIndex);
1025 else
1026 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1027 StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001028}
Steve Naroff0cca7492008-05-01 22:18:59 +00001029
Douglas Gregor05c13a32009-01-22 00:58:24 +00001030/// @brief Check the well-formedness of a C99 designated initializer.
1031///
1032/// Determines whether the designated initializer @p DIE, which
1033/// resides at the given @p Index within the initializer list @p
1034/// IList, is well-formed for a current object of type @p DeclType
1035/// (C99 6.7.8). The actual subobject that this designator refers to
1036/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001037/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001038///
1039/// @param IList The initializer list in which this designated
1040/// initializer occurs.
1041///
1042/// @param DIE The designated initializer and its initialization
1043/// expression.
1044///
1045/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1046/// into which the designation in @p DIE should refer.
1047///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001048/// @param NextField If non-NULL and the first designator in @p DIE is
1049/// a field, this will be set to the field declaration corresponding
1050/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001051///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001052/// @param NextElementIndex If non-NULL and the first designator in @p
1053/// DIE is an array designator or GNU array-range designator, this
1054/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001055///
1056/// @param Index Index into @p IList where the designated initializer
1057/// @p DIE occurs.
1058///
Douglas Gregor4c678342009-01-28 21:54:33 +00001059/// @param StructuredList The initializer list expression that
1060/// describes all of the subobject initializers in the order they'll
1061/// actually be initialized.
1062///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001063/// @returns true if there was an error, false otherwise.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001064bool
1065InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
1066 DesignatedInitExpr *DIE,
Chris Lattner19da8cd2009-02-24 23:01:39 +00001067 DesignatedInitExpr::designators_iterator D,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001068 QualType &CurrentObjectType,
1069 RecordDecl::field_iterator *NextField,
1070 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001071 unsigned &Index,
1072 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001073 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001074 bool FinishSubobjectInit,
1075 bool TopLevelObject) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001076 if (D == DIE->designators_end()) {
1077 // Check the actual initialization for the designated object type.
1078 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001079
1080 // Temporarily remove the designator expression from the
1081 // initializer list that the child calls see, so that we don't try
1082 // to re-process the designator.
1083 unsigned OldIndex = Index;
1084 IList->setInit(OldIndex, DIE->getInit());
1085
1086 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001087 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001088
1089 // Restore the designated initializer expression in the syntactic
1090 // form of the initializer list.
1091 if (IList->getInit(OldIndex) != DIE->getInit())
1092 DIE->setInit(IList->getInit(OldIndex));
1093 IList->setInit(OldIndex, DIE);
1094
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001095 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001096 }
1097
Douglas Gregor4c678342009-01-28 21:54:33 +00001098 bool IsFirstDesignator = (D == DIE->designators_begin());
1099 assert((IsFirstDesignator || StructuredList) &&
1100 "Need a non-designated initializer list to start from");
1101
1102 // Determine the structural initializer list that corresponds to the
1103 // current subobject.
1104 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Douglas Gregored8a93d2009-03-01 17:12:46 +00001105 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1106 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001107 SourceRange(D->getStartLocation(),
1108 DIE->getSourceRange().getEnd()));
1109 assert(StructuredList && "Expected a structured initializer list");
1110
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001111 if (D->isFieldDesignator()) {
1112 // C99 6.7.8p7:
1113 //
1114 // If a designator has the form
1115 //
1116 // . identifier
1117 //
1118 // then the current object (defined below) shall have
1119 // structure or union type and the identifier shall be the
1120 // name of a member of that type.
1121 const RecordType *RT = CurrentObjectType->getAsRecordType();
1122 if (!RT) {
1123 SourceLocation Loc = D->getDotLoc();
1124 if (Loc.isInvalid())
1125 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001126 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1127 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001128 ++Index;
1129 return true;
1130 }
1131
Douglas Gregor4c678342009-01-28 21:54:33 +00001132 // Note: we perform a linear search of the fields here, despite
1133 // the fact that we have a faster lookup method, because we always
1134 // need to compute the field's index.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001135 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001136 unsigned FieldIndex = 0;
1137 RecordDecl::field_iterator Field = RT->getDecl()->field_begin(),
1138 FieldEnd = RT->getDecl()->field_end();
1139 for (; Field != FieldEnd; ++Field) {
1140 if (Field->isUnnamedBitfield())
1141 continue;
1142
1143 if (Field->getIdentifier() == FieldName)
1144 break;
1145
1146 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001147 }
1148
Douglas Gregor4c678342009-01-28 21:54:33 +00001149 if (Field == FieldEnd) {
1150 // We did not find the field we're looking for. Produce a
1151 // suitable diagnostic and return a failure.
1152 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
1153 if (Lookup.first == Lookup.second) {
1154 // Name lookup didn't find anything.
Chris Lattner08202542009-02-24 22:50:46 +00001155 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregor4c678342009-01-28 21:54:33 +00001156 << FieldName << CurrentObjectType;
1157 } else {
1158 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001159 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001160 << FieldName;
Chris Lattner08202542009-02-24 22:50:46 +00001161 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001162 diag::note_field_designator_found);
1163 }
1164
1165 ++Index;
1166 return true;
1167 } else if (cast<RecordDecl>((*Field)->getDeclContext())
1168 ->isAnonymousStructOrUnion()) {
Chris Lattner08202542009-02-24 22:50:46 +00001169 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_anon_class)
Douglas Gregor4c678342009-01-28 21:54:33 +00001170 << FieldName
1171 << (cast<RecordDecl>((*Field)->getDeclContext())->isUnion()? 2 :
Chris Lattner08202542009-02-24 22:50:46 +00001172 (int)SemaRef.getLangOptions().CPlusPlus);
1173 SemaRef.Diag((*Field)->getLocation(), diag::note_field_designator_found);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001174 ++Index;
1175 return true;
1176 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001177
1178 // All of the fields of a union are located at the same place in
1179 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001180 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001181 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001182 StructuredList->setInitializedFieldInUnion(*Field);
1183 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001184
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001185 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001186 D->setField(*Field);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001187
Douglas Gregor4c678342009-01-28 21:54:33 +00001188 // Make sure that our non-designated initializer list has space
1189 // for a subobject corresponding to this field.
1190 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001191 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001192
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001193 // This designator names a flexible array member.
1194 if (Field->getType()->isIncompleteArrayType()) {
1195 bool Invalid = false;
1196 DesignatedInitExpr::designators_iterator NextD = D;
1197 ++NextD;
1198 if (NextD != DIE->designators_end()) {
1199 // We can't designate an object within the flexible array
1200 // member (because GCC doesn't allow it).
Chris Lattner08202542009-02-24 22:50:46 +00001201 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001202 diag::err_designator_into_flexible_array_member)
1203 << SourceRange(NextD->getStartLocation(),
1204 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001205 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001206 << *Field;
1207 Invalid = true;
1208 }
1209
1210 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1211 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001212 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001213 diag::err_flexible_array_init_needs_braces)
1214 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001215 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001216 << *Field;
1217 Invalid = true;
1218 }
1219
1220 // Handle GNU flexible array initializers.
1221 if (!Invalid && !TopLevelObject &&
1222 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Chris Lattner08202542009-02-24 22:50:46 +00001223 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001224 diag::err_flexible_array_init_nonempty)
1225 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001226 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001227 << *Field;
1228 Invalid = true;
1229 }
1230
1231 if (Invalid) {
1232 ++Index;
1233 return true;
1234 }
1235
1236 // Initialize the array.
1237 bool prevHadError = hadError;
1238 unsigned newStructuredIndex = FieldIndex;
1239 unsigned OldIndex = Index;
1240 IList->setInit(Index, DIE->getInit());
1241 CheckSubElementType(IList, Field->getType(), Index,
1242 StructuredList, newStructuredIndex);
1243 IList->setInit(OldIndex, DIE);
1244 if (hadError && !prevHadError) {
1245 ++Field;
1246 ++FieldIndex;
1247 if (NextField)
1248 *NextField = Field;
1249 StructuredIndex = FieldIndex;
1250 return true;
1251 }
1252 } else {
1253 // Recurse to check later designated subobjects.
1254 QualType FieldType = (*Field)->getType();
1255 unsigned newStructuredIndex = FieldIndex;
1256 if (CheckDesignatedInitializer(IList, DIE, ++D, FieldType, 0, 0, Index,
1257 StructuredList, newStructuredIndex,
1258 true, false))
1259 return true;
1260 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001261
1262 // Find the position of the next field to be initialized in this
1263 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001264 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001265 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001266
1267 // If this the first designator, our caller will continue checking
1268 // the rest of this struct/class/union subobject.
1269 if (IsFirstDesignator) {
1270 if (NextField)
1271 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001272 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001273 return false;
1274 }
1275
Douglas Gregor34e79462009-01-28 23:36:17 +00001276 if (!FinishSubobjectInit)
1277 return false;
1278
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001279 // Check the remaining fields within this class/struct/union subobject.
1280 bool prevHadError = hadError;
Douglas Gregor4c678342009-01-28 21:54:33 +00001281 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1282 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001283 return hadError && !prevHadError;
1284 }
1285
1286 // C99 6.7.8p6:
1287 //
1288 // If a designator has the form
1289 //
1290 // [ constant-expression ]
1291 //
1292 // then the current object (defined below) shall have array
1293 // type and the expression shall be an integer constant
1294 // expression. If the array is of unknown size, any
1295 // nonnegative value is valid.
1296 //
1297 // Additionally, cope with the GNU extension that permits
1298 // designators of the form
1299 //
1300 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001301 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001302 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001303 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001304 << CurrentObjectType;
1305 ++Index;
1306 return true;
1307 }
1308
1309 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001310 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1311 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001312 IndexExpr = DIE->getArrayIndex(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001313
1314 bool ConstExpr
Chris Lattner08202542009-02-24 22:50:46 +00001315 = IndexExpr->isIntegerConstantExpr(DesignatedStartIndex, SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001316 assert(ConstExpr && "Expression must be constant"); (void)ConstExpr;
1317
1318 DesignatedEndIndex = DesignatedStartIndex;
1319 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001320 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001321
1322 bool StartConstExpr
1323 = DIE->getArrayRangeStart(*D)->isIntegerConstantExpr(DesignatedStartIndex,
Chris Lattner08202542009-02-24 22:50:46 +00001324 SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001325 assert(StartConstExpr && "Expression must be constant"); (void)StartConstExpr;
1326
1327 bool EndConstExpr
1328 = DIE->getArrayRangeEnd(*D)->isIntegerConstantExpr(DesignatedEndIndex,
Chris Lattner08202542009-02-24 22:50:46 +00001329 SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001330 assert(EndConstExpr && "Expression must be constant"); (void)EndConstExpr;
1331
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001332 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001333
1334 if (DesignatedStartIndex.getZExtValue() != DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001335 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001336 }
1337
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001338 if (isa<ConstantArrayType>(AT)) {
1339 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001340 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1341 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1342 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1343 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1344 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001345 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001346 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001347 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001348 << IndexExpr->getSourceRange();
1349 ++Index;
1350 return true;
1351 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001352 } else {
1353 // Make sure the bit-widths and signedness match.
1354 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1355 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
1356 else if (DesignatedStartIndex.getBitWidth() < DesignatedEndIndex.getBitWidth())
1357 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1358 DesignatedStartIndex.setIsUnsigned(true);
1359 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001360 }
1361
Douglas Gregor4c678342009-01-28 21:54:33 +00001362 // Make sure that our non-designated initializer list has space
1363 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001364 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001365 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001366 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001367
Douglas Gregor34e79462009-01-28 23:36:17 +00001368 // Repeatedly perform subobject initializations in the range
1369 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001370
Douglas Gregor34e79462009-01-28 23:36:17 +00001371 // Move to the next designator
1372 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1373 unsigned OldIndex = Index;
1374 ++D;
1375 while (DesignatedStartIndex <= DesignatedEndIndex) {
1376 // Recurse to check later designated subobjects.
1377 QualType ElementType = AT->getElementType();
1378 Index = OldIndex;
1379 if (CheckDesignatedInitializer(IList, DIE, D, ElementType, 0, 0, Index,
1380 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001381 (DesignatedStartIndex == DesignatedEndIndex),
1382 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001383 return true;
1384
1385 // Move to the next index in the array that we'll be initializing.
1386 ++DesignatedStartIndex;
1387 ElementIndex = DesignatedStartIndex.getZExtValue();
1388 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001389
1390 // If this the first designator, our caller will continue checking
1391 // the rest of this array subobject.
1392 if (IsFirstDesignator) {
1393 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001394 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001395 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001396 return false;
1397 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001398
1399 if (!FinishSubobjectInit)
1400 return false;
1401
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001402 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001403 bool prevHadError = hadError;
Douglas Gregorfdf55692009-02-09 19:45:19 +00001404 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001405 StructuredList, ElementIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001406 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001407}
1408
Douglas Gregor4c678342009-01-28 21:54:33 +00001409// Get the structured initializer list for a subobject of type
1410// @p CurrentObjectType.
1411InitListExpr *
1412InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1413 QualType CurrentObjectType,
1414 InitListExpr *StructuredList,
1415 unsigned StructuredIndex,
1416 SourceRange InitRange) {
1417 Expr *ExistingInit = 0;
1418 if (!StructuredList)
1419 ExistingInit = SyntacticToSemantic[IList];
1420 else if (StructuredIndex < StructuredList->getNumInits())
1421 ExistingInit = StructuredList->getInit(StructuredIndex);
1422
1423 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1424 return Result;
1425
1426 if (ExistingInit) {
1427 // We are creating an initializer list that initializes the
1428 // subobjects of the current object, but there was already an
1429 // initialization that completely initialized the current
1430 // subobject, e.g., by a compound literal:
1431 //
1432 // struct X { int a, b; };
1433 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1434 //
1435 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1436 // designated initializer re-initializes the whole
1437 // subobject [0], overwriting previous initializers.
Douglas Gregored8a93d2009-03-01 17:12:46 +00001438 SemaRef.Diag(InitRange.getBegin(),
1439 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001440 << InitRange;
Chris Lattner08202542009-02-24 22:50:46 +00001441 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001442 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001443 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001444 << ExistingInit->getSourceRange();
1445 }
1446
1447 InitListExpr *Result
Douglas Gregored8a93d2009-03-01 17:12:46 +00001448 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
1449 InitRange.getEnd());
1450
Douglas Gregor4c678342009-01-28 21:54:33 +00001451 Result->setType(CurrentObjectType);
1452
Douglas Gregorfa219202009-03-20 23:58:33 +00001453 // Pre-allocate storage for the structured initializer list.
1454 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001455 unsigned NumInits = 0;
1456 if (!StructuredList)
1457 NumInits = IList->getNumInits();
1458 else if (Index < IList->getNumInits()) {
1459 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1460 NumInits = SubList->getNumInits();
1461 }
1462
Douglas Gregorfa219202009-03-20 23:58:33 +00001463 if (const ArrayType *AType
1464 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1465 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1466 NumElements = CAType->getSize().getZExtValue();
1467 // Simple heuristic so that we don't allocate a very large
1468 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001469 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001470 NumElements = 0;
1471 }
1472 } else if (const VectorType *VType = CurrentObjectType->getAsVectorType())
1473 NumElements = VType->getNumElements();
1474 else if (const RecordType *RType = CurrentObjectType->getAsRecordType()) {
1475 RecordDecl *RDecl = RType->getDecl();
1476 if (RDecl->isUnion())
1477 NumElements = 1;
1478 else
1479 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
1480 }
1481
Douglas Gregor08457732009-03-21 18:13:52 +00001482 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001483 NumElements = IList->getNumInits();
1484
1485 Result->reserveInits(NumElements);
1486
Douglas Gregor4c678342009-01-28 21:54:33 +00001487 // Link this new initializer list into the structured initializer
1488 // lists.
1489 if (StructuredList)
1490 StructuredList->updateInit(StructuredIndex, Result);
1491 else {
1492 Result->setSyntacticForm(IList);
1493 SyntacticToSemantic[IList] = Result;
1494 }
1495
1496 return Result;
1497}
1498
1499/// Update the initializer at index @p StructuredIndex within the
1500/// structured initializer list to the value @p expr.
1501void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1502 unsigned &StructuredIndex,
1503 Expr *expr) {
1504 // No structured initializer list to update
1505 if (!StructuredList)
1506 return;
1507
1508 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1509 // This initializer overwrites a previous initializer. Warn.
Chris Lattner08202542009-02-24 22:50:46 +00001510 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001511 diag::warn_initializer_overrides)
1512 << expr->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001513 SemaRef.Diag(PrevInit->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 << PrevInit->getSourceRange();
1517 }
1518
1519 ++StructuredIndex;
1520}
1521
Douglas Gregor05c13a32009-01-22 00:58:24 +00001522/// Check that the given Index expression is a valid array designator
1523/// value. This is essentailly just a wrapper around
1524/// Expr::isIntegerConstantExpr that also checks for negative values
1525/// and produces a reasonable diagnostic if there is a
1526/// failure. Returns true if there was an error, false otherwise. If
1527/// everything went okay, Value will receive the value of the constant
1528/// expression.
1529static bool
1530CheckArrayDesignatorExpr(Sema &Self, Expr *Index, llvm::APSInt &Value) {
1531 SourceLocation Loc = Index->getSourceRange().getBegin();
1532
1533 // Make sure this is an integer constant expression.
1534 if (!Index->isIntegerConstantExpr(Value, Self.Context, &Loc))
1535 return Self.Diag(Loc, diag::err_array_designator_nonconstant)
1536 << Index->getSourceRange();
1537
1538 // Make sure this constant expression is non-negative.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001539 llvm::APSInt Zero(llvm::APSInt::getNullValue(Value.getBitWidth()),
1540 Value.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001541 if (Value < Zero)
1542 return Self.Diag(Loc, diag::err_array_designator_negative)
1543 << Value.toString(10) << Index->getSourceRange();
1544
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001545 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001546 return false;
1547}
1548
1549Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1550 SourceLocation Loc,
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001551 bool GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001552 OwningExprResult Init) {
1553 typedef DesignatedInitExpr::Designator ASTDesignator;
1554
1555 bool Invalid = false;
1556 llvm::SmallVector<ASTDesignator, 32> Designators;
1557 llvm::SmallVector<Expr *, 32> InitExpressions;
1558
1559 // Build designators and check array designator expressions.
1560 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1561 const Designator &D = Desig.getDesignator(Idx);
1562 switch (D.getKind()) {
1563 case Designator::FieldDesignator:
1564 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1565 D.getFieldLoc()));
1566 break;
1567
1568 case Designator::ArrayDesignator: {
1569 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1570 llvm::APSInt IndexValue;
1571 if (CheckArrayDesignatorExpr(*this, Index, IndexValue))
1572 Invalid = true;
1573 else {
1574 Designators.push_back(ASTDesignator(InitExpressions.size(),
1575 D.getLBracketLoc(),
1576 D.getRBracketLoc()));
1577 InitExpressions.push_back(Index);
1578 }
1579 break;
1580 }
1581
1582 case Designator::ArrayRangeDesignator: {
1583 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1584 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1585 llvm::APSInt StartValue;
1586 llvm::APSInt EndValue;
1587 if (CheckArrayDesignatorExpr(*this, StartIndex, StartValue) ||
1588 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))
1589 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001590 else {
1591 // Make sure we're comparing values with the same bit width.
1592 if (StartValue.getBitWidth() > EndValue.getBitWidth())
1593 EndValue.extend(StartValue.getBitWidth());
1594 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1595 StartValue.extend(EndValue.getBitWidth());
1596
1597 if (EndValue < StartValue) {
1598 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1599 << StartValue.toString(10) << EndValue.toString(10)
1600 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1601 Invalid = true;
1602 } else {
1603 Designators.push_back(ASTDesignator(InitExpressions.size(),
1604 D.getLBracketLoc(),
1605 D.getEllipsisLoc(),
1606 D.getRBracketLoc()));
1607 InitExpressions.push_back(StartIndex);
1608 InitExpressions.push_back(EndIndex);
1609 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001610 }
1611 break;
1612 }
1613 }
1614 }
1615
1616 if (Invalid || Init.isInvalid())
1617 return ExprError();
1618
1619 // Clear out the expressions within the designation.
1620 Desig.ClearExprs(*this);
1621
1622 DesignatedInitExpr *DIE
1623 = DesignatedInitExpr::Create(Context, &Designators[0], Designators.size(),
1624 &InitExpressions[0], InitExpressions.size(),
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001625 Loc, GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001626 static_cast<Expr *>(Init.release()));
1627 return Owned(DIE);
1628}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001629
1630bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
Chris Lattner08202542009-02-24 22:50:46 +00001631 InitListChecker CheckInitList(*this, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001632 if (!CheckInitList.HadError())
1633 InitList = CheckInitList.getFullyStructuredList();
1634
1635 return CheckInitList.HadError();
1636}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001637
1638/// \brief Diagnose any semantic errors with value-initialization of
1639/// the given type.
1640///
1641/// Value-initialization effectively zero-initializes any types
1642/// without user-declared constructors, and calls the default
1643/// constructor for a for any type that has a user-declared
1644/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1645/// a type with a user-declared constructor does not have an
1646/// accessible, non-deleted default constructor. In C, everything can
1647/// be value-initialized, which corresponds to C's notion of
1648/// initializing objects with static storage duration when no
1649/// initializer is provided for that object.
1650///
1651/// \returns true if there was an error, false otherwise.
1652bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1653 // C++ [dcl.init]p5:
1654 //
1655 // To value-initialize an object of type T means:
1656
1657 // -- if T is an array type, then each element is value-initialized;
1658 if (const ArrayType *AT = Context.getAsArrayType(Type))
1659 return CheckValueInitialization(AT->getElementType(), Loc);
1660
1661 if (const RecordType *RT = Type->getAsRecordType()) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001662 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Douglas Gregor87fd7032009-02-02 17:43:21 +00001663 // -- if T is a class type (clause 9) with a user-declared
1664 // constructor (12.1), then the default constructor for T is
1665 // called (and the initialization is ill-formed if T has no
1666 // accessible default constructor);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001667 if (ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor87fd7032009-02-02 17:43:21 +00001668 // FIXME: Eventually, we'll need to put the constructor decl
1669 // into the AST.
1670 return PerformInitializationByConstructor(Type, 0, 0, Loc,
1671 SourceRange(Loc),
1672 DeclarationName(),
1673 IK_Direct);
1674 }
1675 }
1676
1677 if (Type->isReferenceType()) {
1678 // C++ [dcl.init]p5:
1679 // [...] A program that calls for default-initialization or
1680 // value-initialization of an entity of reference type is
1681 // ill-formed. [...]
Douglas Gregord8635172009-02-02 21:35:47 +00001682 // FIXME: Once we have code that goes through this path, add an
1683 // actual diagnostic :)
Douglas Gregor87fd7032009-02-02 17:43:21 +00001684 }
1685
1686 return false;
1687}