blob: 45085962d488a6e588d28d6cd20ebfb2c0f70da6 [file] [log] [blame]
Steve Naroffc4d4a482008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerd3a00502009-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 Lattnere76e9bf2009-02-24 22:48:58 +000014// This file also implements Sema::CheckInitializerTypes.
Steve Naroffc4d4a482008-05-01 22:18:59 +000015//
16//===----------------------------------------------------------------------===//
17
18#include "Sema.h"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +000019#include "clang/Parse/Designator.h"
Steve Naroffc4d4a482008-05-01 22:18:59 +000020#include "clang/AST/ASTContext.h"
Anders Carlsson73bb5e62009-05-27 16:10:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattner19ae2fc2009-02-24 23:10:27 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregor849afc32009-01-29 00:45:39 +000023#include <map>
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +000024using namespace clang;
Steve Naroffc4d4a482008-05-01 22:18:59 +000025
Chris Lattnerd3a00502009-02-24 22:27:37 +000026//===----------------------------------------------------------------------===//
27// Sema Initialization Checking
28//===----------------------------------------------------------------------===//
29
Chris Lattner19ae2fc2009-02-24 23:10:27 +000030static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattner7a7c1452009-02-26 23:26:43 +000031 const ArrayType *AT = Context.getAsArrayType(DeclType);
32 if (!AT) return 0;
33
Eli Friedman95acf982009-05-29 18:22:49 +000034 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
35 return 0;
36
Chris Lattner7a7c1452009-02-26 23:26:43 +000037 // See if this is a string literal or @encode.
38 Init = Init->IgnoreParens();
39
40 // Handle @encode, which is a narrow string.
41 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
42 return Init;
43
44 // Otherwise we can only handle string literals.
45 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattnerff065f72009-02-26 23:42:47 +000046 if (SL == 0) return 0;
Eli Friedmand16b0892009-05-31 10:54:53 +000047
48 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattner7a7c1452009-02-26 23:26:43 +000049 // char array can be initialized with a narrow string.
50 // Only allow char x[] = "foo"; not char x[] = L"foo";
51 if (!SL->isWide())
Eli Friedmand16b0892009-05-31 10:54:53 +000052 return ElemTy->isCharType() ? Init : 0;
Chris Lattner7a7c1452009-02-26 23:26:43 +000053
Eli Friedmand16b0892009-05-31 10:54:53 +000054 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
55 // correction from DR343): "An array with element type compatible with a
56 // qualified or unqualified version of wchar_t may be initialized by a wide
57 // string literal, optionally enclosed in braces."
58 if (Context.typesAreCompatible(Context.getWCharType(),
59 ElemTy.getUnqualifiedType()))
Chris Lattner7a7c1452009-02-26 23:26:43 +000060 return Init;
61
Chris Lattnerd3a00502009-02-24 22:27:37 +000062 return 0;
63}
64
Chris Lattner160da072009-02-24 22:46:58 +000065static bool CheckSingleInitializer(Expr *&Init, QualType DeclType,
66 bool DirectInit, Sema &S) {
Chris Lattnerd3a00502009-02-24 22:27:37 +000067 // Get the type before calling CheckSingleAssignmentConstraints(), since
68 // it can promote the expression.
69 QualType InitType = Init->getType();
70
Chris Lattner160da072009-02-24 22:46:58 +000071 if (S.getLangOptions().CPlusPlus) {
Chris Lattnerd3a00502009-02-24 22:27:37 +000072 // FIXME: I dislike this error message. A lot.
Chris Lattner160da072009-02-24 22:46:58 +000073 if (S.PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
74 return S.Diag(Init->getSourceRange().getBegin(),
75 diag::err_typecheck_convert_incompatible)
76 << DeclType << Init->getType() << "initializing"
77 << Init->getSourceRange();
Chris Lattnerd3a00502009-02-24 22:27:37 +000078 return false;
79 }
80
Chris Lattner160da072009-02-24 22:46:58 +000081 Sema::AssignConvertType ConvTy =
82 S.CheckSingleAssignmentConstraints(DeclType, Init);
83 return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
Chris Lattnerd3a00502009-02-24 22:27:37 +000084 InitType, Init, "initializing");
85}
86
Chris Lattner19ae2fc2009-02-24 23:10:27 +000087static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
88 // Get the length of the string as parsed.
89 uint64_t StrLength =
90 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
91
Chris Lattnerd3a00502009-02-24 22:27:37 +000092
Chris Lattner19ae2fc2009-02-24 23:10:27 +000093 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerd3a00502009-02-24 22:27:37 +000094 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
95 // C99 6.7.8p14. We have an array of character type with unknown size
96 // being initialized to a string literal.
97 llvm::APSInt ConstVal(32);
Chris Lattnerd20fac42009-02-24 23:01:39 +000098 ConstVal = StrLength;
Chris Lattnerd3a00502009-02-24 22:27:37 +000099 // Return a new array type (C99 6.7.8p22).
Chris Lattner45d6fd62009-02-24 22:41:04 +0000100 DeclT = S.Context.getConstantArrayType(IAT->getElementType(), ConstVal,
101 ArrayType::Normal, 0);
Chris Lattnerd20fac42009-02-24 23:01:39 +0000102 return;
Chris Lattnerd3a00502009-02-24 22:27:37 +0000103 }
Chris Lattnerd20fac42009-02-24 23:01:39 +0000104
Eli Friedman95acf982009-05-29 18:22:49 +0000105 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
106
107 // C99 6.7.8p14. We have an array of character type with known size. However,
108 // the size may be smaller or larger than the string we are initializing.
109 // FIXME: Avoid truncation for 64-bit length strings.
110 if (StrLength-1 > CAT->getSize().getZExtValue())
111 S.Diag(Str->getSourceRange().getBegin(),
112 diag::warn_initializer_string_for_char_array_too_long)
113 << Str->getSourceRange();
114
115 // Set the type to the actual size that we are initializing. If we have
116 // something like:
117 // char x[1] = "foo";
118 // then this will set the string literal's type to char[1].
119 Str->setType(DeclT);
Chris Lattnerd3a00502009-02-24 22:27:37 +0000120}
121
122bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
123 SourceLocation InitLoc,
Anders Carlsson8cc1f0d2009-05-30 20:41:30 +0000124 DeclarationName InitEntity, bool DirectInit) {
Douglas Gregor3a7a06e2009-05-21 23:17:49 +0000125 if (DeclType->isDependentType() ||
126 Init->isTypeDependent() || Init->isValueDependent())
Chris Lattnerd3a00502009-02-24 22:27:37 +0000127 return false;
128
129 // C++ [dcl.init.ref]p1:
Sebastian Redlce6fff02009-03-16 23:22:08 +0000130 // A variable declared to be a T& or T&&, that is "reference to type T"
Chris Lattnerd3a00502009-02-24 22:27:37 +0000131 // (8.3.2), shall be initialized by an object, or function, of
132 // type T or by an object that can be converted into a T.
133 if (DeclType->isReferenceType())
134 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
135
136 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
137 // of unknown size ("[]") or an object type that is not a variable array type.
138 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
139 return Diag(InitLoc, diag::err_variable_object_no_init)
140 << VAT->getSizeExpr()->getSourceRange();
141
142 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
143 if (!InitList) {
144 // FIXME: Handle wide strings
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000145 if (Expr *Str = IsStringInit(Init, DeclType, Context)) {
146 CheckStringInit(Str, DeclType, *this);
Chris Lattnerd20fac42009-02-24 23:01:39 +0000147 return false;
148 }
Chris Lattnerd3a00502009-02-24 22:27:37 +0000149
150 // C++ [dcl.init]p14:
151 // -- If the destination type is a (possibly cv-qualified) class
152 // type:
153 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
154 QualType DeclTypeC = Context.getCanonicalType(DeclType);
155 QualType InitTypeC = Context.getCanonicalType(Init->getType());
156
157 // -- If the initialization is direct-initialization, or if it is
158 // copy-initialization where the cv-unqualified version of the
159 // source type is the same class as, or a derived class of, the
160 // class of the destination, constructors are considered.
161 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
162 IsDerivedFrom(InitTypeC, DeclTypeC)) {
Anders Carlsson5868dfc2009-05-27 16:38:58 +0000163 const CXXRecordDecl *RD =
164 cast<CXXRecordDecl>(DeclType->getAsRecordType()->getDecl());
165
166 // No need to make a CXXConstructExpr if both the ctor and dtor are
167 // trivial.
168 if (RD->hasTrivialConstructor() && RD->hasTrivialDestructor())
169 return false;
170
Chris Lattnerd3a00502009-02-24 22:27:37 +0000171 CXXConstructorDecl *Constructor
172 = PerformInitializationByConstructor(DeclType, &Init, 1,
173 InitLoc, Init->getSourceRange(),
174 InitEntity,
175 DirectInit? IK_Direct : IK_Copy);
Anders Carlsson73bb5e62009-05-27 16:10:08 +0000176 if (!Constructor)
177 return true;
178
Anders Carlsson7b7b2552009-05-30 20:56:46 +0000179 Init = CXXConstructExpr::Create(Context, DeclType, Constructor, false,
180 &Init, 1);
Anders Carlsson73bb5e62009-05-27 16:10:08 +0000181 return false;
Chris Lattnerd3a00502009-02-24 22:27:37 +0000182 }
183
184 // -- Otherwise (i.e., for the remaining copy-initialization
185 // cases), user-defined conversion sequences that can
186 // convert from the source type to the destination type or
187 // (when a conversion function is used) to a derived class
188 // thereof are enumerated as described in 13.3.1.4, and the
189 // best one is chosen through overload resolution
190 // (13.3). If the conversion cannot be done or is
191 // ambiguous, the initialization is ill-formed. The
192 // function selected is called with the initializer
193 // expression as its argument; if the function is a
194 // constructor, the call initializes a temporary of the
195 // destination type.
Mike Stumpe127ae32009-05-16 07:39:55 +0000196 // FIXME: We're pretending to do copy elision here; return to this when we
197 // have ASTs for such things.
Chris Lattnerd3a00502009-02-24 22:27:37 +0000198 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
199 return false;
200
201 if (InitEntity)
202 return Diag(InitLoc, diag::err_cannot_initialize_decl)
203 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
204 << Init->getType() << Init->getSourceRange();
205 else
206 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
207 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
208 << Init->getType() << Init->getSourceRange();
209 }
210
211 // C99 6.7.8p16.
212 if (DeclType->isArrayType())
213 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
214 << Init->getSourceRange();
215
Chris Lattner160da072009-02-24 22:46:58 +0000216 return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
Chris Lattnerd3a00502009-02-24 22:27:37 +0000217 }
218
219 bool hadError = CheckInitList(InitList, DeclType);
220 Init = InitList;
221 return hadError;
222}
223
224//===----------------------------------------------------------------------===//
225// Semantic checking for initializer lists.
226//===----------------------------------------------------------------------===//
227
Douglas Gregoraaa20962009-01-29 01:05:33 +0000228/// @brief Semantic checking for initializer lists.
229///
230/// The InitListChecker class contains a set of routines that each
231/// handle the initialization of a certain kind of entity, e.g.,
232/// arrays, vectors, struct/union types, scalars, etc. The
233/// InitListChecker itself performs a recursive walk of the subobject
234/// structure of the type to be initialized, while stepping through
235/// the initializer list one element at a time. The IList and Index
236/// parameters to each of the Check* routines contain the active
237/// (syntactic) initializer list and the index into that initializer
238/// list that represents the current initializer. Each routine is
239/// responsible for moving that Index forward as it consumes elements.
240///
241/// Each Check* routine also has a StructuredList/StructuredIndex
242/// arguments, which contains the current the "structured" (semantic)
243/// initializer list and the index into that initializer list where we
244/// are copying initializers as we map them over to the semantic
245/// list. Once we have completed our recursive walk of the subobject
246/// structure, we will have constructed a full semantic initializer
247/// list.
248///
249/// C99 designators cause changes in the initializer list traversal,
250/// because they make the initialization "jump" into a specific
251/// subobject and then continue the initialization from that
252/// point. CheckDesignatedInitializer() recursively steps into the
253/// designated subobject and manages backing out the recursion to
254/// initialize the subobjects after the one designated.
Chris Lattnere76e9bf2009-02-24 22:48:58 +0000255namespace {
Douglas Gregor849afc32009-01-29 00:45:39 +0000256class InitListChecker {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000257 Sema &SemaRef;
Douglas Gregor849afc32009-01-29 00:45:39 +0000258 bool hadError;
259 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
260 InitListExpr *FullyStructuredList;
261
262 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000263 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000264 unsigned &StructuredIndex,
265 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000266 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000267 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000268 unsigned &StructuredIndex,
269 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000270 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
271 bool SubobjectIsDesignatorContext,
272 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000273 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000274 unsigned &StructuredIndex,
275 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000276 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
277 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000278 InitListExpr *StructuredList,
279 unsigned &StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000280 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor849afc32009-01-29 00:45:39 +0000281 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000282 InitListExpr *StructuredList,
283 unsigned &StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000284 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
285 unsigned &Index,
286 InitListExpr *StructuredList,
287 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000288 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000289 InitListExpr *StructuredList,
290 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000291 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
292 RecordDecl::field_iterator Field,
293 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000294 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000295 unsigned &StructuredIndex,
296 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000297 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
298 llvm::APSInt elementIndex,
299 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000300 InitListExpr *StructuredList,
301 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000302 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregoraa357272009-04-15 04:56:10 +0000303 unsigned DesigIdx,
Douglas Gregor849afc32009-01-29 00:45:39 +0000304 QualType &CurrentObjectType,
305 RecordDecl::field_iterator *NextField,
306 llvm::APSInt *NextElementIndex,
307 unsigned &Index,
308 InitListExpr *StructuredList,
309 unsigned &StructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000310 bool FinishSubobjectInit,
311 bool TopLevelObject);
Douglas Gregor849afc32009-01-29 00:45:39 +0000312 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
313 QualType CurrentObjectType,
314 InitListExpr *StructuredList,
315 unsigned StructuredIndex,
316 SourceRange InitRange);
Douglas Gregoraaa20962009-01-29 01:05:33 +0000317 void UpdateStructuredListElement(InitListExpr *StructuredList,
318 unsigned &StructuredIndex,
Douglas Gregor849afc32009-01-29 00:45:39 +0000319 Expr *expr);
320 int numArrayElements(QualType DeclType);
321 int numStructUnionElements(QualType DeclType);
Douglas Gregord45210d2009-01-30 22:09:00 +0000322
323 void FillInValueInitializations(InitListExpr *ILE);
Douglas Gregor849afc32009-01-29 00:45:39 +0000324public:
Chris Lattner2e2766a2009-02-24 22:50:46 +0000325 InitListChecker(Sema &S, InitListExpr *IL, QualType &T);
Douglas Gregor849afc32009-01-29 00:45:39 +0000326 bool HadError() { return hadError; }
327
328 // @brief Retrieves the fully-structured initializer list used for
329 // semantic analysis and code generation.
330 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
331};
Chris Lattnere76e9bf2009-02-24 22:48:58 +0000332} // end anonymous namespace
Chris Lattner1aa25a72009-01-29 05:10:57 +0000333
Douglas Gregorf603b472009-01-28 21:54:33 +0000334/// Recursively replaces NULL values within the given initializer list
335/// with expressions that perform value-initialization of the
336/// appropriate type.
Douglas Gregord45210d2009-01-30 22:09:00 +0000337void InitListChecker::FillInValueInitializations(InitListExpr *ILE) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000338 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord45210d2009-01-30 22:09:00 +0000339 "Should not have void type");
Douglas Gregor538a4c22009-02-02 17:43:21 +0000340 SourceLocation Loc = ILE->getSourceRange().getBegin();
341 if (ILE->getSyntacticForm())
342 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
343
Douglas Gregorf603b472009-01-28 21:54:33 +0000344 if (const RecordType *RType = ILE->getType()->getAsRecordType()) {
345 unsigned Init = 0, NumInits = ILE->getNumInits();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000346 for (RecordDecl::field_iterator
347 Field = RType->getDecl()->field_begin(SemaRef.Context),
348 FieldEnd = RType->getDecl()->field_end(SemaRef.Context);
Douglas Gregorf603b472009-01-28 21:54:33 +0000349 Field != FieldEnd; ++Field) {
350 if (Field->isUnnamedBitfield())
351 continue;
352
Douglas Gregor538a4c22009-02-02 17:43:21 +0000353 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000354 if (Field->getType()->isReferenceType()) {
355 // C++ [dcl.init.aggr]p9:
356 // If an incomplete or empty initializer-list leaves a
357 // member of reference type uninitialized, the program is
358 // ill-formed.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000359 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregord45210d2009-01-30 22:09:00 +0000360 << Field->getType()
361 << ILE->getSyntacticForm()->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +0000362 SemaRef.Diag(Field->getLocation(),
Douglas Gregord45210d2009-01-30 22:09:00 +0000363 diag::note_uninit_reference_member);
364 hadError = true;
Douglas Gregor538a4c22009-02-02 17:43:21 +0000365 return;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000366 } else if (SemaRef.CheckValueInitialization(Field->getType(), Loc)) {
Douglas Gregor538a4c22009-02-02 17:43:21 +0000367 hadError = true;
368 return;
Douglas Gregord45210d2009-01-30 22:09:00 +0000369 }
Douglas Gregor538a4c22009-02-02 17:43:21 +0000370
Mike Stumpe127ae32009-05-16 07:39:55 +0000371 // FIXME: If value-initialization involves calling a constructor, should
372 // we make that call explicit in the representation (even when it means
373 // extending the initializer list)?
Douglas Gregor538a4c22009-02-02 17:43:21 +0000374 if (Init < NumInits && !hadError)
375 ILE->setInit(Init,
Chris Lattner2e2766a2009-02-24 22:50:46 +0000376 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()));
Douglas Gregor538a4c22009-02-02 17:43:21 +0000377 } else if (InitListExpr *InnerILE
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000378 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregord45210d2009-01-30 22:09:00 +0000379 FillInValueInitializations(InnerILE);
Douglas Gregorf603b472009-01-28 21:54:33 +0000380 ++Init;
Douglas Gregord45210d2009-01-30 22:09:00 +0000381
382 // Only look at the first initialization of a union.
383 if (RType->getDecl()->isUnion())
384 break;
Douglas Gregorf603b472009-01-28 21:54:33 +0000385 }
386
387 return;
388 }
389
390 QualType ElementType;
391
Douglas Gregor538a4c22009-02-02 17:43:21 +0000392 unsigned NumInits = ILE->getNumInits();
393 unsigned NumElements = NumInits;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000394 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000395 ElementType = AType->getElementType();
Douglas Gregor538a4c22009-02-02 17:43:21 +0000396 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
397 NumElements = CAType->getSize().getZExtValue();
398 } else if (const VectorType *VType = ILE->getType()->getAsVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000399 ElementType = VType->getElementType();
Douglas Gregor538a4c22009-02-02 17:43:21 +0000400 NumElements = VType->getNumElements();
401 } else
Douglas Gregorf603b472009-01-28 21:54:33 +0000402 ElementType = ILE->getType();
403
Douglas Gregor538a4c22009-02-02 17:43:21 +0000404 for (unsigned Init = 0; Init != NumElements; ++Init) {
405 if (Init >= NumInits || !ILE->getInit(Init)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000406 if (SemaRef.CheckValueInitialization(ElementType, Loc)) {
Douglas Gregor538a4c22009-02-02 17:43:21 +0000407 hadError = true;
408 return;
409 }
410
Mike Stumpe127ae32009-05-16 07:39:55 +0000411 // FIXME: If value-initialization involves calling a constructor, should
412 // we make that call explicit in the representation (even when it means
413 // extending the initializer list)?
Douglas Gregor538a4c22009-02-02 17:43:21 +0000414 if (Init < NumInits && !hadError)
415 ILE->setInit(Init,
Chris Lattner2e2766a2009-02-24 22:50:46 +0000416 new (SemaRef.Context) ImplicitValueInitExpr(ElementType));
Douglas Gregor538a4c22009-02-02 17:43:21 +0000417 }
Chris Lattner1aa25a72009-01-29 05:10:57 +0000418 else if (InitListExpr *InnerILE =dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregord45210d2009-01-30 22:09:00 +0000419 FillInValueInitializations(InnerILE);
Douglas Gregorf603b472009-01-28 21:54:33 +0000420 }
421}
422
Chris Lattner1aa25a72009-01-29 05:10:57 +0000423
Chris Lattner2e2766a2009-02-24 22:50:46 +0000424InitListChecker::InitListChecker(Sema &S, InitListExpr *IL, QualType &T)
425 : SemaRef(S) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000426 hadError = false;
Eli Friedmand8535af2008-05-19 20:00:43 +0000427
Eli Friedman683cedf2008-05-19 19:16:24 +0000428 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000429 unsigned newStructuredIndex = 0;
430 FullyStructuredList
Douglas Gregorea765e12009-03-01 17:12:46 +0000431 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregorbe69b162009-02-04 22:46:25 +0000432 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
433 /*TopLevelObject=*/true);
Eli Friedmand8535af2008-05-19 20:00:43 +0000434
Douglas Gregord45210d2009-01-30 22:09:00 +0000435 if (!hadError)
436 FillInValueInitializations(FullyStructuredList);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000437}
438
439int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman46f81662008-05-25 13:22:35 +0000440 // FIXME: use a proper constant
441 int maxElements = 0x7FFFFFFF;
Chris Lattnera1923f62008-08-04 07:31:14 +0000442 if (const ConstantArrayType *CAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000443 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000444 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
445 }
446 return maxElements;
447}
448
449int InitListChecker::numStructUnionElements(QualType DeclType) {
450 RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl();
Douglas Gregorf603b472009-01-28 21:54:33 +0000451 int InitializableMembers = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000452 for (RecordDecl::field_iterator
453 Field = structDecl->field_begin(SemaRef.Context),
454 FieldEnd = structDecl->field_end(SemaRef.Context);
Douglas Gregorf603b472009-01-28 21:54:33 +0000455 Field != FieldEnd; ++Field) {
456 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
457 ++InitializableMembers;
458 }
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000459 if (structDecl->isUnion())
Eli Friedman9f5250b2008-05-25 14:03:31 +0000460 return std::min(InitializableMembers, 1);
461 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000462}
463
464void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregorf603b472009-01-28 21:54:33 +0000465 QualType T, unsigned &Index,
466 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000467 unsigned &StructuredIndex,
468 bool TopLevelObject) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000469 int maxElements = 0;
470
471 if (T->isArrayType())
472 maxElements = numArrayElements(T);
473 else if (T->isStructureType() || T->isUnionType())
474 maxElements = numStructUnionElements(T);
Eli Friedman683cedf2008-05-19 19:16:24 +0000475 else if (T->isVectorType())
476 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000477 else
478 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman683cedf2008-05-19 19:16:24 +0000479
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000480 if (maxElements == 0) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000481 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000482 diag::err_implicit_empty_initializer);
Douglas Gregorf603b472009-01-28 21:54:33 +0000483 ++Index;
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000484 hadError = true;
485 return;
486 }
487
Douglas Gregorf603b472009-01-28 21:54:33 +0000488 // Build a structured initializer list corresponding to this subobject.
489 InitListExpr *StructuredSubobjectInitList
490 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
491 StructuredIndex,
Douglas Gregorea765e12009-03-01 17:12:46 +0000492 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
493 ParentIList->getSourceRange().getEnd()));
Douglas Gregorf603b472009-01-28 21:54:33 +0000494 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman683cedf2008-05-19 19:16:24 +0000495
Douglas Gregorf603b472009-01-28 21:54:33 +0000496 // Check the element types and build the structural subobject.
Douglas Gregor538a4c22009-02-02 17:43:21 +0000497 unsigned StartIndex = Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000498 CheckListElementTypes(ParentIList, T, false, Index,
499 StructuredSubobjectInitList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000500 StructuredSubobjectInitIndex,
501 TopLevelObject);
Douglas Gregor538a4c22009-02-02 17:43:21 +0000502 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregorcd2c5272009-03-20 00:32:56 +0000503 StructuredSubobjectInitList->setType(T);
504
Douglas Gregorea765e12009-03-01 17:12:46 +0000505 // Update the structured sub-object initializer so that it's ending
Douglas Gregor538a4c22009-02-02 17:43:21 +0000506 // range corresponds with the end of the last initializer it used.
507 if (EndIndex < ParentIList->getNumInits()) {
508 SourceLocation EndLoc
509 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
510 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
511 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000512}
513
Steve Naroff56099522008-05-06 00:23:44 +0000514void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregorf603b472009-01-28 21:54:33 +0000515 unsigned &Index,
516 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000517 unsigned &StructuredIndex,
518 bool TopLevelObject) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000519 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregorf603b472009-01-28 21:54:33 +0000520 SyntacticToSemantic[IList] = StructuredList;
521 StructuredList->setSyntacticForm(IList);
522 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000523 StructuredIndex, TopLevelObject);
Steve Naroff56099522008-05-06 00:23:44 +0000524 IList->setType(T);
Douglas Gregorf603b472009-01-28 21:54:33 +0000525 StructuredList->setType(T);
Eli Friedman46f81662008-05-25 13:22:35 +0000526 if (hadError)
527 return;
Eli Friedmand8535af2008-05-19 20:00:43 +0000528
Eli Friedman46f81662008-05-25 13:22:35 +0000529 if (Index < IList->getNumInits()) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000530 // We have leftover initializers
Eli Friedman579534a2009-05-29 20:20:05 +0000531 if (StructuredIndex == 1 &&
532 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000533 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedman579534a2009-05-29 20:20:05 +0000534 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000535 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedman579534a2009-05-29 20:20:05 +0000536 hadError = true;
537 }
Eli Friedman71de9eb2008-05-19 20:12:18 +0000538 // Special-case
Chris Lattner2e2766a2009-02-24 22:50:46 +0000539 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattner9d2cf082008-11-19 05:27:50 +0000540 << IList->getInit(Index)->getSourceRange();
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000541 } else if (!T->isIncompleteType()) {
Douglas Gregor09f078c2009-01-30 22:26:29 +0000542 // Don't complain for incomplete types, since we'll get an error
543 // elsewhere
Douglas Gregorbe69b162009-02-04 22:46:25 +0000544 QualType CurrentObjectType = StructuredList->getType();
545 int initKind =
546 CurrentObjectType->isArrayType()? 0 :
547 CurrentObjectType->isVectorType()? 1 :
548 CurrentObjectType->isScalarType()? 2 :
549 CurrentObjectType->isUnionType()? 3 :
550 4;
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000551
552 unsigned DK = diag::warn_excess_initializers;
Eli Friedman579534a2009-05-29 20:20:05 +0000553 if (SemaRef.getLangOptions().CPlusPlus) {
554 DK = diag::err_excess_initializers;
555 hadError = true;
556 }
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000557
Chris Lattner2e2766a2009-02-24 22:50:46 +0000558 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorbe69b162009-02-04 22:46:25 +0000559 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000560 }
561 }
Eli Friedman455f7622008-05-19 20:20:43 +0000562
Eli Friedman90bcb892009-05-16 11:45:48 +0000563 if (T->isScalarType() && !TopLevelObject)
Chris Lattner2e2766a2009-02-24 22:50:46 +0000564 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor3faaa812009-04-01 23:51:29 +0000565 << IList->getSourceRange()
566 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocStart()))
567 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocEnd()));
Steve Naroffc4d4a482008-05-01 22:18:59 +0000568}
569
Eli Friedman683cedf2008-05-19 19:16:24 +0000570void InitListChecker::CheckListElementTypes(InitListExpr *IList,
571 QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000572 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000573 unsigned &Index,
574 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000575 unsigned &StructuredIndex,
576 bool TopLevelObject) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000577 if (DeclType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000578 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000579 } else if (DeclType->isVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000580 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregore7ef5002009-01-30 17:31:00 +0000581 } else if (DeclType->isAggregateType()) {
582 if (DeclType->isRecordType()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000583 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000584 CheckStructUnionTypes(IList, DeclType, RD->field_begin(SemaRef.Context),
Douglas Gregorf603b472009-01-28 21:54:33 +0000585 SubobjectIsDesignatorContext, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000586 StructuredList, StructuredIndex,
587 TopLevelObject);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000588 } else if (DeclType->isArrayType()) {
Douglas Gregor5a203a62009-01-23 16:54:12 +0000589 llvm::APSInt Zero(
Chris Lattner2e2766a2009-02-24 22:50:46 +0000590 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor5a203a62009-01-23 16:54:12 +0000591 false);
Douglas Gregorf603b472009-01-28 21:54:33 +0000592 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
593 StructuredList, StructuredIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000594 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000595 else
Douglas Gregorf603b472009-01-28 21:54:33 +0000596 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffff5b3a82008-08-10 16:05:48 +0000597 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
598 // This type is invalid, issue a diagnostic.
Douglas Gregorf603b472009-01-28 21:54:33 +0000599 ++Index;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000600 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000601 << DeclType;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000602 hadError = true;
Douglas Gregord45210d2009-01-30 22:09:00 +0000603 } else if (DeclType->isRecordType()) {
604 // C++ [dcl.init]p14:
605 // [...] If the class is an aggregate (8.5.1), and the initializer
606 // is a brace-enclosed list, see 8.5.1.
607 //
608 // Note: 8.5.1 is handled below; here, we diagnose the case where
609 // we have an initializer list and a destination type that is not
610 // an aggregate.
611 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000612 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord45210d2009-01-30 22:09:00 +0000613 << DeclType << IList->getSourceRange();
614 hadError = true;
615 } else if (DeclType->isReferenceType()) {
616 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000617 } else {
618 // In C, all types are either scalars or aggregates, but
619 // additional handling is needed here for C++ (and possibly others?).
620 assert(0 && "Unsupported initializer type");
621 }
622}
623
Eli Friedman683cedf2008-05-19 19:16:24 +0000624void InitListChecker::CheckSubElementType(InitListExpr *IList,
625 QualType ElemType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000626 unsigned &Index,
627 InitListExpr *StructuredList,
628 unsigned &StructuredIndex) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000629 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000630 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
631 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000632 unsigned newStructuredIndex = 0;
633 InitListExpr *newStructuredList
634 = getStructuredSubobjectInit(IList, Index, ElemType,
635 StructuredList, StructuredIndex,
636 SubInitList->getSourceRange());
637 CheckExplicitInitList(SubInitList, ElemType, newIndex,
638 newStructuredList, newStructuredIndex);
639 ++StructuredIndex;
640 ++Index;
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000641 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
642 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattner45d6fd62009-02-24 22:41:04 +0000643 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregorf603b472009-01-28 21:54:33 +0000644 ++Index;
Eli Friedmand8535af2008-05-19 20:00:43 +0000645 } else if (ElemType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000646 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000647 } else if (ElemType->isReferenceType()) {
648 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedman683cedf2008-05-19 19:16:24 +0000649 } else {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000650 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000651 // C++ [dcl.init.aggr]p12:
652 // All implicit type conversions (clause 4) are considered when
653 // initializing the aggregate member with an ini- tializer from
654 // an initializer-list. If the initializer can initialize a
655 // member, the member is initialized. [...]
656 ImplicitConversionSequence ICS
Chris Lattner2e2766a2009-02-24 22:50:46 +0000657 = SemaRef.TryCopyInitialization(expr, ElemType);
Douglas Gregord45210d2009-01-30 22:09:00 +0000658 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000659 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregord45210d2009-01-30 22:09:00 +0000660 "initializing"))
661 hadError = true;
662 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
663 ++Index;
664 return;
665 }
666
667 // Fall through for subaggregate initialization
668 } else {
669 // C99 6.7.8p13:
670 //
671 // The initializer for a structure or union object that has
672 // automatic storage duration shall be either an initializer
673 // list as described below, or a single expression that has
674 // compatible structure or union type. In the latter case, the
675 // initial value of the object, including unnamed members, is
676 // that of the expression.
Eli Friedman2a553812009-06-13 10:38:46 +0000677 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman95acf982009-05-29 18:22:49 +0000678 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000679 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
680 ++Index;
681 return;
682 }
683
684 // Fall through for subaggregate initialization
685 }
686
687 // C++ [dcl.init.aggr]p12:
688 //
689 // [...] Otherwise, if the member is itself a non-empty
690 // subaggregate, brace elision is assumed and the initializer is
691 // considered for the initialization of the first member of
692 // the subaggregate.
693 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
694 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
695 StructuredIndex);
696 ++StructuredIndex;
697 } else {
698 // We cannot initialize this element, so let
699 // PerformCopyInitialization produce the appropriate diagnostic.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000700 SemaRef.PerformCopyInitialization(expr, ElemType, "initializing");
Douglas Gregord45210d2009-01-30 22:09:00 +0000701 hadError = true;
702 ++Index;
703 ++StructuredIndex;
704 }
705 }
Eli Friedman683cedf2008-05-19 19:16:24 +0000706}
707
Douglas Gregord45210d2009-01-30 22:09:00 +0000708void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor36859eb2009-01-29 00:39:20 +0000709 unsigned &Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000710 InitListExpr *StructuredList,
711 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000712 if (Index < IList->getNumInits()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000713 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000714 if (isa<InitListExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000715 SemaRef.Diag(IList->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000716 diag::err_many_braces_around_scalar_init)
717 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000718 hadError = true;
719 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000720 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000721 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000722 } else if (isa<DesignatedInitExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000723 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000724 diag::err_designator_for_scalar_init)
725 << DeclType << expr->getSourceRange();
726 hadError = true;
727 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000728 ++StructuredIndex;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000729 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000730 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000731
Eli Friedmand8535af2008-05-19 20:00:43 +0000732 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000733 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedman71de9eb2008-05-19 20:12:18 +0000734 hadError = true; // types weren't compatible.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000735 else if (savExpr != expr) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000736 // The type was promoted, update initializer list.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000737 IList->setInit(Index, expr);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000738 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000739 if (hadError)
740 ++StructuredIndex;
741 else
742 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000743 ++Index;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000744 } else {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000745 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattner9d2cf082008-11-19 05:27:50 +0000746 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000747 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000748 ++Index;
749 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000750 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000751 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000752}
753
Douglas Gregord45210d2009-01-30 22:09:00 +0000754void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
755 unsigned &Index,
756 InitListExpr *StructuredList,
757 unsigned &StructuredIndex) {
758 if (Index < IList->getNumInits()) {
759 Expr *expr = IList->getInit(Index);
760 if (isa<InitListExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000761 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord45210d2009-01-30 22:09:00 +0000762 << DeclType << IList->getSourceRange();
763 hadError = true;
764 ++Index;
765 ++StructuredIndex;
766 return;
767 }
768
769 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000770 if (SemaRef.CheckReferenceInit(expr, DeclType))
Douglas Gregord45210d2009-01-30 22:09:00 +0000771 hadError = true;
772 else if (savExpr != expr) {
773 // The type was promoted, update initializer list.
774 IList->setInit(Index, expr);
775 }
776 if (hadError)
777 ++StructuredIndex;
778 else
779 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
780 ++Index;
781 } else {
Mike Stumpe127ae32009-05-16 07:39:55 +0000782 // FIXME: It would be wonderful if we could point at the actual member. In
783 // general, it would be useful to pass location information down the stack,
784 // so that we know the location (or decl) of the "current object" being
785 // initialized.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000786 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord45210d2009-01-30 22:09:00 +0000787 diag::err_init_reference_member_uninitialized)
788 << DeclType
789 << IList->getSourceRange();
790 hadError = true;
791 ++Index;
792 ++StructuredIndex;
793 return;
794 }
795}
796
Steve Naroffc4d4a482008-05-01 22:18:59 +0000797void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000798 unsigned &Index,
799 InitListExpr *StructuredList,
800 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000801 if (Index < IList->getNumInits()) {
802 const VectorType *VT = DeclType->getAsVectorType();
803 int maxElements = VT->getNumElements();
804 QualType elementType = VT->getElementType();
805
806 for (int i = 0; i < maxElements; ++i) {
807 // Don't attempt to go past the end of the init list
808 if (Index >= IList->getNumInits())
809 break;
Douglas Gregor36859eb2009-01-29 00:39:20 +0000810 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000811 StructuredList, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000812 }
813 }
814}
815
816void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000817 llvm::APSInt elementIndex,
818 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000819 unsigned &Index,
820 InitListExpr *StructuredList,
821 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000822 // Check for the special-case of initializing an array with a string.
823 if (Index < IList->getNumInits()) {
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000824 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
825 SemaRef.Context)) {
826 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregorf603b472009-01-28 21:54:33 +0000827 // We place the string literal directly into the resulting
828 // initializer list. This is the only place where the structure
829 // of the structured initializer list doesn't match exactly,
830 // because doing so would involve allocating one character
831 // constant for each string.
Chris Lattner45d6fd62009-02-24 22:41:04 +0000832 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner2e2766a2009-02-24 22:50:46 +0000833 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000834 ++Index;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000835 return;
836 }
837 }
Chris Lattnera1923f62008-08-04 07:31:14 +0000838 if (const VariableArrayType *VAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000839 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman46f81662008-05-25 13:22:35 +0000840 // Check for VLAs; in standard C it would be possible to check this
841 // earlier, but I don't know where clang accepts VLAs (gcc accepts
842 // them in all sorts of strange places).
Chris Lattner2e2766a2009-02-24 22:50:46 +0000843 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000844 diag::err_variable_object_no_init)
845 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman46f81662008-05-25 13:22:35 +0000846 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000847 ++Index;
848 ++StructuredIndex;
Eli Friedman46f81662008-05-25 13:22:35 +0000849 return;
850 }
851
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000852 // We might know the maximum number of elements in advance.
Douglas Gregorf603b472009-01-28 21:54:33 +0000853 llvm::APSInt maxElements(elementIndex.getBitWidth(),
854 elementIndex.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000855 bool maxElementsKnown = false;
856 if (const ConstantArrayType *CAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000857 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000858 maxElements = CAT->getSize();
Douglas Gregor5a203a62009-01-23 16:54:12 +0000859 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000860 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000861 maxElementsKnown = true;
862 }
863
Chris Lattner2e2766a2009-02-24 22:50:46 +0000864 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnera1923f62008-08-04 07:31:14 +0000865 ->getElementType();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000866 while (Index < IList->getNumInits()) {
867 Expr *Init = IList->getInit(Index);
868 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000869 // If we're not the subobject that matches up with the '{' for
870 // the designator, we shouldn't be handling the
871 // designator. Return immediately.
872 if (!SubobjectIsDesignatorContext)
873 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000874
Douglas Gregor710f6d42009-01-22 23:26:18 +0000875 // Handle this designated initializer. elementIndex will be
876 // updated to be the next array element we'll initialize.
Douglas Gregoraa357272009-04-15 04:56:10 +0000877 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregorf603b472009-01-28 21:54:33 +0000878 DeclType, 0, &elementIndex, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000879 StructuredList, StructuredIndex, true,
880 false)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000881 hadError = true;
882 continue;
883 }
884
Douglas Gregor5a203a62009-01-23 16:54:12 +0000885 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
886 maxElements.extend(elementIndex.getBitWidth());
887 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
888 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000889 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor5a203a62009-01-23 16:54:12 +0000890
Douglas Gregor710f6d42009-01-22 23:26:18 +0000891 // If the array is of incomplete type, keep track of the number of
892 // elements in the initializer.
893 if (!maxElementsKnown && elementIndex > maxElements)
894 maxElements = elementIndex;
895
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000896 continue;
897 }
898
899 // If we know the maximum number of elements, and we've already
900 // hit it, stop consuming elements in the initializer list.
901 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000902 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000903
904 // Check this element.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000905 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000906 StructuredList, StructuredIndex);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000907 ++elementIndex;
908
909 // If the array is of incomplete type, keep track of the number of
910 // elements in the initializer.
911 if (!maxElementsKnown && elementIndex > maxElements)
912 maxElements = elementIndex;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000913 }
Eli Friedmanb4c71b32009-05-29 20:17:55 +0000914 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000915 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000916 // be calculated here.
Douglas Gregor69722702009-01-23 18:58:42 +0000917 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000918 if (maxElements == Zero) {
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000919 // Sizing an array implicitly to zero is not allowed by ISO C,
920 // but is supported by GNU.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000921 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000922 diag::ext_typecheck_zero_array_size);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000923 }
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000924
Chris Lattner2e2766a2009-02-24 22:50:46 +0000925 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000926 ArrayType::Normal, 0);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000927 }
928}
929
930void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
931 QualType DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000932 RecordDecl::field_iterator Field,
933 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000934 unsigned &Index,
935 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000936 unsigned &StructuredIndex,
937 bool TopLevelObject) {
Eli Friedman683cedf2008-05-19 19:16:24 +0000938 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000939
Eli Friedman683cedf2008-05-19 19:16:24 +0000940 // If the record is invalid, some of it's members are invalid. To avoid
941 // confusion, we forgo checking the intializer for the entire record.
942 if (structDecl->isInvalidDecl()) {
943 hadError = true;
944 return;
945 }
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000946
947 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
948 // Value-initialize the first named member of the union.
949 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000950 for (RecordDecl::field_iterator FieldEnd = RD->field_end(SemaRef.Context);
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000951 Field != FieldEnd; ++Field) {
952 if (Field->getDeclName()) {
953 StructuredList->setInitializedFieldInUnion(*Field);
954 break;
955 }
956 }
957 return;
958 }
959
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000960 // If structDecl is a forward declaration, this loop won't do
961 // anything except look at designated initializers; That's okay,
962 // because an error should get printed out elsewhere. It might be
963 // worthwhile to skip over the rest of the initializer, though.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000964 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000965 RecordDecl::field_iterator FieldEnd = RD->field_end(SemaRef.Context);
Douglas Gregor0ecc9e92009-02-12 19:00:39 +0000966 bool InitializedSomething = false;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000967 while (Index < IList->getNumInits()) {
968 Expr *Init = IList->getInit(Index);
969
970 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000971 // If we're not the subobject that matches up with the '{' for
972 // the designator, we shouldn't be handling the
973 // designator. Return immediately.
974 if (!SubobjectIsDesignatorContext)
975 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000976
Douglas Gregor710f6d42009-01-22 23:26:18 +0000977 // Handle this designated initializer. Field will be updated to
978 // the next field that we'll be initializing.
Douglas Gregoraa357272009-04-15 04:56:10 +0000979 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregorf603b472009-01-28 21:54:33 +0000980 DeclType, &Field, 0, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000981 StructuredList, StructuredIndex,
982 true, TopLevelObject))
Douglas Gregor710f6d42009-01-22 23:26:18 +0000983 hadError = true;
984
Douglas Gregor0ecc9e92009-02-12 19:00:39 +0000985 InitializedSomething = true;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000986 continue;
987 }
988
989 if (Field == FieldEnd) {
990 // We've run out of fields. We're done.
991 break;
992 }
993
Douglas Gregor0ecc9e92009-02-12 19:00:39 +0000994 // We've already initialized a member of a union. We're done.
995 if (InitializedSomething && DeclType->isUnionType())
996 break;
997
Douglas Gregor8acb7272008-12-11 16:49:14 +0000998 // If we've hit the flexible array member at the end, we're done.
999 if (Field->getType()->isIncompleteArrayType())
1000 break;
1001
Douglas Gregor82462762009-01-29 16:53:55 +00001002 if (Field->isUnnamedBitfield()) {
Douglas Gregorf603b472009-01-28 21:54:33 +00001003 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001004 ++Field;
Eli Friedman683cedf2008-05-19 19:16:24 +00001005 continue;
Steve Naroffc4d4a482008-05-01 22:18:59 +00001006 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001007
Douglas Gregor36859eb2009-01-29 00:39:20 +00001008 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001009 StructuredList, StructuredIndex);
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001010 InitializedSomething = true;
Douglas Gregor82462762009-01-29 16:53:55 +00001011
1012 if (DeclType->isUnionType()) {
1013 // Initialize the first field within the union.
1014 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor82462762009-01-29 16:53:55 +00001015 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001016
1017 ++Field;
Steve Naroffc4d4a482008-05-01 22:18:59 +00001018 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001019
Douglas Gregorbe69b162009-02-04 22:46:25 +00001020 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001021 Index >= IList->getNumInits())
Douglas Gregorbe69b162009-02-04 22:46:25 +00001022 return;
1023
1024 // Handle GNU flexible array initializers.
1025 if (!TopLevelObject &&
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001026 (!isa<InitListExpr>(IList->getInit(Index)) ||
1027 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001028 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001029 diag::err_flexible_array_init_nonempty)
1030 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001031 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001032 << *Field;
1033 hadError = true;
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001034 ++Index;
1035 return;
1036 } else {
1037 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
1038 diag::ext_flexible_array_init)
1039 << IList->getInit(Index)->getSourceRange().getBegin();
1040 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1041 << *Field;
Douglas Gregorbe69b162009-02-04 22:46:25 +00001042 }
1043
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001044 if (isa<InitListExpr>(IList->getInit(Index)))
1045 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1046 StructuredIndex);
1047 else
1048 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1049 StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +00001050}
Steve Naroffc4d4a482008-05-01 22:18:59 +00001051
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001052/// \brief Expand a field designator that refers to a member of an
1053/// anonymous struct or union into a series of field designators that
1054/// refers to the field within the appropriate subobject.
1055///
1056/// Field/FieldIndex will be updated to point to the (new)
1057/// currently-designated field.
1058static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1059 DesignatedInitExpr *DIE,
1060 unsigned DesigIdx,
1061 FieldDecl *Field,
1062 RecordDecl::field_iterator &FieldIter,
1063 unsigned &FieldIndex) {
1064 typedef DesignatedInitExpr::Designator Designator;
1065
1066 // Build the path from the current object to the member of the
1067 // anonymous struct/union (backwards).
1068 llvm::SmallVector<FieldDecl *, 4> Path;
1069 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
1070
1071 // Build the replacement designators.
1072 llvm::SmallVector<Designator, 4> Replacements;
1073 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1074 FI = Path.rbegin(), FIEnd = Path.rend();
1075 FI != FIEnd; ++FI) {
1076 if (FI + 1 == FIEnd)
1077 Replacements.push_back(Designator((IdentifierInfo *)0,
1078 DIE->getDesignator(DesigIdx)->getDotLoc(),
1079 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1080 else
1081 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1082 SourceLocation()));
1083 Replacements.back().setField(*FI);
1084 }
1085
1086 // Expand the current designator into the set of replacement
1087 // designators, so we have a full subobject path down to where the
1088 // member of the anonymous struct/union is actually stored.
1089 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
1090 &Replacements[0] + Replacements.size());
1091
1092 // Update FieldIter/FieldIndex;
1093 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
1094 FieldIter = Record->field_begin(SemaRef.Context);
1095 FieldIndex = 0;
1096 for (RecordDecl::field_iterator FEnd = Record->field_end(SemaRef.Context);
1097 FieldIter != FEnd; ++FieldIter) {
1098 if (FieldIter->isUnnamedBitfield())
1099 continue;
1100
1101 if (*FieldIter == Path.back())
1102 return;
1103
1104 ++FieldIndex;
1105 }
1106
1107 assert(false && "Unable to find anonymous struct/union field");
1108}
1109
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001110/// @brief Check the well-formedness of a C99 designated initializer.
1111///
1112/// Determines whether the designated initializer @p DIE, which
1113/// resides at the given @p Index within the initializer list @p
1114/// IList, is well-formed for a current object of type @p DeclType
1115/// (C99 6.7.8). The actual subobject that this designator refers to
1116/// within the current subobject is returned in either
Douglas Gregorf603b472009-01-28 21:54:33 +00001117/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001118///
1119/// @param IList The initializer list in which this designated
1120/// initializer occurs.
1121///
Douglas Gregoraa357272009-04-15 04:56:10 +00001122/// @param DIE The designated initializer expression.
1123///
1124/// @param DesigIdx The index of the current designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001125///
1126/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1127/// into which the designation in @p DIE should refer.
1128///
Douglas Gregor710f6d42009-01-22 23:26:18 +00001129/// @param NextField If non-NULL and the first designator in @p DIE is
1130/// a field, this will be set to the field declaration corresponding
1131/// to the field named by the designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001132///
Douglas Gregor710f6d42009-01-22 23:26:18 +00001133/// @param NextElementIndex If non-NULL and the first designator in @p
1134/// DIE is an array designator or GNU array-range designator, this
1135/// will be set to the last index initialized by this designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001136///
1137/// @param Index Index into @p IList where the designated initializer
1138/// @p DIE occurs.
1139///
Douglas Gregorf603b472009-01-28 21:54:33 +00001140/// @param StructuredList The initializer list expression that
1141/// describes all of the subobject initializers in the order they'll
1142/// actually be initialized.
1143///
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001144/// @returns true if there was an error, false otherwise.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001145bool
1146InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
1147 DesignatedInitExpr *DIE,
Douglas Gregoraa357272009-04-15 04:56:10 +00001148 unsigned DesigIdx,
Douglas Gregor710f6d42009-01-22 23:26:18 +00001149 QualType &CurrentObjectType,
1150 RecordDecl::field_iterator *NextField,
1151 llvm::APSInt *NextElementIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +00001152 unsigned &Index,
1153 InitListExpr *StructuredList,
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001154 unsigned &StructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001155 bool FinishSubobjectInit,
1156 bool TopLevelObject) {
Douglas Gregoraa357272009-04-15 04:56:10 +00001157 if (DesigIdx == DIE->size()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001158 // Check the actual initialization for the designated object type.
1159 bool prevHadError = hadError;
Douglas Gregor36859eb2009-01-29 00:39:20 +00001160
1161 // Temporarily remove the designator expression from the
1162 // initializer list that the child calls see, so that we don't try
1163 // to re-process the designator.
1164 unsigned OldIndex = Index;
1165 IList->setInit(OldIndex, DIE->getInit());
1166
1167 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001168 StructuredList, StructuredIndex);
Douglas Gregor36859eb2009-01-29 00:39:20 +00001169
1170 // Restore the designated initializer expression in the syntactic
1171 // form of the initializer list.
1172 if (IList->getInit(OldIndex) != DIE->getInit())
1173 DIE->setInit(IList->getInit(OldIndex));
1174 IList->setInit(OldIndex, DIE);
1175
Douglas Gregor710f6d42009-01-22 23:26:18 +00001176 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001177 }
1178
Douglas Gregoraa357272009-04-15 04:56:10 +00001179 bool IsFirstDesignator = (DesigIdx == 0);
Douglas Gregorf603b472009-01-28 21:54:33 +00001180 assert((IsFirstDesignator || StructuredList) &&
1181 "Need a non-designated initializer list to start from");
1182
Douglas Gregoraa357272009-04-15 04:56:10 +00001183 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregorf603b472009-01-28 21:54:33 +00001184 // Determine the structural initializer list that corresponds to the
1185 // current subobject.
1186 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Douglas Gregorea765e12009-03-01 17:12:46 +00001187 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1188 StructuredList, StructuredIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +00001189 SourceRange(D->getStartLocation(),
1190 DIE->getSourceRange().getEnd()));
1191 assert(StructuredList && "Expected a structured initializer list");
1192
Douglas Gregor710f6d42009-01-22 23:26:18 +00001193 if (D->isFieldDesignator()) {
1194 // C99 6.7.8p7:
1195 //
1196 // If a designator has the form
1197 //
1198 // . identifier
1199 //
1200 // then the current object (defined below) shall have
1201 // structure or union type and the identifier shall be the
1202 // name of a member of that type.
1203 const RecordType *RT = CurrentObjectType->getAsRecordType();
1204 if (!RT) {
1205 SourceLocation Loc = D->getDotLoc();
1206 if (Loc.isInvalid())
1207 Loc = D->getFieldLoc();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001208 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1209 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001210 ++Index;
1211 return true;
1212 }
1213
Douglas Gregorf603b472009-01-28 21:54:33 +00001214 // Note: we perform a linear search of the fields here, despite
1215 // the fact that we have a faster lookup method, because we always
1216 // need to compute the field's index.
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001217 FieldDecl *KnownField = D->getField();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001218 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregorf603b472009-01-28 21:54:33 +00001219 unsigned FieldIndex = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001220 RecordDecl::field_iterator
1221 Field = RT->getDecl()->field_begin(SemaRef.Context),
1222 FieldEnd = RT->getDecl()->field_end(SemaRef.Context);
Douglas Gregorf603b472009-01-28 21:54:33 +00001223 for (; Field != FieldEnd; ++Field) {
1224 if (Field->isUnnamedBitfield())
1225 continue;
1226
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001227 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregorf603b472009-01-28 21:54:33 +00001228 break;
1229
1230 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001231 }
1232
Douglas Gregorf603b472009-01-28 21:54:33 +00001233 if (Field == FieldEnd) {
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001234 // There was no normal field in the struct with the designated
1235 // name. Perform another lookup for this name, which may find
1236 // something that we can't designate (e.g., a member function),
1237 // may find nothing, or may find a member of an anonymous
1238 // struct/union.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001239 DeclContext::lookup_result Lookup
1240 = RT->getDecl()->lookup(SemaRef.Context, FieldName);
Douglas Gregorf603b472009-01-28 21:54:33 +00001241 if (Lookup.first == Lookup.second) {
1242 // Name lookup didn't find anything.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001243 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregorf603b472009-01-28 21:54:33 +00001244 << FieldName << CurrentObjectType;
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001245 ++Index;
1246 return true;
1247 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1248 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1249 ->isAnonymousStructOrUnion()) {
1250 // Handle an field designator that refers to a member of an
1251 // anonymous struct or union.
1252 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1253 cast<FieldDecl>(*Lookup.first),
1254 Field, FieldIndex);
Eli Friedmanbd45b552009-04-16 17:49:48 +00001255 D = DIE->getDesignator(DesigIdx);
Douglas Gregorf603b472009-01-28 21:54:33 +00001256 } else {
1257 // Name lookup found something, but it wasn't a field.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001258 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregorf603b472009-01-28 21:54:33 +00001259 << FieldName;
Chris Lattner2e2766a2009-02-24 22:50:46 +00001260 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001261 diag::note_field_designator_found);
Eli Friedmanbd45b552009-04-16 17:49:48 +00001262 ++Index;
1263 return true;
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001264 }
1265 } else if (!KnownField &&
1266 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregorf603b472009-01-28 21:54:33 +00001267 ->isAnonymousStructOrUnion()) {
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001268 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1269 Field, FieldIndex);
1270 D = DIE->getDesignator(DesigIdx);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001271 }
Douglas Gregorf603b472009-01-28 21:54:33 +00001272
1273 // All of the fields of a union are located at the same place in
1274 // the initializer list.
Douglas Gregor82462762009-01-29 16:53:55 +00001275 if (RT->getDecl()->isUnion()) {
Douglas Gregorf603b472009-01-28 21:54:33 +00001276 FieldIndex = 0;
Douglas Gregor82462762009-01-29 16:53:55 +00001277 StructuredList->setInitializedFieldInUnion(*Field);
1278 }
Douglas Gregorf603b472009-01-28 21:54:33 +00001279
Douglas Gregor710f6d42009-01-22 23:26:18 +00001280 // Update the designator with the field declaration.
Douglas Gregorf603b472009-01-28 21:54:33 +00001281 D->setField(*Field);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001282
Douglas Gregorf603b472009-01-28 21:54:33 +00001283 // Make sure that our non-designated initializer list has space
1284 // for a subobject corresponding to this field.
1285 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner2e2766a2009-02-24 22:50:46 +00001286 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +00001287
Douglas Gregorbe69b162009-02-04 22:46:25 +00001288 // This designator names a flexible array member.
1289 if (Field->getType()->isIncompleteArrayType()) {
1290 bool Invalid = false;
Douglas Gregoraa357272009-04-15 04:56:10 +00001291 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorbe69b162009-02-04 22:46:25 +00001292 // We can't designate an object within the flexible array
1293 // member (because GCC doesn't allow it).
Douglas Gregoraa357272009-04-15 04:56:10 +00001294 DesignatedInitExpr::Designator *NextD
1295 = DIE->getDesignator(DesigIdx + 1);
Chris Lattner2e2766a2009-02-24 22:50:46 +00001296 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001297 diag::err_designator_into_flexible_array_member)
1298 << SourceRange(NextD->getStartLocation(),
1299 DIE->getSourceRange().getEnd());
Chris Lattner2e2766a2009-02-24 22:50:46 +00001300 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001301 << *Field;
1302 Invalid = true;
1303 }
1304
1305 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1306 // The initializer is not an initializer list.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001307 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001308 diag::err_flexible_array_init_needs_braces)
1309 << DIE->getInit()->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001310 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001311 << *Field;
1312 Invalid = true;
1313 }
1314
1315 // Handle GNU flexible array initializers.
1316 if (!Invalid && !TopLevelObject &&
1317 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001318 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001319 diag::err_flexible_array_init_nonempty)
1320 << DIE->getSourceRange().getBegin();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001321 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001322 << *Field;
1323 Invalid = true;
1324 }
1325
1326 if (Invalid) {
1327 ++Index;
1328 return true;
1329 }
1330
1331 // Initialize the array.
1332 bool prevHadError = hadError;
1333 unsigned newStructuredIndex = FieldIndex;
1334 unsigned OldIndex = Index;
1335 IList->setInit(Index, DIE->getInit());
1336 CheckSubElementType(IList, Field->getType(), Index,
1337 StructuredList, newStructuredIndex);
1338 IList->setInit(OldIndex, DIE);
1339 if (hadError && !prevHadError) {
1340 ++Field;
1341 ++FieldIndex;
1342 if (NextField)
1343 *NextField = Field;
1344 StructuredIndex = FieldIndex;
1345 return true;
1346 }
1347 } else {
1348 // Recurse to check later designated subobjects.
1349 QualType FieldType = (*Field)->getType();
1350 unsigned newStructuredIndex = FieldIndex;
Douglas Gregoraa357272009-04-15 04:56:10 +00001351 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1352 Index, StructuredList, newStructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001353 true, false))
1354 return true;
1355 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001356
1357 // Find the position of the next field to be initialized in this
1358 // subobject.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001359 ++Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001360 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001361
1362 // If this the first designator, our caller will continue checking
1363 // the rest of this struct/class/union subobject.
1364 if (IsFirstDesignator) {
1365 if (NextField)
1366 *NextField = Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001367 StructuredIndex = FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001368 return false;
1369 }
1370
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001371 if (!FinishSubobjectInit)
1372 return false;
1373
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001374 // We've already initialized something in the union; we're done.
1375 if (RT->getDecl()->isUnion())
1376 return hadError;
1377
Douglas Gregor710f6d42009-01-22 23:26:18 +00001378 // Check the remaining fields within this class/struct/union subobject.
1379 bool prevHadError = hadError;
Douglas Gregorf603b472009-01-28 21:54:33 +00001380 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1381 StructuredList, FieldIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001382 return hadError && !prevHadError;
1383 }
1384
1385 // C99 6.7.8p6:
1386 //
1387 // If a designator has the form
1388 //
1389 // [ constant-expression ]
1390 //
1391 // then the current object (defined below) shall have array
1392 // type and the expression shall be an integer constant
1393 // expression. If the array is of unknown size, any
1394 // nonnegative value is valid.
1395 //
1396 // Additionally, cope with the GNU extension that permits
1397 // designators of the form
1398 //
1399 // [ constant-expression ... constant-expression ]
Chris Lattner2e2766a2009-02-24 22:50:46 +00001400 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001401 if (!AT) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001402 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor710f6d42009-01-22 23:26:18 +00001403 << CurrentObjectType;
1404 ++Index;
1405 return true;
1406 }
1407
1408 Expr *IndexExpr = 0;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001409 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1410 if (D->isArrayDesignator()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001411 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnereec8ae22009-04-25 21:59:05 +00001412 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001413 DesignatedEndIndex = DesignatedStartIndex;
1414 } else {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001415 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001416
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001417
Chris Lattnereec8ae22009-04-25 21:59:05 +00001418 DesignatedStartIndex =
1419 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
1420 DesignatedEndIndex =
1421 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001422 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001423
Chris Lattnereec8ae22009-04-25 21:59:05 +00001424 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregor9fddded2009-01-29 19:42:23 +00001425 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001426 }
1427
Douglas Gregor710f6d42009-01-22 23:26:18 +00001428 if (isa<ConstantArrayType>(AT)) {
1429 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001430 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1431 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1432 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1433 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1434 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001435 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor710f6d42009-01-22 23:26:18 +00001436 diag::err_array_designator_too_large)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001437 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor710f6d42009-01-22 23:26:18 +00001438 << IndexExpr->getSourceRange();
1439 ++Index;
1440 return true;
1441 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001442 } else {
1443 // Make sure the bit-widths and signedness match.
1444 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1445 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnereec8ae22009-04-25 21:59:05 +00001446 else if (DesignatedStartIndex.getBitWidth() <
1447 DesignatedEndIndex.getBitWidth())
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001448 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1449 DesignatedStartIndex.setIsUnsigned(true);
1450 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001451 }
1452
Douglas Gregorf603b472009-01-28 21:54:33 +00001453 // Make sure that our non-designated initializer list has space
1454 // for a subobject corresponding to this array element.
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001455 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Chris Lattner2e2766a2009-02-24 22:50:46 +00001456 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001457 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +00001458
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001459 // Repeatedly perform subobject initializations in the range
1460 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor710f6d42009-01-22 23:26:18 +00001461
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001462 // Move to the next designator
1463 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1464 unsigned OldIndex = Index;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001465 while (DesignatedStartIndex <= DesignatedEndIndex) {
1466 // Recurse to check later designated subobjects.
1467 QualType ElementType = AT->getElementType();
1468 Index = OldIndex;
Douglas Gregoraa357272009-04-15 04:56:10 +00001469 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1470 Index, StructuredList, ElementIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001471 (DesignatedStartIndex == DesignatedEndIndex),
1472 false))
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001473 return true;
1474
1475 // Move to the next index in the array that we'll be initializing.
1476 ++DesignatedStartIndex;
1477 ElementIndex = DesignatedStartIndex.getZExtValue();
1478 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001479
1480 // If this the first designator, our caller will continue checking
1481 // the rest of this array subobject.
1482 if (IsFirstDesignator) {
1483 if (NextElementIndex)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001484 *NextElementIndex = DesignatedStartIndex;
Douglas Gregorf603b472009-01-28 21:54:33 +00001485 StructuredIndex = ElementIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001486 return false;
1487 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001488
1489 if (!FinishSubobjectInit)
1490 return false;
1491
Douglas Gregor710f6d42009-01-22 23:26:18 +00001492 // Check the remaining elements within this array subobject.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001493 bool prevHadError = hadError;
Douglas Gregord7e76c52009-02-09 19:45:19 +00001494 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001495 StructuredList, ElementIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001496 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001497}
1498
Douglas Gregorf603b472009-01-28 21:54:33 +00001499// Get the structured initializer list for a subobject of type
1500// @p CurrentObjectType.
1501InitListExpr *
1502InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1503 QualType CurrentObjectType,
1504 InitListExpr *StructuredList,
1505 unsigned StructuredIndex,
1506 SourceRange InitRange) {
1507 Expr *ExistingInit = 0;
1508 if (!StructuredList)
1509 ExistingInit = SyntacticToSemantic[IList];
1510 else if (StructuredIndex < StructuredList->getNumInits())
1511 ExistingInit = StructuredList->getInit(StructuredIndex);
1512
1513 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1514 return Result;
1515
1516 if (ExistingInit) {
1517 // We are creating an initializer list that initializes the
1518 // subobjects of the current object, but there was already an
1519 // initialization that completely initialized the current
1520 // subobject, e.g., by a compound literal:
1521 //
1522 // struct X { int a, b; };
1523 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1524 //
1525 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1526 // designated initializer re-initializes the whole
1527 // subobject [0], overwriting previous initializers.
Douglas Gregorea765e12009-03-01 17:12:46 +00001528 SemaRef.Diag(InitRange.getBegin(),
1529 diag::warn_subobject_initializer_overrides)
Douglas Gregorf603b472009-01-28 21:54:33 +00001530 << InitRange;
Chris Lattner2e2766a2009-02-24 22:50:46 +00001531 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001532 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001533 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001534 << ExistingInit->getSourceRange();
1535 }
1536
1537 InitListExpr *Result
Douglas Gregorea765e12009-03-01 17:12:46 +00001538 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
1539 InitRange.getEnd());
1540
Douglas Gregorf603b472009-01-28 21:54:33 +00001541 Result->setType(CurrentObjectType);
1542
Douglas Gregoree0792c2009-03-20 23:58:33 +00001543 // Pre-allocate storage for the structured initializer list.
1544 unsigned NumElements = 0;
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001545 unsigned NumInits = 0;
1546 if (!StructuredList)
1547 NumInits = IList->getNumInits();
1548 else if (Index < IList->getNumInits()) {
1549 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1550 NumInits = SubList->getNumInits();
1551 }
1552
Douglas Gregoree0792c2009-03-20 23:58:33 +00001553 if (const ArrayType *AType
1554 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1555 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1556 NumElements = CAType->getSize().getZExtValue();
1557 // Simple heuristic so that we don't allocate a very large
1558 // initializer with many empty entries at the end.
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001559 if (NumInits && NumElements > NumInits)
Douglas Gregoree0792c2009-03-20 23:58:33 +00001560 NumElements = 0;
1561 }
1562 } else if (const VectorType *VType = CurrentObjectType->getAsVectorType())
1563 NumElements = VType->getNumElements();
1564 else if (const RecordType *RType = CurrentObjectType->getAsRecordType()) {
1565 RecordDecl *RDecl = RType->getDecl();
1566 if (RDecl->isUnion())
1567 NumElements = 1;
1568 else
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001569 NumElements = std::distance(RDecl->field_begin(SemaRef.Context),
1570 RDecl->field_end(SemaRef.Context));
Douglas Gregoree0792c2009-03-20 23:58:33 +00001571 }
1572
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001573 if (NumElements < NumInits)
Douglas Gregoree0792c2009-03-20 23:58:33 +00001574 NumElements = IList->getNumInits();
1575
1576 Result->reserveInits(NumElements);
1577
Douglas Gregorf603b472009-01-28 21:54:33 +00001578 // Link this new initializer list into the structured initializer
1579 // lists.
1580 if (StructuredList)
1581 StructuredList->updateInit(StructuredIndex, Result);
1582 else {
1583 Result->setSyntacticForm(IList);
1584 SyntacticToSemantic[IList] = Result;
1585 }
1586
1587 return Result;
1588}
1589
1590/// Update the initializer at index @p StructuredIndex within the
1591/// structured initializer list to the value @p expr.
1592void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1593 unsigned &StructuredIndex,
1594 Expr *expr) {
1595 // No structured initializer list to update
1596 if (!StructuredList)
1597 return;
1598
1599 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1600 // This initializer overwrites a previous initializer. Warn.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001601 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001602 diag::warn_initializer_overrides)
1603 << expr->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001604 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001605 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001606 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001607 << PrevInit->getSourceRange();
1608 }
1609
1610 ++StructuredIndex;
1611}
1612
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001613/// Check that the given Index expression is a valid array designator
1614/// value. This is essentailly just a wrapper around
Chris Lattnereec8ae22009-04-25 21:59:05 +00001615/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001616/// and produces a reasonable diagnostic if there is a
1617/// failure. Returns true if there was an error, false otherwise. If
1618/// everything went okay, Value will receive the value of the constant
1619/// expression.
1620static bool
Chris Lattnereec8ae22009-04-25 21:59:05 +00001621CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001622 SourceLocation Loc = Index->getSourceRange().getBegin();
1623
1624 // Make sure this is an integer constant expression.
Chris Lattnereec8ae22009-04-25 21:59:05 +00001625 if (S.VerifyIntegerConstantExpression(Index, &Value))
1626 return true;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001627
Chris Lattnereec8ae22009-04-25 21:59:05 +00001628 if (Value.isSigned() && Value.isNegative())
1629 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001630 << Value.toString(10) << Index->getSourceRange();
1631
Douglas Gregore498e372009-01-23 21:04:18 +00001632 Value.setIsUnsigned(true);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001633 return false;
1634}
1635
1636Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1637 SourceLocation Loc,
Douglas Gregor5f34f0e2009-03-28 00:41:23 +00001638 bool GNUSyntax,
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001639 OwningExprResult Init) {
1640 typedef DesignatedInitExpr::Designator ASTDesignator;
1641
1642 bool Invalid = false;
1643 llvm::SmallVector<ASTDesignator, 32> Designators;
1644 llvm::SmallVector<Expr *, 32> InitExpressions;
1645
1646 // Build designators and check array designator expressions.
1647 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1648 const Designator &D = Desig.getDesignator(Idx);
1649 switch (D.getKind()) {
1650 case Designator::FieldDesignator:
1651 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1652 D.getFieldLoc()));
1653 break;
1654
1655 case Designator::ArrayDesignator: {
1656 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1657 llvm::APSInt IndexValue;
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001658 if (!Index->isTypeDependent() &&
1659 !Index->isValueDependent() &&
1660 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001661 Invalid = true;
1662 else {
1663 Designators.push_back(ASTDesignator(InitExpressions.size(),
1664 D.getLBracketLoc(),
1665 D.getRBracketLoc()));
1666 InitExpressions.push_back(Index);
1667 }
1668 break;
1669 }
1670
1671 case Designator::ArrayRangeDesignator: {
1672 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1673 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1674 llvm::APSInt StartValue;
1675 llvm::APSInt EndValue;
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001676 bool StartDependent = StartIndex->isTypeDependent() ||
1677 StartIndex->isValueDependent();
1678 bool EndDependent = EndIndex->isTypeDependent() ||
1679 EndIndex->isValueDependent();
1680 if ((!StartDependent &&
1681 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1682 (!EndDependent &&
1683 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001684 Invalid = true;
Douglas Gregorea0528d2009-01-23 22:22:29 +00001685 else {
1686 // Make sure we're comparing values with the same bit width.
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001687 if (StartDependent || EndDependent) {
1688 // Nothing to compute.
1689 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregorea0528d2009-01-23 22:22:29 +00001690 EndValue.extend(StartValue.getBitWidth());
1691 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1692 StartValue.extend(EndValue.getBitWidth());
1693
Douglas Gregor1401c062009-05-21 23:30:39 +00001694 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregorea0528d2009-01-23 22:22:29 +00001695 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1696 << StartValue.toString(10) << EndValue.toString(10)
1697 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1698 Invalid = true;
1699 } else {
1700 Designators.push_back(ASTDesignator(InitExpressions.size(),
1701 D.getLBracketLoc(),
1702 D.getEllipsisLoc(),
1703 D.getRBracketLoc()));
1704 InitExpressions.push_back(StartIndex);
1705 InitExpressions.push_back(EndIndex);
1706 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001707 }
1708 break;
1709 }
1710 }
1711 }
1712
1713 if (Invalid || Init.isInvalid())
1714 return ExprError();
1715
1716 // Clear out the expressions within the designation.
1717 Desig.ClearExprs(*this);
1718
1719 DesignatedInitExpr *DIE
Jay Foad9e6bef42009-05-21 09:52:38 +00001720 = DesignatedInitExpr::Create(Context,
1721 Designators.data(), Designators.size(),
1722 InitExpressions.data(), InitExpressions.size(),
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001723 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001724 return Owned(DIE);
1725}
Douglas Gregor849afc32009-01-29 00:45:39 +00001726
1727bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001728 InitListChecker CheckInitList(*this, InitList, DeclType);
Douglas Gregor849afc32009-01-29 00:45:39 +00001729 if (!CheckInitList.HadError())
1730 InitList = CheckInitList.getFullyStructuredList();
1731
1732 return CheckInitList.HadError();
1733}
Douglas Gregor538a4c22009-02-02 17:43:21 +00001734
1735/// \brief Diagnose any semantic errors with value-initialization of
1736/// the given type.
1737///
1738/// Value-initialization effectively zero-initializes any types
1739/// without user-declared constructors, and calls the default
1740/// constructor for a for any type that has a user-declared
1741/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1742/// a type with a user-declared constructor does not have an
1743/// accessible, non-deleted default constructor. In C, everything can
1744/// be value-initialized, which corresponds to C's notion of
1745/// initializing objects with static storage duration when no
1746/// initializer is provided for that object.
1747///
1748/// \returns true if there was an error, false otherwise.
1749bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1750 // C++ [dcl.init]p5:
1751 //
1752 // To value-initialize an object of type T means:
1753
1754 // -- if T is an array type, then each element is value-initialized;
1755 if (const ArrayType *AT = Context.getAsArrayType(Type))
1756 return CheckValueInitialization(AT->getElementType(), Loc);
1757
1758 if (const RecordType *RT = Type->getAsRecordType()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001759 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Douglas Gregor538a4c22009-02-02 17:43:21 +00001760 // -- if T is a class type (clause 9) with a user-declared
1761 // constructor (12.1), then the default constructor for T is
1762 // called (and the initialization is ill-formed if T has no
1763 // accessible default constructor);
Douglas Gregor2e047592009-02-28 01:32:25 +00001764 if (ClassDecl->hasUserDeclaredConstructor())
Mike Stumpe127ae32009-05-16 07:39:55 +00001765 // FIXME: Eventually, we'll need to put the constructor decl into the
1766 // AST.
Douglas Gregor538a4c22009-02-02 17:43:21 +00001767 return PerformInitializationByConstructor(Type, 0, 0, Loc,
1768 SourceRange(Loc),
1769 DeclarationName(),
1770 IK_Direct);
1771 }
1772 }
1773
1774 if (Type->isReferenceType()) {
1775 // C++ [dcl.init]p5:
1776 // [...] A program that calls for default-initialization or
1777 // value-initialization of an entity of reference type is
1778 // ill-formed. [...]
Mike Stumpe127ae32009-05-16 07:39:55 +00001779 // FIXME: Once we have code that goes through this path, add an actual
1780 // diagnostic :)
Douglas Gregor538a4c22009-02-02 17:43:21 +00001781 }
1782
1783 return false;
1784}