blob: 6090b79c5c1445dae5d2150f6b845386acc9023e [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"
Anders Carlsson2078bb92009-05-27 16:10:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000023#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000024using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000025
Chris Lattnerdd8e0062009-02-24 22:27:37 +000026//===----------------------------------------------------------------------===//
27// Sema Initialization Checking
28//===----------------------------------------------------------------------===//
29
Chris Lattner79e079d2009-02-24 23:10:27 +000030static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattner8879e3b2009-02-26 23:26:43 +000031 const ArrayType *AT = Context.getAsArrayType(DeclType);
32 if (!AT) return 0;
33
34 // See if this is a string literal or @encode.
35 Init = Init->IgnoreParens();
36
37 // Handle @encode, which is a narrow string.
38 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
39 return Init;
40
41 // Otherwise we can only handle string literals.
42 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000043 if (SL == 0) return 0;
Chris Lattner8879e3b2009-02-26 23:26:43 +000044
45 // char array can be initialized with a narrow string.
46 // Only allow char x[] = "foo"; not char x[] = L"foo";
47 if (!SL->isWide())
48 return AT->getElementType()->isCharType() ? Init : 0;
49
50 // wchar_t array can be initialized with a wide string: C99 6.7.8p15:
51 // "An array with element type compatible with wchar_t may be initialized by a
52 // wide string literal, optionally enclosed in braces."
Chris Lattner19753cf2009-02-26 23:36:02 +000053 if (Context.typesAreCompatible(Context.getWCharType(), AT->getElementType()))
Chris Lattner8879e3b2009-02-26 23:26:43 +000054 // Only allow wchar_t x[] = L"foo"; not wchar_t x[] = "foo";
55 return Init;
56
Chris Lattnerdd8e0062009-02-24 22:27:37 +000057 return 0;
58}
59
Chris Lattner95e8d652009-02-24 22:46:58 +000060static bool CheckSingleInitializer(Expr *&Init, QualType DeclType,
61 bool DirectInit, Sema &S) {
Chris Lattnerdd8e0062009-02-24 22:27:37 +000062 // Get the type before calling CheckSingleAssignmentConstraints(), since
63 // it can promote the expression.
64 QualType InitType = Init->getType();
65
Chris Lattner95e8d652009-02-24 22:46:58 +000066 if (S.getLangOptions().CPlusPlus) {
Chris Lattnerdd8e0062009-02-24 22:27:37 +000067 // FIXME: I dislike this error message. A lot.
Chris Lattner95e8d652009-02-24 22:46:58 +000068 if (S.PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
69 return S.Diag(Init->getSourceRange().getBegin(),
70 diag::err_typecheck_convert_incompatible)
71 << DeclType << Init->getType() << "initializing"
72 << Init->getSourceRange();
Chris Lattnerdd8e0062009-02-24 22:27:37 +000073 return false;
74 }
75
Chris Lattner95e8d652009-02-24 22:46:58 +000076 Sema::AssignConvertType ConvTy =
77 S.CheckSingleAssignmentConstraints(DeclType, Init);
78 return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
Chris Lattnerdd8e0062009-02-24 22:27:37 +000079 InitType, Init, "initializing");
80}
81
Chris Lattner79e079d2009-02-24 23:10:27 +000082static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
83 // Get the length of the string as parsed.
84 uint64_t StrLength =
85 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
86
Chris Lattnerdd8e0062009-02-24 22:27:37 +000087
Chris Lattner79e079d2009-02-24 23:10:27 +000088 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +000089 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
90 // C99 6.7.8p14. We have an array of character type with unknown size
91 // being initialized to a string literal.
92 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +000093 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000094 // Return a new array type (C99 6.7.8p22).
Chris Lattnerf71ae8d2009-02-24 22:41:04 +000095 DeclT = S.Context.getConstantArrayType(IAT->getElementType(), ConstVal,
96 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +000097 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000098 }
Chris Lattner19da8cd2009-02-24 23:01:39 +000099
Mike Stump4f54f4e2009-05-29 16:34:15 +0000100 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
101 // C99 6.7.8p14. We have an array of character type with known size.
102 // However, the size may be smaller or larger than the string we are
103 // initializing.
104 // FIXME: Avoid truncation for 64-bit length strings.
105 if (StrLength-1 > CAT->getSize().getZExtValue())
106 S.Diag(Str->getSourceRange().getBegin(),
107 diag::warn_initializer_string_for_char_array_too_long)
108 << Str->getSourceRange();
109
110 // Set the type to the actual size that we are initializing. If we have
111 // something like:
112 // char x[1] = "foo";
113 // then this will set the string literal's type to char[1].
114 Str->setType(DeclT);
115 }
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000116}
117
118bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
119 SourceLocation InitLoc,
120 DeclarationName InitEntity,
Anders Carlsson2078bb92009-05-27 16:10:08 +0000121 bool DirectInit, VarDecl *VD) {
Douglas Gregor9ea62762009-05-21 23:17:49 +0000122 if (DeclType->isDependentType() ||
123 Init->isTypeDependent() || Init->isValueDependent())
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000124 return false;
125
126 // C++ [dcl.init.ref]p1:
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000127 // A variable declared to be a T& or T&&, that is "reference to type T"
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000128 // (8.3.2), shall be initialized by an object, or function, of
129 // type T or by an object that can be converted into a T.
130 if (DeclType->isReferenceType())
131 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
132
133 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
134 // of unknown size ("[]") or an object type that is not a variable array type.
135 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
136 return Diag(InitLoc, diag::err_variable_object_no_init)
137 << VAT->getSizeExpr()->getSourceRange();
138
139 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
140 if (!InitList) {
141 // FIXME: Handle wide strings
Chris Lattner79e079d2009-02-24 23:10:27 +0000142 if (Expr *Str = IsStringInit(Init, DeclType, Context)) {
143 CheckStringInit(Str, DeclType, *this);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000144 return false;
145 }
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000146
147 // C++ [dcl.init]p14:
148 // -- If the destination type is a (possibly cv-qualified) class
149 // type:
150 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
151 QualType DeclTypeC = Context.getCanonicalType(DeclType);
152 QualType InitTypeC = Context.getCanonicalType(Init->getType());
153
154 // -- If the initialization is direct-initialization, or if it is
155 // copy-initialization where the cv-unqualified version of the
156 // source type is the same class as, or a derived class of, the
157 // class of the destination, constructors are considered.
158 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
159 IsDerivedFrom(InitTypeC, DeclTypeC)) {
Anders Carlssonbffed8a2009-05-27 16:38:58 +0000160 const CXXRecordDecl *RD =
161 cast<CXXRecordDecl>(DeclType->getAsRecordType()->getDecl());
162
163 // No need to make a CXXConstructExpr if both the ctor and dtor are
164 // trivial.
165 if (RD->hasTrivialConstructor() && RD->hasTrivialDestructor())
166 return false;
167
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000168 CXXConstructorDecl *Constructor
169 = PerformInitializationByConstructor(DeclType, &Init, 1,
170 InitLoc, Init->getSourceRange(),
171 InitEntity,
172 DirectInit? IK_Direct : IK_Copy);
Anders Carlsson2078bb92009-05-27 16:10:08 +0000173 if (!Constructor)
174 return true;
175
176 // FIXME: What do do if VD is null here?
Anders Carlsson7c520cf2009-05-27 16:28:34 +0000177 if (VD)
178 Init = CXXConstructExpr::Create(Context, VD, DeclType, Constructor,
179 false, &Init, 1);
Anders Carlsson2078bb92009-05-27 16:10:08 +0000180 return false;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000181 }
182
183 // -- Otherwise (i.e., for the remaining copy-initialization
184 // cases), user-defined conversion sequences that can
185 // convert from the source type to the destination type or
186 // (when a conversion function is used) to a derived class
187 // thereof are enumerated as described in 13.3.1.4, and the
188 // best one is chosen through overload resolution
189 // (13.3). If the conversion cannot be done or is
190 // ambiguous, the initialization is ill-formed. The
191 // function selected is called with the initializer
192 // expression as its argument; if the function is a
193 // constructor, the call initializes a temporary of the
194 // destination type.
Mike Stump390b4cc2009-05-16 07:39:55 +0000195 // FIXME: We're pretending to do copy elision here; return to this when we
196 // have ASTs for such things.
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000197 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
198 return false;
199
200 if (InitEntity)
201 return Diag(InitLoc, diag::err_cannot_initialize_decl)
202 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
203 << Init->getType() << Init->getSourceRange();
204 else
205 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
206 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
207 << Init->getType() << Init->getSourceRange();
208 }
209
210 // C99 6.7.8p16.
211 if (DeclType->isArrayType())
212 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
213 << Init->getSourceRange();
214
Chris Lattner95e8d652009-02-24 22:46:58 +0000215 return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000216 }
217
218 bool hadError = CheckInitList(InitList, DeclType);
219 Init = InitList;
220 return hadError;
221}
222
223//===----------------------------------------------------------------------===//
224// Semantic checking for initializer lists.
225//===----------------------------------------------------------------------===//
226
Douglas Gregor9e80f722009-01-29 01:05:33 +0000227/// @brief Semantic checking for initializer lists.
228///
229/// The InitListChecker class contains a set of routines that each
230/// handle the initialization of a certain kind of entity, e.g.,
231/// arrays, vectors, struct/union types, scalars, etc. The
232/// InitListChecker itself performs a recursive walk of the subobject
233/// structure of the type to be initialized, while stepping through
234/// the initializer list one element at a time. The IList and Index
235/// parameters to each of the Check* routines contain the active
236/// (syntactic) initializer list and the index into that initializer
237/// list that represents the current initializer. Each routine is
238/// responsible for moving that Index forward as it consumes elements.
239///
240/// Each Check* routine also has a StructuredList/StructuredIndex
241/// arguments, which contains the current the "structured" (semantic)
242/// initializer list and the index into that initializer list where we
243/// are copying initializers as we map them over to the semantic
244/// list. Once we have completed our recursive walk of the subobject
245/// structure, we will have constructed a full semantic initializer
246/// list.
247///
248/// C99 designators cause changes in the initializer list traversal,
249/// because they make the initialization "jump" into a specific
250/// subobject and then continue the initialization from that
251/// point. CheckDesignatedInitializer() recursively steps into the
252/// designated subobject and manages backing out the recursion to
253/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000254namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000255class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000256 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000257 bool hadError;
258 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
259 InitListExpr *FullyStructuredList;
260
261 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000262 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000263 unsigned &StructuredIndex,
264 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000265 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000266 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000267 unsigned &StructuredIndex,
268 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000269 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
270 bool SubobjectIsDesignatorContext,
271 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000272 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000273 unsigned &StructuredIndex,
274 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000275 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
276 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000277 InitListExpr *StructuredList,
278 unsigned &StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000279 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000280 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000281 InitListExpr *StructuredList,
282 unsigned &StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000283 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
284 unsigned &Index,
285 InitListExpr *StructuredList,
286 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000287 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000288 InitListExpr *StructuredList,
289 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000290 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
291 RecordDecl::field_iterator Field,
292 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000293 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000294 unsigned &StructuredIndex,
295 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000296 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
297 llvm::APSInt elementIndex,
298 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000299 InitListExpr *StructuredList,
300 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000301 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000302 unsigned DesigIdx,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000303 QualType &CurrentObjectType,
304 RecordDecl::field_iterator *NextField,
305 llvm::APSInt *NextElementIndex,
306 unsigned &Index,
307 InitListExpr *StructuredList,
308 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000309 bool FinishSubobjectInit,
310 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000311 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
312 QualType CurrentObjectType,
313 InitListExpr *StructuredList,
314 unsigned StructuredIndex,
315 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000316 void UpdateStructuredListElement(InitListExpr *StructuredList,
317 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000318 Expr *expr);
319 int numArrayElements(QualType DeclType);
320 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000321
322 void FillInValueInitializations(InitListExpr *ILE);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000323public:
Chris Lattner08202542009-02-24 22:50:46 +0000324 InitListChecker(Sema &S, InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000325 bool HadError() { return hadError; }
326
327 // @brief Retrieves the fully-structured initializer list used for
328 // semantic analysis and code generation.
329 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
330};
Chris Lattner8b419b92009-02-24 22:48:58 +0000331} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000332
Douglas Gregor4c678342009-01-28 21:54:33 +0000333/// Recursively replaces NULL values within the given initializer list
334/// with expressions that perform value-initialization of the
335/// appropriate type.
Douglas Gregor930d8b52009-01-30 22:09:00 +0000336void InitListChecker::FillInValueInitializations(InitListExpr *ILE) {
Chris Lattner08202542009-02-24 22:50:46 +0000337 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000338 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000339 SourceLocation Loc = ILE->getSourceRange().getBegin();
340 if (ILE->getSyntacticForm())
341 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
342
Douglas Gregor4c678342009-01-28 21:54:33 +0000343 if (const RecordType *RType = ILE->getType()->getAsRecordType()) {
344 unsigned Init = 0, NumInits = ILE->getNumInits();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000345 for (RecordDecl::field_iterator
346 Field = RType->getDecl()->field_begin(SemaRef.Context),
347 FieldEnd = RType->getDecl()->field_end(SemaRef.Context);
Douglas Gregor4c678342009-01-28 21:54:33 +0000348 Field != FieldEnd; ++Field) {
349 if (Field->isUnnamedBitfield())
350 continue;
351
Douglas Gregor87fd7032009-02-02 17:43:21 +0000352 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000353 if (Field->getType()->isReferenceType()) {
354 // C++ [dcl.init.aggr]p9:
355 // If an incomplete or empty initializer-list leaves a
356 // member of reference type uninitialized, the program is
357 // ill-formed.
Chris Lattner08202542009-02-24 22:50:46 +0000358 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000359 << Field->getType()
360 << ILE->getSyntacticForm()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +0000361 SemaRef.Diag(Field->getLocation(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000362 diag::note_uninit_reference_member);
363 hadError = true;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000364 return;
Chris Lattner08202542009-02-24 22:50:46 +0000365 } else if (SemaRef.CheckValueInitialization(Field->getType(), Loc)) {
Douglas Gregor87fd7032009-02-02 17:43:21 +0000366 hadError = true;
367 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000368 }
Douglas Gregor87fd7032009-02-02 17:43:21 +0000369
Mike Stump390b4cc2009-05-16 07:39:55 +0000370 // FIXME: If value-initialization involves calling a constructor, should
371 // we make that call explicit in the representation (even when it means
372 // extending the initializer list)?
Douglas Gregor87fd7032009-02-02 17:43:21 +0000373 if (Init < NumInits && !hadError)
374 ILE->setInit(Init,
Chris Lattner08202542009-02-24 22:50:46 +0000375 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()));
Douglas Gregor87fd7032009-02-02 17:43:21 +0000376 } else if (InitListExpr *InnerILE
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000377 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000378 FillInValueInitializations(InnerILE);
Douglas Gregor4c678342009-01-28 21:54:33 +0000379 ++Init;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000380
381 // Only look at the first initialization of a union.
382 if (RType->getDecl()->isUnion())
383 break;
Douglas Gregor4c678342009-01-28 21:54:33 +0000384 }
385
386 return;
387 }
388
389 QualType ElementType;
390
Douglas Gregor87fd7032009-02-02 17:43:21 +0000391 unsigned NumInits = ILE->getNumInits();
392 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000393 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000394 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000395 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
396 NumElements = CAType->getSize().getZExtValue();
397 } else if (const VectorType *VType = ILE->getType()->getAsVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000398 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000399 NumElements = VType->getNumElements();
400 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000401 ElementType = ILE->getType();
402
Douglas Gregor87fd7032009-02-02 17:43:21 +0000403 for (unsigned Init = 0; Init != NumElements; ++Init) {
404 if (Init >= NumInits || !ILE->getInit(Init)) {
Chris Lattner08202542009-02-24 22:50:46 +0000405 if (SemaRef.CheckValueInitialization(ElementType, Loc)) {
Douglas Gregor87fd7032009-02-02 17:43:21 +0000406 hadError = true;
407 return;
408 }
409
Mike Stump390b4cc2009-05-16 07:39:55 +0000410 // FIXME: If value-initialization involves calling a constructor, should
411 // we make that call explicit in the representation (even when it means
412 // extending the initializer list)?
Douglas Gregor87fd7032009-02-02 17:43:21 +0000413 if (Init < NumInits && !hadError)
414 ILE->setInit(Init,
Chris Lattner08202542009-02-24 22:50:46 +0000415 new (SemaRef.Context) ImplicitValueInitExpr(ElementType));
Douglas Gregor87fd7032009-02-02 17:43:21 +0000416 }
Chris Lattner68355a52009-01-29 05:10:57 +0000417 else if (InitListExpr *InnerILE =dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000418 FillInValueInitializations(InnerILE);
Douglas Gregor4c678342009-01-28 21:54:33 +0000419 }
420}
421
Chris Lattner68355a52009-01-29 05:10:57 +0000422
Chris Lattner08202542009-02-24 22:50:46 +0000423InitListChecker::InitListChecker(Sema &S, InitListExpr *IL, QualType &T)
424 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000425 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000426
Eli Friedmanb85f7072008-05-19 19:16:24 +0000427 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000428 unsigned newStructuredIndex = 0;
429 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000430 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000431 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
432 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000433
Douglas Gregor930d8b52009-01-30 22:09:00 +0000434 if (!hadError)
435 FillInValueInitializations(FullyStructuredList);
Steve Naroff0cca7492008-05-01 22:18:59 +0000436}
437
438int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000439 // FIXME: use a proper constant
440 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000441 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000442 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000443 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
444 }
445 return maxElements;
446}
447
448int InitListChecker::numStructUnionElements(QualType DeclType) {
449 RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000450 int InitializableMembers = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000451 for (RecordDecl::field_iterator
452 Field = structDecl->field_begin(SemaRef.Context),
453 FieldEnd = structDecl->field_end(SemaRef.Context);
Douglas Gregor4c678342009-01-28 21:54:33 +0000454 Field != FieldEnd; ++Field) {
455 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
456 ++InitializableMembers;
457 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000458 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000459 return std::min(InitializableMembers, 1);
460 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000461}
462
463void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000464 QualType T, unsigned &Index,
465 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000466 unsigned &StructuredIndex,
467 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000468 int maxElements = 0;
469
470 if (T->isArrayType())
471 maxElements = numArrayElements(T);
472 else if (T->isStructureType() || T->isUnionType())
473 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000474 else if (T->isVectorType())
475 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000476 else
477 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000478
Eli Friedman402256f2008-05-25 13:49:22 +0000479 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000480 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000481 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000482 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000483 hadError = true;
484 return;
485 }
486
Douglas Gregor4c678342009-01-28 21:54:33 +0000487 // Build a structured initializer list corresponding to this subobject.
488 InitListExpr *StructuredSubobjectInitList
489 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
490 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000491 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
492 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000493 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000494
Douglas Gregor4c678342009-01-28 21:54:33 +0000495 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000496 unsigned StartIndex = Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000497 CheckListElementTypes(ParentIList, T, false, Index,
498 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000499 StructuredSubobjectInitIndex,
500 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000501 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000502 StructuredSubobjectInitList->setType(T);
503
Douglas Gregored8a93d2009-03-01 17:12:46 +0000504 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000505 // range corresponds with the end of the last initializer it used.
506 if (EndIndex < ParentIList->getNumInits()) {
507 SourceLocation EndLoc
508 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
509 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
510 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000511}
512
Steve Naroffa647caa2008-05-06 00:23:44 +0000513void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000514 unsigned &Index,
515 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000516 unsigned &StructuredIndex,
517 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000518 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000519 SyntacticToSemantic[IList] = StructuredList;
520 StructuredList->setSyntacticForm(IList);
521 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000522 StructuredIndex, TopLevelObject);
Steve Naroffa647caa2008-05-06 00:23:44 +0000523 IList->setType(T);
Douglas Gregor4c678342009-01-28 21:54:33 +0000524 StructuredList->setType(T);
Eli Friedman638e1442008-05-25 13:22:35 +0000525 if (hadError)
526 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000527
Eli Friedman638e1442008-05-25 13:22:35 +0000528 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000529 // We have leftover initializers
530 if (IList->getNumInits() > 0 &&
Chris Lattner08202542009-02-24 22:50:46 +0000531 IsStringInit(IList->getInit(Index), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000532 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
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_in_char_array_initializer;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000535 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000536 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000537 << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000538 hadError = true;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000539 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000540 // Don't complain for incomplete types, since we'll get an error
541 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000542 QualType CurrentObjectType = StructuredList->getType();
543 int initKind =
544 CurrentObjectType->isArrayType()? 0 :
545 CurrentObjectType->isVectorType()? 1 :
546 CurrentObjectType->isScalarType()? 2 :
547 CurrentObjectType->isUnionType()? 3 :
548 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000549
550 unsigned DK = diag::warn_excess_initializers;
Chris Lattner08202542009-02-24 22:50:46 +0000551 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000552 DK = diag::err_excess_initializers;
553
Chris Lattner08202542009-02-24 22:50:46 +0000554 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000555 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000556 }
557 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000558
Eli Friedman759f2522009-05-16 11:45:48 +0000559 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000560 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000561 << IList->getSourceRange()
562 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocStart()))
563 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocEnd()));
Steve Naroff0cca7492008-05-01 22:18:59 +0000564}
565
Eli Friedmanb85f7072008-05-19 19:16:24 +0000566void InitListChecker::CheckListElementTypes(InitListExpr *IList,
567 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000568 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000569 unsigned &Index,
570 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000571 unsigned &StructuredIndex,
572 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000573 if (DeclType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000574 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000575 } else if (DeclType->isVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000576 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000577 } else if (DeclType->isAggregateType()) {
578 if (DeclType->isRecordType()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000579 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000580 CheckStructUnionTypes(IList, DeclType, RD->field_begin(SemaRef.Context),
Douglas Gregor4c678342009-01-28 21:54:33 +0000581 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000582 StructuredList, StructuredIndex,
583 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000584 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000585 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000586 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000587 false);
Douglas Gregor4c678342009-01-28 21:54:33 +0000588 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
589 StructuredList, StructuredIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000590 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000591 else
Douglas Gregor4c678342009-01-28 21:54:33 +0000592 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000593 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
594 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000595 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000596 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000597 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000598 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000599 } else if (DeclType->isRecordType()) {
600 // C++ [dcl.init]p14:
601 // [...] If the class is an aggregate (8.5.1), and the initializer
602 // is a brace-enclosed list, see 8.5.1.
603 //
604 // Note: 8.5.1 is handled below; here, we diagnose the case where
605 // we have an initializer list and a destination type that is not
606 // an aggregate.
607 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000608 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000609 << DeclType << IList->getSourceRange();
610 hadError = true;
611 } else if (DeclType->isReferenceType()) {
612 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000613 } else {
614 // In C, all types are either scalars or aggregates, but
615 // additional handling is needed here for C++ (and possibly others?).
616 assert(0 && "Unsupported initializer type");
617 }
618}
619
Eli Friedmanb85f7072008-05-19 19:16:24 +0000620void InitListChecker::CheckSubElementType(InitListExpr *IList,
621 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000622 unsigned &Index,
623 InitListExpr *StructuredList,
624 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000625 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000626 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
627 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000628 unsigned newStructuredIndex = 0;
629 InitListExpr *newStructuredList
630 = getStructuredSubobjectInit(IList, Index, ElemType,
631 StructuredList, StructuredIndex,
632 SubInitList->getSourceRange());
633 CheckExplicitInitList(SubInitList, ElemType, newIndex,
634 newStructuredList, newStructuredIndex);
635 ++StructuredIndex;
636 ++Index;
Chris Lattner79e079d2009-02-24 23:10:27 +0000637 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
638 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000639 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000640 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000641 } else if (ElemType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000642 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000643 } else if (ElemType->isReferenceType()) {
644 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000645 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000646 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000647 // C++ [dcl.init.aggr]p12:
648 // All implicit type conversions (clause 4) are considered when
649 // initializing the aggregate member with an ini- tializer from
650 // an initializer-list. If the initializer can initialize a
651 // member, the member is initialized. [...]
652 ImplicitConversionSequence ICS
Chris Lattner08202542009-02-24 22:50:46 +0000653 = SemaRef.TryCopyInitialization(expr, ElemType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000654 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Chris Lattner08202542009-02-24 22:50:46 +0000655 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000656 "initializing"))
657 hadError = true;
658 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
659 ++Index;
660 return;
661 }
662
663 // Fall through for subaggregate initialization
664 } else {
665 // C99 6.7.8p13:
666 //
667 // The initializer for a structure or union object that has
668 // automatic storage duration shall be either an initializer
669 // list as described below, or a single expression that has
670 // compatible structure or union type. In the latter case, the
671 // initial value of the object, including unnamed members, is
672 // that of the expression.
Chris Lattner08202542009-02-24 22:50:46 +0000673 QualType ExprType = SemaRef.Context.getCanonicalType(expr->getType());
674 QualType ElemTypeCanon = SemaRef.Context.getCanonicalType(ElemType);
675 if (SemaRef.Context.typesAreCompatible(ExprType.getUnqualifiedType(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000676 ElemTypeCanon.getUnqualifiedType())) {
677 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
678 ++Index;
679 return;
680 }
681
682 // Fall through for subaggregate initialization
683 }
684
685 // C++ [dcl.init.aggr]p12:
686 //
687 // [...] Otherwise, if the member is itself a non-empty
688 // subaggregate, brace elision is assumed and the initializer is
689 // considered for the initialization of the first member of
690 // the subaggregate.
691 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
692 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
693 StructuredIndex);
694 ++StructuredIndex;
695 } else {
696 // We cannot initialize this element, so let
697 // PerformCopyInitialization produce the appropriate diagnostic.
Chris Lattner08202542009-02-24 22:50:46 +0000698 SemaRef.PerformCopyInitialization(expr, ElemType, "initializing");
Douglas Gregor930d8b52009-01-30 22:09:00 +0000699 hadError = true;
700 ++Index;
701 ++StructuredIndex;
702 }
703 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000704}
705
Douglas Gregor930d8b52009-01-30 22:09:00 +0000706void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000707 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000708 InitListExpr *StructuredList,
709 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000710 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000711 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000712 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000713 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000714 diag::err_many_braces_around_scalar_init)
715 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000716 hadError = true;
717 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000718 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000719 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000720 } else if (isa<DesignatedInitExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000721 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor05c13a32009-01-22 00:58:24 +0000722 diag::err_designator_for_scalar_init)
723 << DeclType << expr->getSourceRange();
724 hadError = true;
725 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000726 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000727 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000728 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000729
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000730 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner08202542009-02-24 22:50:46 +0000731 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedmanbb504d32008-05-19 20:12:18 +0000732 hadError = true; // types weren't compatible.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000733 else if (savExpr != expr) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000734 // The type was promoted, update initializer list.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000735 IList->setInit(Index, expr);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000736 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000737 if (hadError)
738 ++StructuredIndex;
739 else
740 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000741 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000742 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000743 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000744 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000745 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000746 ++Index;
747 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000748 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000749 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000750}
751
Douglas Gregor930d8b52009-01-30 22:09:00 +0000752void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
753 unsigned &Index,
754 InitListExpr *StructuredList,
755 unsigned &StructuredIndex) {
756 if (Index < IList->getNumInits()) {
757 Expr *expr = IList->getInit(Index);
758 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000759 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000760 << DeclType << IList->getSourceRange();
761 hadError = true;
762 ++Index;
763 ++StructuredIndex;
764 return;
765 }
766
767 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner08202542009-02-24 22:50:46 +0000768 if (SemaRef.CheckReferenceInit(expr, DeclType))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000769 hadError = true;
770 else if (savExpr != expr) {
771 // The type was promoted, update initializer list.
772 IList->setInit(Index, expr);
773 }
774 if (hadError)
775 ++StructuredIndex;
776 else
777 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
778 ++Index;
779 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000780 // FIXME: It would be wonderful if we could point at the actual member. In
781 // general, it would be useful to pass location information down the stack,
782 // so that we know the location (or decl) of the "current object" being
783 // initialized.
Chris Lattner08202542009-02-24 22:50:46 +0000784 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000785 diag::err_init_reference_member_uninitialized)
786 << DeclType
787 << IList->getSourceRange();
788 hadError = true;
789 ++Index;
790 ++StructuredIndex;
791 return;
792 }
793}
794
Steve Naroff0cca7492008-05-01 22:18:59 +0000795void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000796 unsigned &Index,
797 InitListExpr *StructuredList,
798 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000799 if (Index < IList->getNumInits()) {
800 const VectorType *VT = DeclType->getAsVectorType();
801 int maxElements = VT->getNumElements();
802 QualType elementType = VT->getElementType();
803
804 for (int i = 0; i < maxElements; ++i) {
805 // Don't attempt to go past the end of the init list
806 if (Index >= IList->getNumInits())
807 break;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000808 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000809 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000810 }
811 }
812}
813
814void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000815 llvm::APSInt elementIndex,
816 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000817 unsigned &Index,
818 InitListExpr *StructuredList,
819 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000820 // Check for the special-case of initializing an array with a string.
821 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000822 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
823 SemaRef.Context)) {
824 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +0000825 // We place the string literal directly into the resulting
826 // initializer list. This is the only place where the structure
827 // of the structured initializer list doesn't match exactly,
828 // because doing so would involve allocating one character
829 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000830 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +0000831 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000832 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000833 return;
834 }
835 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000836 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +0000837 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000838 // Check for VLAs; in standard C it would be possible to check this
839 // earlier, but I don't know where clang accepts VLAs (gcc accepts
840 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +0000841 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000842 diag::err_variable_object_no_init)
843 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000844 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000845 ++Index;
846 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000847 return;
848 }
849
Douglas Gregor05c13a32009-01-22 00:58:24 +0000850 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000851 llvm::APSInt maxElements(elementIndex.getBitWidth(),
852 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000853 bool maxElementsKnown = false;
854 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000855 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000856 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000857 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000858 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000859 maxElementsKnown = true;
860 }
861
Chris Lattner08202542009-02-24 22:50:46 +0000862 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000863 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000864 while (Index < IList->getNumInits()) {
865 Expr *Init = IList->getInit(Index);
866 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000867 // If we're not the subobject that matches up with the '{' for
868 // the designator, we shouldn't be handling the
869 // designator. Return immediately.
870 if (!SubobjectIsDesignatorContext)
871 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000872
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000873 // Handle this designated initializer. elementIndex will be
874 // updated to be the next array element we'll initialize.
Douglas Gregor71199712009-04-15 04:56:10 +0000875 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +0000876 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000877 StructuredList, StructuredIndex, true,
878 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000879 hadError = true;
880 continue;
881 }
882
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000883 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
884 maxElements.extend(elementIndex.getBitWidth());
885 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
886 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000887 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000888
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000889 // If the array is of incomplete type, keep track of the number of
890 // elements in the initializer.
891 if (!maxElementsKnown && elementIndex > maxElements)
892 maxElements = elementIndex;
893
Douglas Gregor05c13a32009-01-22 00:58:24 +0000894 continue;
895 }
896
897 // If we know the maximum number of elements, and we've already
898 // hit it, stop consuming elements in the initializer list.
899 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +0000900 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000901
902 // Check this element.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000903 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000904 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000905 ++elementIndex;
906
907 // If the array is of incomplete type, keep track of the number of
908 // elements in the initializer.
909 if (!maxElementsKnown && elementIndex > maxElements)
910 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +0000911 }
912 if (DeclType->isIncompleteArrayType()) {
913 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000914 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000915 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000916 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000917 // Sizing an array implicitly to zero is not allowed by ISO C,
918 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +0000919 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000920 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +0000921 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000922
Chris Lattner08202542009-02-24 22:50:46 +0000923 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000924 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +0000925 }
926}
927
928void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
929 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000930 RecordDecl::field_iterator Field,
931 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000932 unsigned &Index,
933 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000934 unsigned &StructuredIndex,
935 bool TopLevelObject) {
Eli Friedmanb85f7072008-05-19 19:16:24 +0000936 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroff0cca7492008-05-01 22:18:59 +0000937
Eli Friedmanb85f7072008-05-19 19:16:24 +0000938 // If the record is invalid, some of it's members are invalid. To avoid
939 // confusion, we forgo checking the intializer for the entire record.
940 if (structDecl->isInvalidDecl()) {
941 hadError = true;
942 return;
943 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000944
945 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
946 // Value-initialize the first named member of the union.
947 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000948 for (RecordDecl::field_iterator FieldEnd = RD->field_end(SemaRef.Context);
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000949 Field != FieldEnd; ++Field) {
950 if (Field->getDeclName()) {
951 StructuredList->setInitializedFieldInUnion(*Field);
952 break;
953 }
954 }
955 return;
956 }
957
Douglas Gregor05c13a32009-01-22 00:58:24 +0000958 // If structDecl is a forward declaration, this loop won't do
959 // anything except look at designated initializers; That's okay,
960 // because an error should get printed out elsewhere. It might be
961 // worthwhile to skip over the rest of the initializer, though.
Douglas Gregor44b43212008-12-11 16:49:14 +0000962 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000963 RecordDecl::field_iterator FieldEnd = RD->field_end(SemaRef.Context);
Douglas Gregordfb5e592009-02-12 19:00:39 +0000964 bool InitializedSomething = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000965 while (Index < IList->getNumInits()) {
966 Expr *Init = IList->getInit(Index);
967
968 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000969 // If we're not the subobject that matches up with the '{' for
970 // the designator, we shouldn't be handling the
971 // designator. Return immediately.
972 if (!SubobjectIsDesignatorContext)
973 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000974
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000975 // Handle this designated initializer. Field will be updated to
976 // the next field that we'll be initializing.
Douglas Gregor71199712009-04-15 04:56:10 +0000977 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +0000978 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000979 StructuredList, StructuredIndex,
980 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000981 hadError = true;
982
Douglas Gregordfb5e592009-02-12 19:00:39 +0000983 InitializedSomething = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000984 continue;
985 }
986
987 if (Field == FieldEnd) {
988 // We've run out of fields. We're done.
989 break;
990 }
991
Douglas Gregordfb5e592009-02-12 19:00:39 +0000992 // We've already initialized a member of a union. We're done.
993 if (InitializedSomething && DeclType->isUnionType())
994 break;
995
Douglas Gregor44b43212008-12-11 16:49:14 +0000996 // If we've hit the flexible array member at the end, we're done.
997 if (Field->getType()->isIncompleteArrayType())
998 break;
999
Douglas Gregor0bb76892009-01-29 16:53:55 +00001000 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001001 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001002 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001003 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001004 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001005
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001006 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001007 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001008 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001009
1010 if (DeclType->isUnionType()) {
1011 // Initialize the first field within the union.
1012 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001013 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001014
1015 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001016 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001017
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001018 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001019 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001020 return;
1021
1022 // Handle GNU flexible array initializers.
1023 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001024 (!isa<InitListExpr>(IList->getInit(Index)) ||
1025 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Chris Lattner08202542009-02-24 22:50:46 +00001026 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001027 diag::err_flexible_array_init_nonempty)
1028 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001029 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001030 << *Field;
1031 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001032 ++Index;
1033 return;
1034 } else {
1035 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
1036 diag::ext_flexible_array_init)
1037 << IList->getInit(Index)->getSourceRange().getBegin();
1038 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1039 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001040 }
1041
Douglas Gregora6457962009-03-20 00:32:56 +00001042 if (isa<InitListExpr>(IList->getInit(Index)))
1043 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1044 StructuredIndex);
1045 else
1046 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1047 StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001048}
Steve Naroff0cca7492008-05-01 22:18:59 +00001049
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001050/// \brief Expand a field designator that refers to a member of an
1051/// anonymous struct or union into a series of field designators that
1052/// refers to the field within the appropriate subobject.
1053///
1054/// Field/FieldIndex will be updated to point to the (new)
1055/// currently-designated field.
1056static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1057 DesignatedInitExpr *DIE,
1058 unsigned DesigIdx,
1059 FieldDecl *Field,
1060 RecordDecl::field_iterator &FieldIter,
1061 unsigned &FieldIndex) {
1062 typedef DesignatedInitExpr::Designator Designator;
1063
1064 // Build the path from the current object to the member of the
1065 // anonymous struct/union (backwards).
1066 llvm::SmallVector<FieldDecl *, 4> Path;
1067 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
1068
1069 // Build the replacement designators.
1070 llvm::SmallVector<Designator, 4> Replacements;
1071 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1072 FI = Path.rbegin(), FIEnd = Path.rend();
1073 FI != FIEnd; ++FI) {
1074 if (FI + 1 == FIEnd)
1075 Replacements.push_back(Designator((IdentifierInfo *)0,
1076 DIE->getDesignator(DesigIdx)->getDotLoc(),
1077 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1078 else
1079 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1080 SourceLocation()));
1081 Replacements.back().setField(*FI);
1082 }
1083
1084 // Expand the current designator into the set of replacement
1085 // designators, so we have a full subobject path down to where the
1086 // member of the anonymous struct/union is actually stored.
1087 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
1088 &Replacements[0] + Replacements.size());
1089
1090 // Update FieldIter/FieldIndex;
1091 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
1092 FieldIter = Record->field_begin(SemaRef.Context);
1093 FieldIndex = 0;
1094 for (RecordDecl::field_iterator FEnd = Record->field_end(SemaRef.Context);
1095 FieldIter != FEnd; ++FieldIter) {
1096 if (FieldIter->isUnnamedBitfield())
1097 continue;
1098
1099 if (*FieldIter == Path.back())
1100 return;
1101
1102 ++FieldIndex;
1103 }
1104
1105 assert(false && "Unable to find anonymous struct/union field");
1106}
1107
Douglas Gregor05c13a32009-01-22 00:58:24 +00001108/// @brief Check the well-formedness of a C99 designated initializer.
1109///
1110/// Determines whether the designated initializer @p DIE, which
1111/// resides at the given @p Index within the initializer list @p
1112/// IList, is well-formed for a current object of type @p DeclType
1113/// (C99 6.7.8). The actual subobject that this designator refers to
1114/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001115/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001116///
1117/// @param IList The initializer list in which this designated
1118/// initializer occurs.
1119///
Douglas Gregor71199712009-04-15 04:56:10 +00001120/// @param DIE The designated initializer expression.
1121///
1122/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001123///
1124/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1125/// into which the designation in @p DIE should refer.
1126///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001127/// @param NextField If non-NULL and the first designator in @p DIE is
1128/// a field, this will be set to the field declaration corresponding
1129/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001130///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001131/// @param NextElementIndex If non-NULL and the first designator in @p
1132/// DIE is an array designator or GNU array-range designator, this
1133/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001134///
1135/// @param Index Index into @p IList where the designated initializer
1136/// @p DIE occurs.
1137///
Douglas Gregor4c678342009-01-28 21:54:33 +00001138/// @param StructuredList The initializer list expression that
1139/// describes all of the subobject initializers in the order they'll
1140/// actually be initialized.
1141///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001142/// @returns true if there was an error, false otherwise.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001143bool
1144InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
1145 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001146 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001147 QualType &CurrentObjectType,
1148 RecordDecl::field_iterator *NextField,
1149 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001150 unsigned &Index,
1151 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001152 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001153 bool FinishSubobjectInit,
1154 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001155 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001156 // Check the actual initialization for the designated object type.
1157 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001158
1159 // Temporarily remove the designator expression from the
1160 // initializer list that the child calls see, so that we don't try
1161 // to re-process the designator.
1162 unsigned OldIndex = Index;
1163 IList->setInit(OldIndex, DIE->getInit());
1164
1165 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001166 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001167
1168 // Restore the designated initializer expression in the syntactic
1169 // form of the initializer list.
1170 if (IList->getInit(OldIndex) != DIE->getInit())
1171 DIE->setInit(IList->getInit(OldIndex));
1172 IList->setInit(OldIndex, DIE);
1173
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001174 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001175 }
1176
Douglas Gregor71199712009-04-15 04:56:10 +00001177 bool IsFirstDesignator = (DesigIdx == 0);
Douglas Gregor4c678342009-01-28 21:54:33 +00001178 assert((IsFirstDesignator || StructuredList) &&
1179 "Need a non-designated initializer list to start from");
1180
Douglas Gregor71199712009-04-15 04:56:10 +00001181 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001182 // Determine the structural initializer list that corresponds to the
1183 // current subobject.
1184 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Douglas Gregored8a93d2009-03-01 17:12:46 +00001185 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1186 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001187 SourceRange(D->getStartLocation(),
1188 DIE->getSourceRange().getEnd()));
1189 assert(StructuredList && "Expected a structured initializer list");
1190
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001191 if (D->isFieldDesignator()) {
1192 // C99 6.7.8p7:
1193 //
1194 // If a designator has the form
1195 //
1196 // . identifier
1197 //
1198 // then the current object (defined below) shall have
1199 // structure or union type and the identifier shall be the
1200 // name of a member of that type.
1201 const RecordType *RT = CurrentObjectType->getAsRecordType();
1202 if (!RT) {
1203 SourceLocation Loc = D->getDotLoc();
1204 if (Loc.isInvalid())
1205 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001206 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1207 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001208 ++Index;
1209 return true;
1210 }
1211
Douglas Gregor4c678342009-01-28 21:54:33 +00001212 // Note: we perform a linear search of the fields here, despite
1213 // the fact that we have a faster lookup method, because we always
1214 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001215 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001216 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001217 unsigned FieldIndex = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001218 RecordDecl::field_iterator
1219 Field = RT->getDecl()->field_begin(SemaRef.Context),
1220 FieldEnd = RT->getDecl()->field_end(SemaRef.Context);
Douglas Gregor4c678342009-01-28 21:54:33 +00001221 for (; Field != FieldEnd; ++Field) {
1222 if (Field->isUnnamedBitfield())
1223 continue;
1224
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001225 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor4c678342009-01-28 21:54:33 +00001226 break;
1227
1228 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001229 }
1230
Douglas Gregor4c678342009-01-28 21:54:33 +00001231 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001232 // There was no normal field in the struct with the designated
1233 // name. Perform another lookup for this name, which may find
1234 // something that we can't designate (e.g., a member function),
1235 // may find nothing, or may find a member of an anonymous
1236 // struct/union.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001237 DeclContext::lookup_result Lookup
1238 = RT->getDecl()->lookup(SemaRef.Context, FieldName);
Douglas Gregor4c678342009-01-28 21:54:33 +00001239 if (Lookup.first == Lookup.second) {
1240 // Name lookup didn't find anything.
Chris Lattner08202542009-02-24 22:50:46 +00001241 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregor4c678342009-01-28 21:54:33 +00001242 << FieldName << CurrentObjectType;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001243 ++Index;
1244 return true;
1245 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1246 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1247 ->isAnonymousStructOrUnion()) {
1248 // Handle an field designator that refers to a member of an
1249 // anonymous struct or union.
1250 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1251 cast<FieldDecl>(*Lookup.first),
1252 Field, FieldIndex);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001253 D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001254 } else {
1255 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001256 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001257 << FieldName;
Chris Lattner08202542009-02-24 22:50:46 +00001258 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001259 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001260 ++Index;
1261 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001262 }
1263 } else if (!KnownField &&
1264 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor4c678342009-01-28 21:54:33 +00001265 ->isAnonymousStructOrUnion()) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001266 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1267 Field, FieldIndex);
1268 D = DIE->getDesignator(DesigIdx);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001269 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001270
1271 // All of the fields of a union are located at the same place in
1272 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001273 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001274 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001275 StructuredList->setInitializedFieldInUnion(*Field);
1276 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001277
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001278 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001279 D->setField(*Field);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001280
Douglas Gregor4c678342009-01-28 21:54:33 +00001281 // Make sure that our non-designated initializer list has space
1282 // for a subobject corresponding to this field.
1283 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001284 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001285
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001286 // This designator names a flexible array member.
1287 if (Field->getType()->isIncompleteArrayType()) {
1288 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001289 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001290 // We can't designate an object within the flexible array
1291 // member (because GCC doesn't allow it).
Douglas Gregor71199712009-04-15 04:56:10 +00001292 DesignatedInitExpr::Designator *NextD
1293 = DIE->getDesignator(DesigIdx + 1);
Chris Lattner08202542009-02-24 22:50:46 +00001294 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001295 diag::err_designator_into_flexible_array_member)
1296 << SourceRange(NextD->getStartLocation(),
1297 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001298 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001299 << *Field;
1300 Invalid = true;
1301 }
1302
1303 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1304 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001305 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001306 diag::err_flexible_array_init_needs_braces)
1307 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001308 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001309 << *Field;
1310 Invalid = true;
1311 }
1312
1313 // Handle GNU flexible array initializers.
1314 if (!Invalid && !TopLevelObject &&
1315 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Chris Lattner08202542009-02-24 22:50:46 +00001316 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001317 diag::err_flexible_array_init_nonempty)
1318 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001319 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001320 << *Field;
1321 Invalid = true;
1322 }
1323
1324 if (Invalid) {
1325 ++Index;
1326 return true;
1327 }
1328
1329 // Initialize the array.
1330 bool prevHadError = hadError;
1331 unsigned newStructuredIndex = FieldIndex;
1332 unsigned OldIndex = Index;
1333 IList->setInit(Index, DIE->getInit());
1334 CheckSubElementType(IList, Field->getType(), Index,
1335 StructuredList, newStructuredIndex);
1336 IList->setInit(OldIndex, DIE);
1337 if (hadError && !prevHadError) {
1338 ++Field;
1339 ++FieldIndex;
1340 if (NextField)
1341 *NextField = Field;
1342 StructuredIndex = FieldIndex;
1343 return true;
1344 }
1345 } else {
1346 // Recurse to check later designated subobjects.
1347 QualType FieldType = (*Field)->getType();
1348 unsigned newStructuredIndex = FieldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001349 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1350 Index, StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001351 true, false))
1352 return true;
1353 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001354
1355 // Find the position of the next field to be initialized in this
1356 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001357 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001358 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001359
1360 // If this the first designator, our caller will continue checking
1361 // the rest of this struct/class/union subobject.
1362 if (IsFirstDesignator) {
1363 if (NextField)
1364 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001365 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001366 return false;
1367 }
1368
Douglas Gregor34e79462009-01-28 23:36:17 +00001369 if (!FinishSubobjectInit)
1370 return false;
1371
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001372 // We've already initialized something in the union; we're done.
1373 if (RT->getDecl()->isUnion())
1374 return hadError;
1375
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001376 // Check the remaining fields within this class/struct/union subobject.
1377 bool prevHadError = hadError;
Douglas Gregor4c678342009-01-28 21:54:33 +00001378 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1379 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001380 return hadError && !prevHadError;
1381 }
1382
1383 // C99 6.7.8p6:
1384 //
1385 // If a designator has the form
1386 //
1387 // [ constant-expression ]
1388 //
1389 // then the current object (defined below) shall have array
1390 // type and the expression shall be an integer constant
1391 // expression. If the array is of unknown size, any
1392 // nonnegative value is valid.
1393 //
1394 // Additionally, cope with the GNU extension that permits
1395 // designators of the form
1396 //
1397 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001398 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001399 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001400 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001401 << CurrentObjectType;
1402 ++Index;
1403 return true;
1404 }
1405
1406 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001407 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1408 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001409 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001410 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001411 DesignatedEndIndex = DesignatedStartIndex;
1412 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001413 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001414
Douglas Gregor34e79462009-01-28 23:36:17 +00001415
Chris Lattner3bf68932009-04-25 21:59:05 +00001416 DesignatedStartIndex =
1417 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
1418 DesignatedEndIndex =
1419 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001420 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001421
Chris Lattner3bf68932009-04-25 21:59:05 +00001422 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001423 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001424 }
1425
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001426 if (isa<ConstantArrayType>(AT)) {
1427 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001428 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1429 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1430 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1431 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1432 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001433 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001434 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001435 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001436 << IndexExpr->getSourceRange();
1437 ++Index;
1438 return true;
1439 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001440 } else {
1441 // Make sure the bit-widths and signedness match.
1442 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1443 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001444 else if (DesignatedStartIndex.getBitWidth() <
1445 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001446 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1447 DesignatedStartIndex.setIsUnsigned(true);
1448 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001449 }
1450
Douglas Gregor4c678342009-01-28 21:54:33 +00001451 // Make sure that our non-designated initializer list has space
1452 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001453 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001454 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001455 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001456
Douglas Gregor34e79462009-01-28 23:36:17 +00001457 // Repeatedly perform subobject initializations in the range
1458 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001459
Douglas Gregor34e79462009-01-28 23:36:17 +00001460 // Move to the next designator
1461 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1462 unsigned OldIndex = Index;
Douglas Gregor34e79462009-01-28 23:36:17 +00001463 while (DesignatedStartIndex <= DesignatedEndIndex) {
1464 // Recurse to check later designated subobjects.
1465 QualType ElementType = AT->getElementType();
1466 Index = OldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001467 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1468 Index, StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001469 (DesignatedStartIndex == DesignatedEndIndex),
1470 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001471 return true;
1472
1473 // Move to the next index in the array that we'll be initializing.
1474 ++DesignatedStartIndex;
1475 ElementIndex = DesignatedStartIndex.getZExtValue();
1476 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001477
1478 // If this the first designator, our caller will continue checking
1479 // the rest of this array subobject.
1480 if (IsFirstDesignator) {
1481 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001482 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001483 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001484 return false;
1485 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001486
1487 if (!FinishSubobjectInit)
1488 return false;
1489
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001490 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001491 bool prevHadError = hadError;
Douglas Gregorfdf55692009-02-09 19:45:19 +00001492 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001493 StructuredList, ElementIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001494 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001495}
1496
Douglas Gregor4c678342009-01-28 21:54:33 +00001497// Get the structured initializer list for a subobject of type
1498// @p CurrentObjectType.
1499InitListExpr *
1500InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1501 QualType CurrentObjectType,
1502 InitListExpr *StructuredList,
1503 unsigned StructuredIndex,
1504 SourceRange InitRange) {
1505 Expr *ExistingInit = 0;
1506 if (!StructuredList)
1507 ExistingInit = SyntacticToSemantic[IList];
1508 else if (StructuredIndex < StructuredList->getNumInits())
1509 ExistingInit = StructuredList->getInit(StructuredIndex);
1510
1511 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1512 return Result;
1513
1514 if (ExistingInit) {
1515 // We are creating an initializer list that initializes the
1516 // subobjects of the current object, but there was already an
1517 // initialization that completely initialized the current
1518 // subobject, e.g., by a compound literal:
1519 //
1520 // struct X { int a, b; };
1521 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1522 //
1523 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1524 // designated initializer re-initializes the whole
1525 // subobject [0], overwriting previous initializers.
Douglas Gregored8a93d2009-03-01 17:12:46 +00001526 SemaRef.Diag(InitRange.getBegin(),
1527 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001528 << InitRange;
Chris Lattner08202542009-02-24 22:50:46 +00001529 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001530 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001531 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001532 << ExistingInit->getSourceRange();
1533 }
1534
1535 InitListExpr *Result
Douglas Gregored8a93d2009-03-01 17:12:46 +00001536 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
1537 InitRange.getEnd());
1538
Douglas Gregor4c678342009-01-28 21:54:33 +00001539 Result->setType(CurrentObjectType);
1540
Douglas Gregorfa219202009-03-20 23:58:33 +00001541 // Pre-allocate storage for the structured initializer list.
1542 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001543 unsigned NumInits = 0;
1544 if (!StructuredList)
1545 NumInits = IList->getNumInits();
1546 else if (Index < IList->getNumInits()) {
1547 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1548 NumInits = SubList->getNumInits();
1549 }
1550
Douglas Gregorfa219202009-03-20 23:58:33 +00001551 if (const ArrayType *AType
1552 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1553 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1554 NumElements = CAType->getSize().getZExtValue();
1555 // Simple heuristic so that we don't allocate a very large
1556 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001557 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001558 NumElements = 0;
1559 }
1560 } else if (const VectorType *VType = CurrentObjectType->getAsVectorType())
1561 NumElements = VType->getNumElements();
1562 else if (const RecordType *RType = CurrentObjectType->getAsRecordType()) {
1563 RecordDecl *RDecl = RType->getDecl();
1564 if (RDecl->isUnion())
1565 NumElements = 1;
1566 else
Douglas Gregor6ab35242009-04-09 21:40:53 +00001567 NumElements = std::distance(RDecl->field_begin(SemaRef.Context),
1568 RDecl->field_end(SemaRef.Context));
Douglas Gregorfa219202009-03-20 23:58:33 +00001569 }
1570
Douglas Gregor08457732009-03-21 18:13:52 +00001571 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001572 NumElements = IList->getNumInits();
1573
1574 Result->reserveInits(NumElements);
1575
Douglas Gregor4c678342009-01-28 21:54:33 +00001576 // Link this new initializer list into the structured initializer
1577 // lists.
1578 if (StructuredList)
1579 StructuredList->updateInit(StructuredIndex, Result);
1580 else {
1581 Result->setSyntacticForm(IList);
1582 SyntacticToSemantic[IList] = Result;
1583 }
1584
1585 return Result;
1586}
1587
1588/// Update the initializer at index @p StructuredIndex within the
1589/// structured initializer list to the value @p expr.
1590void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1591 unsigned &StructuredIndex,
1592 Expr *expr) {
1593 // No structured initializer list to update
1594 if (!StructuredList)
1595 return;
1596
1597 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1598 // This initializer overwrites a previous initializer. Warn.
Chris Lattner08202542009-02-24 22:50:46 +00001599 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001600 diag::warn_initializer_overrides)
1601 << expr->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001602 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001603 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001604 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001605 << PrevInit->getSourceRange();
1606 }
1607
1608 ++StructuredIndex;
1609}
1610
Douglas Gregor05c13a32009-01-22 00:58:24 +00001611/// Check that the given Index expression is a valid array designator
1612/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001613/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001614/// and produces a reasonable diagnostic if there is a
1615/// failure. Returns true if there was an error, false otherwise. If
1616/// everything went okay, Value will receive the value of the constant
1617/// expression.
1618static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001619CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001620 SourceLocation Loc = Index->getSourceRange().getBegin();
1621
1622 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001623 if (S.VerifyIntegerConstantExpression(Index, &Value))
1624 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001625
Chris Lattner3bf68932009-04-25 21:59:05 +00001626 if (Value.isSigned() && Value.isNegative())
1627 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001628 << Value.toString(10) << Index->getSourceRange();
1629
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001630 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001631 return false;
1632}
1633
1634Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1635 SourceLocation Loc,
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001636 bool GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001637 OwningExprResult Init) {
1638 typedef DesignatedInitExpr::Designator ASTDesignator;
1639
1640 bool Invalid = false;
1641 llvm::SmallVector<ASTDesignator, 32> Designators;
1642 llvm::SmallVector<Expr *, 32> InitExpressions;
1643
1644 // Build designators and check array designator expressions.
1645 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1646 const Designator &D = Desig.getDesignator(Idx);
1647 switch (D.getKind()) {
1648 case Designator::FieldDesignator:
1649 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1650 D.getFieldLoc()));
1651 break;
1652
1653 case Designator::ArrayDesignator: {
1654 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1655 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001656 if (!Index->isTypeDependent() &&
1657 !Index->isValueDependent() &&
1658 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001659 Invalid = true;
1660 else {
1661 Designators.push_back(ASTDesignator(InitExpressions.size(),
1662 D.getLBracketLoc(),
1663 D.getRBracketLoc()));
1664 InitExpressions.push_back(Index);
1665 }
1666 break;
1667 }
1668
1669 case Designator::ArrayRangeDesignator: {
1670 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1671 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1672 llvm::APSInt StartValue;
1673 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001674 bool StartDependent = StartIndex->isTypeDependent() ||
1675 StartIndex->isValueDependent();
1676 bool EndDependent = EndIndex->isTypeDependent() ||
1677 EndIndex->isValueDependent();
1678 if ((!StartDependent &&
1679 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1680 (!EndDependent &&
1681 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001682 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001683 else {
1684 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001685 if (StartDependent || EndDependent) {
1686 // Nothing to compute.
1687 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregord6f584f2009-01-23 22:22:29 +00001688 EndValue.extend(StartValue.getBitWidth());
1689 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1690 StartValue.extend(EndValue.getBitWidth());
1691
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001692 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001693 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1694 << StartValue.toString(10) << EndValue.toString(10)
1695 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1696 Invalid = true;
1697 } else {
1698 Designators.push_back(ASTDesignator(InitExpressions.size(),
1699 D.getLBracketLoc(),
1700 D.getEllipsisLoc(),
1701 D.getRBracketLoc()));
1702 InitExpressions.push_back(StartIndex);
1703 InitExpressions.push_back(EndIndex);
1704 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001705 }
1706 break;
1707 }
1708 }
1709 }
1710
1711 if (Invalid || Init.isInvalid())
1712 return ExprError();
1713
1714 // Clear out the expressions within the designation.
1715 Desig.ClearExprs(*this);
1716
1717 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001718 = DesignatedInitExpr::Create(Context,
1719 Designators.data(), Designators.size(),
1720 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001721 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001722 return Owned(DIE);
1723}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001724
1725bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
Chris Lattner08202542009-02-24 22:50:46 +00001726 InitListChecker CheckInitList(*this, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001727 if (!CheckInitList.HadError())
1728 InitList = CheckInitList.getFullyStructuredList();
1729
1730 return CheckInitList.HadError();
1731}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001732
1733/// \brief Diagnose any semantic errors with value-initialization of
1734/// the given type.
1735///
1736/// Value-initialization effectively zero-initializes any types
1737/// without user-declared constructors, and calls the default
1738/// constructor for a for any type that has a user-declared
1739/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1740/// a type with a user-declared constructor does not have an
1741/// accessible, non-deleted default constructor. In C, everything can
1742/// be value-initialized, which corresponds to C's notion of
1743/// initializing objects with static storage duration when no
1744/// initializer is provided for that object.
1745///
1746/// \returns true if there was an error, false otherwise.
1747bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1748 // C++ [dcl.init]p5:
1749 //
1750 // To value-initialize an object of type T means:
1751
1752 // -- if T is an array type, then each element is value-initialized;
1753 if (const ArrayType *AT = Context.getAsArrayType(Type))
1754 return CheckValueInitialization(AT->getElementType(), Loc);
1755
1756 if (const RecordType *RT = Type->getAsRecordType()) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001757 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Douglas Gregor87fd7032009-02-02 17:43:21 +00001758 // -- if T is a class type (clause 9) with a user-declared
1759 // constructor (12.1), then the default constructor for T is
1760 // called (and the initialization is ill-formed if T has no
1761 // accessible default constructor);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001762 if (ClassDecl->hasUserDeclaredConstructor())
Mike Stump390b4cc2009-05-16 07:39:55 +00001763 // FIXME: Eventually, we'll need to put the constructor decl into the
1764 // AST.
Douglas Gregor87fd7032009-02-02 17:43:21 +00001765 return PerformInitializationByConstructor(Type, 0, 0, Loc,
1766 SourceRange(Loc),
1767 DeclarationName(),
1768 IK_Direct);
1769 }
1770 }
1771
1772 if (Type->isReferenceType()) {
1773 // C++ [dcl.init]p5:
1774 // [...] A program that calls for default-initialization or
1775 // value-initialization of an entity of reference type is
1776 // ill-formed. [...]
Mike Stump390b4cc2009-05-16 07:39:55 +00001777 // FIXME: Once we have code that goes through this path, add an actual
1778 // diagnostic :)
Douglas Gregor87fd7032009-02-02 17:43:21 +00001779 }
1780
1781 return false;
1782}