blob: 877efc31b9207a9b47be5b947ac461349e494f13 [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).
Douglas Gregor1d381132009-07-06 15:59:29 +0000100 DeclT = S.Context.getConstantArrayWithoutExprType(IAT->getElementType(),
101 ConstVal,
102 ArrayType::Normal, 0);
Chris Lattnerd20fac42009-02-24 23:01:39 +0000103 return;
Chris Lattnerd3a00502009-02-24 22:27:37 +0000104 }
Chris Lattnerd20fac42009-02-24 23:01:39 +0000105
Eli Friedman95acf982009-05-29 18:22:49 +0000106 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
107
108 // C99 6.7.8p14. We have an array of character type with known size. However,
109 // the size may be smaller or larger than the string we are initializing.
110 // FIXME: Avoid truncation for 64-bit length strings.
111 if (StrLength-1 > CAT->getSize().getZExtValue())
112 S.Diag(Str->getSourceRange().getBegin(),
113 diag::warn_initializer_string_for_char_array_too_long)
114 << Str->getSourceRange();
115
116 // Set the type to the actual size that we are initializing. If we have
117 // something like:
118 // char x[1] = "foo";
119 // then this will set the string literal's type to char[1].
120 Str->setType(DeclT);
Chris Lattnerd3a00502009-02-24 22:27:37 +0000121}
122
123bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
124 SourceLocation InitLoc,
Anders Carlsson8cc1f0d2009-05-30 20:41:30 +0000125 DeclarationName InitEntity, bool DirectInit) {
Douglas Gregor3a7a06e2009-05-21 23:17:49 +0000126 if (DeclType->isDependentType() ||
127 Init->isTypeDependent() || Init->isValueDependent())
Chris Lattnerd3a00502009-02-24 22:27:37 +0000128 return false;
129
130 // C++ [dcl.init.ref]p1:
Sebastian Redlce6fff02009-03-16 23:22:08 +0000131 // A variable declared to be a T& or T&&, that is "reference to type T"
Chris Lattnerd3a00502009-02-24 22:27:37 +0000132 // (8.3.2), shall be initialized by an object, or function, of
133 // type T or by an object that can be converted into a T.
134 if (DeclType->isReferenceType())
Anders Carlsson8f809f92009-08-27 17:30:43 +0000135 return CheckReferenceInit(Init, DeclType,
136 /*SuppressUserConversions=*/false,
137 /*AllowExplicit=*/DirectInit,
138 /*ForceRValue=*/false);
Chris Lattnerd3a00502009-02-24 22:27:37 +0000139
140 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
141 // of unknown size ("[]") or an object type that is not a variable array type.
142 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
143 return Diag(InitLoc, diag::err_variable_object_no_init)
144 << VAT->getSizeExpr()->getSourceRange();
145
146 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
147 if (!InitList) {
148 // FIXME: Handle wide strings
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000149 if (Expr *Str = IsStringInit(Init, DeclType, Context)) {
150 CheckStringInit(Str, DeclType, *this);
Chris Lattnerd20fac42009-02-24 23:01:39 +0000151 return false;
152 }
Chris Lattnerd3a00502009-02-24 22:27:37 +0000153
154 // C++ [dcl.init]p14:
155 // -- If the destination type is a (possibly cv-qualified) class
156 // type:
157 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
158 QualType DeclTypeC = Context.getCanonicalType(DeclType);
159 QualType InitTypeC = Context.getCanonicalType(Init->getType());
160
161 // -- If the initialization is direct-initialization, or if it is
162 // copy-initialization where the cv-unqualified version of the
163 // source type is the same class as, or a derived class of, the
164 // class of the destination, constructors are considered.
165 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
166 IsDerivedFrom(InitTypeC, DeclTypeC)) {
Anders Carlsson5868dfc2009-05-27 16:38:58 +0000167 const CXXRecordDecl *RD =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000168 cast<CXXRecordDecl>(DeclType->getAs<RecordType>()->getDecl());
Anders Carlsson5868dfc2009-05-27 16:38:58 +0000169
170 // No need to make a CXXConstructExpr if both the ctor and dtor are
171 // trivial.
172 if (RD->hasTrivialConstructor() && RD->hasTrivialDestructor())
173 return false;
174
Chris Lattnerd3a00502009-02-24 22:27:37 +0000175 CXXConstructorDecl *Constructor
176 = PerformInitializationByConstructor(DeclType, &Init, 1,
177 InitLoc, Init->getSourceRange(),
178 InitEntity,
179 DirectInit? IK_Direct : IK_Copy);
Anders Carlsson73bb5e62009-05-27 16:10:08 +0000180 if (!Constructor)
181 return true;
Anders Carlsson665e4692009-08-25 05:12:04 +0000182
183 OwningExprResult InitResult =
Anders Carlssonbf2dfb12009-09-05 07:40:38 +0000184 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
Anders Carlsson0d49ba62009-09-07 22:23:31 +0000185 DeclType, Constructor,
186 MultiExprArg(*this, (void**)&Init, 1));
Anders Carlsson665e4692009-08-25 05:12:04 +0000187 if (InitResult.isInvalid())
188 return true;
189
190 Init = InitResult.takeAs<Expr>();
Anders Carlsson73bb5e62009-05-27 16:10:08 +0000191 return false;
Chris Lattnerd3a00502009-02-24 22:27:37 +0000192 }
193
194 // -- Otherwise (i.e., for the remaining copy-initialization
195 // cases), user-defined conversion sequences that can
196 // convert from the source type to the destination type or
197 // (when a conversion function is used) to a derived class
198 // thereof are enumerated as described in 13.3.1.4, and the
199 // best one is chosen through overload resolution
200 // (13.3). If the conversion cannot be done or is
201 // ambiguous, the initialization is ill-formed. The
202 // function selected is called with the initializer
203 // expression as its argument; if the function is a
204 // constructor, the call initializes a temporary of the
205 // destination type.
Mike Stumpe127ae32009-05-16 07:39:55 +0000206 // FIXME: We're pretending to do copy elision here; return to this when we
207 // have ASTs for such things.
Chris Lattnerd3a00502009-02-24 22:27:37 +0000208 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
209 return false;
210
211 if (InitEntity)
212 return Diag(InitLoc, diag::err_cannot_initialize_decl)
Chris Lattner6434a1b2009-06-26 04:45:06 +0000213 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
214 << Init->getType() << Init->getSourceRange();
215 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
Chris Lattnerd3a00502009-02-24 22:27:37 +0000216 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
217 << Init->getType() << Init->getSourceRange();
218 }
219
220 // C99 6.7.8p16.
221 if (DeclType->isArrayType())
222 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
Chris Lattner6434a1b2009-06-26 04:45:06 +0000223 << Init->getSourceRange();
Chris Lattnerd3a00502009-02-24 22:27:37 +0000224
Chris Lattner160da072009-02-24 22:46:58 +0000225 return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
Chris Lattnerd3a00502009-02-24 22:27:37 +0000226 }
227
228 bool hadError = CheckInitList(InitList, DeclType);
229 Init = InitList;
230 return hadError;
231}
232
233//===----------------------------------------------------------------------===//
234// Semantic checking for initializer lists.
235//===----------------------------------------------------------------------===//
236
Douglas Gregoraaa20962009-01-29 01:05:33 +0000237/// @brief Semantic checking for initializer lists.
238///
239/// The InitListChecker class contains a set of routines that each
240/// handle the initialization of a certain kind of entity, e.g.,
241/// arrays, vectors, struct/union types, scalars, etc. The
242/// InitListChecker itself performs a recursive walk of the subobject
243/// structure of the type to be initialized, while stepping through
244/// the initializer list one element at a time. The IList and Index
245/// parameters to each of the Check* routines contain the active
246/// (syntactic) initializer list and the index into that initializer
247/// list that represents the current initializer. Each routine is
248/// responsible for moving that Index forward as it consumes elements.
249///
250/// Each Check* routine also has a StructuredList/StructuredIndex
251/// arguments, which contains the current the "structured" (semantic)
252/// initializer list and the index into that initializer list where we
253/// are copying initializers as we map them over to the semantic
254/// list. Once we have completed our recursive walk of the subobject
255/// structure, we will have constructed a full semantic initializer
256/// list.
257///
258/// C99 designators cause changes in the initializer list traversal,
259/// because they make the initialization "jump" into a specific
260/// subobject and then continue the initialization from that
261/// point. CheckDesignatedInitializer() recursively steps into the
262/// designated subobject and manages backing out the recursion to
263/// initialize the subobjects after the one designated.
Chris Lattnere76e9bf2009-02-24 22:48:58 +0000264namespace {
Douglas Gregor849afc32009-01-29 00:45:39 +0000265class InitListChecker {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000266 Sema &SemaRef;
Douglas Gregor849afc32009-01-29 00:45:39 +0000267 bool hadError;
268 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
269 InitListExpr *FullyStructuredList;
270
271 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000272 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000273 unsigned &StructuredIndex,
274 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000275 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000276 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000277 unsigned &StructuredIndex,
278 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000279 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
280 bool SubobjectIsDesignatorContext,
281 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000282 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000283 unsigned &StructuredIndex,
284 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000285 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
286 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000287 InitListExpr *StructuredList,
288 unsigned &StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000289 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor849afc32009-01-29 00:45:39 +0000290 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000291 InitListExpr *StructuredList,
292 unsigned &StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000293 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
294 unsigned &Index,
295 InitListExpr *StructuredList,
296 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000297 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000298 InitListExpr *StructuredList,
299 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000300 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
301 RecordDecl::field_iterator Field,
302 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000303 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000304 unsigned &StructuredIndex,
305 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000306 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
307 llvm::APSInt elementIndex,
308 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000309 InitListExpr *StructuredList,
310 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000311 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregoraa357272009-04-15 04:56:10 +0000312 unsigned DesigIdx,
Douglas Gregor849afc32009-01-29 00:45:39 +0000313 QualType &CurrentObjectType,
314 RecordDecl::field_iterator *NextField,
315 llvm::APSInt *NextElementIndex,
316 unsigned &Index,
317 InitListExpr *StructuredList,
318 unsigned &StructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000319 bool FinishSubobjectInit,
320 bool TopLevelObject);
Douglas Gregor849afc32009-01-29 00:45:39 +0000321 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
322 QualType CurrentObjectType,
323 InitListExpr *StructuredList,
324 unsigned StructuredIndex,
325 SourceRange InitRange);
Douglas Gregoraaa20962009-01-29 01:05:33 +0000326 void UpdateStructuredListElement(InitListExpr *StructuredList,
327 unsigned &StructuredIndex,
Douglas Gregor849afc32009-01-29 00:45:39 +0000328 Expr *expr);
329 int numArrayElements(QualType DeclType);
330 int numStructUnionElements(QualType DeclType);
Douglas Gregord45210d2009-01-30 22:09:00 +0000331
332 void FillInValueInitializations(InitListExpr *ILE);
Douglas Gregor849afc32009-01-29 00:45:39 +0000333public:
Chris Lattner2e2766a2009-02-24 22:50:46 +0000334 InitListChecker(Sema &S, InitListExpr *IL, QualType &T);
Douglas Gregor849afc32009-01-29 00:45:39 +0000335 bool HadError() { return hadError; }
336
337 // @brief Retrieves the fully-structured initializer list used for
338 // semantic analysis and code generation.
339 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
340};
Chris Lattnere76e9bf2009-02-24 22:48:58 +0000341} // end anonymous namespace
Chris Lattner1aa25a72009-01-29 05:10:57 +0000342
Douglas Gregorf603b472009-01-28 21:54:33 +0000343/// Recursively replaces NULL values within the given initializer list
344/// with expressions that perform value-initialization of the
345/// appropriate type.
Douglas Gregord45210d2009-01-30 22:09:00 +0000346void InitListChecker::FillInValueInitializations(InitListExpr *ILE) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000347 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord45210d2009-01-30 22:09:00 +0000348 "Should not have void type");
Douglas Gregor538a4c22009-02-02 17:43:21 +0000349 SourceLocation Loc = ILE->getSourceRange().getBegin();
350 if (ILE->getSyntacticForm())
351 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
352
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000353 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000354 unsigned Init = 0, NumInits = ILE->getNumInits();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000355 for (RecordDecl::field_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000356 Field = RType->getDecl()->field_begin(),
357 FieldEnd = RType->getDecl()->field_end();
Douglas Gregorf603b472009-01-28 21:54:33 +0000358 Field != FieldEnd; ++Field) {
359 if (Field->isUnnamedBitfield())
360 continue;
361
Douglas Gregor538a4c22009-02-02 17:43:21 +0000362 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000363 if (Field->getType()->isReferenceType()) {
364 // C++ [dcl.init.aggr]p9:
365 // If an incomplete or empty initializer-list leaves a
366 // member of reference type uninitialized, the program is
367 // ill-formed.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000368 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregord45210d2009-01-30 22:09:00 +0000369 << Field->getType()
370 << ILE->getSyntacticForm()->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +0000371 SemaRef.Diag(Field->getLocation(),
Douglas Gregord45210d2009-01-30 22:09:00 +0000372 diag::note_uninit_reference_member);
373 hadError = true;
Douglas Gregor538a4c22009-02-02 17:43:21 +0000374 return;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000375 } else if (SemaRef.CheckValueInitialization(Field->getType(), Loc)) {
Douglas Gregor538a4c22009-02-02 17:43:21 +0000376 hadError = true;
377 return;
Douglas Gregord45210d2009-01-30 22:09:00 +0000378 }
Douglas Gregor538a4c22009-02-02 17:43:21 +0000379
Mike Stumpe127ae32009-05-16 07:39:55 +0000380 // FIXME: If value-initialization involves calling a constructor, should
381 // we make that call explicit in the representation (even when it means
382 // extending the initializer list)?
Douglas Gregor538a4c22009-02-02 17:43:21 +0000383 if (Init < NumInits && !hadError)
384 ILE->setInit(Init,
Chris Lattner2e2766a2009-02-24 22:50:46 +0000385 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()));
Douglas Gregor538a4c22009-02-02 17:43:21 +0000386 } else if (InitListExpr *InnerILE
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000387 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregord45210d2009-01-30 22:09:00 +0000388 FillInValueInitializations(InnerILE);
Douglas Gregorf603b472009-01-28 21:54:33 +0000389 ++Init;
Douglas Gregord45210d2009-01-30 22:09:00 +0000390
391 // Only look at the first initialization of a union.
392 if (RType->getDecl()->isUnion())
393 break;
Douglas Gregorf603b472009-01-28 21:54:33 +0000394 }
395
396 return;
397 }
398
399 QualType ElementType;
400
Douglas Gregor538a4c22009-02-02 17:43:21 +0000401 unsigned NumInits = ILE->getNumInits();
402 unsigned NumElements = NumInits;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000403 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000404 ElementType = AType->getElementType();
Douglas Gregor538a4c22009-02-02 17:43:21 +0000405 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
406 NumElements = CAType->getSize().getZExtValue();
407 } else if (const VectorType *VType = ILE->getType()->getAsVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000408 ElementType = VType->getElementType();
Douglas Gregor538a4c22009-02-02 17:43:21 +0000409 NumElements = VType->getNumElements();
410 } else
Douglas Gregorf603b472009-01-28 21:54:33 +0000411 ElementType = ILE->getType();
412
Douglas Gregor538a4c22009-02-02 17:43:21 +0000413 for (unsigned Init = 0; Init != NumElements; ++Init) {
414 if (Init >= NumInits || !ILE->getInit(Init)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000415 if (SemaRef.CheckValueInitialization(ElementType, Loc)) {
Douglas Gregor538a4c22009-02-02 17:43:21 +0000416 hadError = true;
417 return;
418 }
419
Mike Stumpe127ae32009-05-16 07:39:55 +0000420 // FIXME: If value-initialization involves calling a constructor, should
421 // we make that call explicit in the representation (even when it means
422 // extending the initializer list)?
Douglas Gregor538a4c22009-02-02 17:43:21 +0000423 if (Init < NumInits && !hadError)
424 ILE->setInit(Init,
Chris Lattner2e2766a2009-02-24 22:50:46 +0000425 new (SemaRef.Context) ImplicitValueInitExpr(ElementType));
Mike Stump90fc78e2009-08-04 21:02:39 +0000426 } else if (InitListExpr *InnerILE
427 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregord45210d2009-01-30 22:09:00 +0000428 FillInValueInitializations(InnerILE);
Douglas Gregorf603b472009-01-28 21:54:33 +0000429 }
430}
431
Chris Lattner1aa25a72009-01-29 05:10:57 +0000432
Chris Lattner2e2766a2009-02-24 22:50:46 +0000433InitListChecker::InitListChecker(Sema &S, InitListExpr *IL, QualType &T)
434 : SemaRef(S) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000435 hadError = false;
Eli Friedmand8535af2008-05-19 20:00:43 +0000436
Eli Friedman683cedf2008-05-19 19:16:24 +0000437 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000438 unsigned newStructuredIndex = 0;
439 FullyStructuredList
Douglas Gregorea765e12009-03-01 17:12:46 +0000440 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregorbe69b162009-02-04 22:46:25 +0000441 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
442 /*TopLevelObject=*/true);
Eli Friedmand8535af2008-05-19 20:00:43 +0000443
Douglas Gregord45210d2009-01-30 22:09:00 +0000444 if (!hadError)
445 FillInValueInitializations(FullyStructuredList);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000446}
447
448int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman46f81662008-05-25 13:22:35 +0000449 // FIXME: use a proper constant
450 int maxElements = 0x7FFFFFFF;
Chris Lattnera1923f62008-08-04 07:31:14 +0000451 if (const ConstantArrayType *CAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000452 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000453 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
454 }
455 return maxElements;
456}
457
458int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000459 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregorf603b472009-01-28 21:54:33 +0000460 int InitializableMembers = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000461 for (RecordDecl::field_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000462 Field = structDecl->field_begin(),
463 FieldEnd = structDecl->field_end();
Douglas Gregorf603b472009-01-28 21:54:33 +0000464 Field != FieldEnd; ++Field) {
465 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
466 ++InitializableMembers;
467 }
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000468 if (structDecl->isUnion())
Eli Friedman9f5250b2008-05-25 14:03:31 +0000469 return std::min(InitializableMembers, 1);
470 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000471}
472
473void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregorf603b472009-01-28 21:54:33 +0000474 QualType T, unsigned &Index,
475 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000476 unsigned &StructuredIndex,
477 bool TopLevelObject) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000478 int maxElements = 0;
479
480 if (T->isArrayType())
481 maxElements = numArrayElements(T);
482 else if (T->isStructureType() || T->isUnionType())
483 maxElements = numStructUnionElements(T);
Eli Friedman683cedf2008-05-19 19:16:24 +0000484 else if (T->isVectorType())
485 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000486 else
487 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman683cedf2008-05-19 19:16:24 +0000488
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000489 if (maxElements == 0) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000490 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000491 diag::err_implicit_empty_initializer);
Douglas Gregorf603b472009-01-28 21:54:33 +0000492 ++Index;
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000493 hadError = true;
494 return;
495 }
496
Douglas Gregorf603b472009-01-28 21:54:33 +0000497 // Build a structured initializer list corresponding to this subobject.
498 InitListExpr *StructuredSubobjectInitList
499 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
500 StructuredIndex,
Douglas Gregorea765e12009-03-01 17:12:46 +0000501 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
502 ParentIList->getSourceRange().getEnd()));
Douglas Gregorf603b472009-01-28 21:54:33 +0000503 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman683cedf2008-05-19 19:16:24 +0000504
Douglas Gregorf603b472009-01-28 21:54:33 +0000505 // Check the element types and build the structural subobject.
Douglas Gregor538a4c22009-02-02 17:43:21 +0000506 unsigned StartIndex = Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000507 CheckListElementTypes(ParentIList, T, false, Index,
508 StructuredSubobjectInitList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000509 StructuredSubobjectInitIndex,
510 TopLevelObject);
Douglas Gregor538a4c22009-02-02 17:43:21 +0000511 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregorcd2c5272009-03-20 00:32:56 +0000512 StructuredSubobjectInitList->setType(T);
513
Douglas Gregorea765e12009-03-01 17:12:46 +0000514 // Update the structured sub-object initializer so that it's ending
Douglas Gregor538a4c22009-02-02 17:43:21 +0000515 // range corresponds with the end of the last initializer it used.
516 if (EndIndex < ParentIList->getNumInits()) {
517 SourceLocation EndLoc
518 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
519 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
520 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000521}
522
Steve Naroff56099522008-05-06 00:23:44 +0000523void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregorf603b472009-01-28 21:54:33 +0000524 unsigned &Index,
525 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000526 unsigned &StructuredIndex,
527 bool TopLevelObject) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000528 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregorf603b472009-01-28 21:54:33 +0000529 SyntacticToSemantic[IList] = StructuredList;
530 StructuredList->setSyntacticForm(IList);
531 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000532 StructuredIndex, TopLevelObject);
Steve Naroff56099522008-05-06 00:23:44 +0000533 IList->setType(T);
Douglas Gregorf603b472009-01-28 21:54:33 +0000534 StructuredList->setType(T);
Eli Friedman46f81662008-05-25 13:22:35 +0000535 if (hadError)
536 return;
Eli Friedmand8535af2008-05-19 20:00:43 +0000537
Eli Friedman46f81662008-05-25 13:22:35 +0000538 if (Index < IList->getNumInits()) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000539 // We have leftover initializers
Eli Friedman579534a2009-05-29 20:20:05 +0000540 if (StructuredIndex == 1 &&
541 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000542 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedman579534a2009-05-29 20:20:05 +0000543 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000544 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedman579534a2009-05-29 20:20:05 +0000545 hadError = true;
546 }
Eli Friedman71de9eb2008-05-19 20:12:18 +0000547 // Special-case
Chris Lattner2e2766a2009-02-24 22:50:46 +0000548 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattner9d2cf082008-11-19 05:27:50 +0000549 << IList->getInit(Index)->getSourceRange();
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000550 } else if (!T->isIncompleteType()) {
Douglas Gregor09f078c2009-01-30 22:26:29 +0000551 // Don't complain for incomplete types, since we'll get an error
552 // elsewhere
Douglas Gregorbe69b162009-02-04 22:46:25 +0000553 QualType CurrentObjectType = StructuredList->getType();
554 int initKind =
555 CurrentObjectType->isArrayType()? 0 :
556 CurrentObjectType->isVectorType()? 1 :
557 CurrentObjectType->isScalarType()? 2 :
558 CurrentObjectType->isUnionType()? 3 :
559 4;
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000560
561 unsigned DK = diag::warn_excess_initializers;
Eli Friedman579534a2009-05-29 20:20:05 +0000562 if (SemaRef.getLangOptions().CPlusPlus) {
563 DK = diag::err_excess_initializers;
564 hadError = true;
565 }
Nate Begeman48fd8c92009-07-07 21:53:06 +0000566 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
567 DK = diag::err_excess_initializers;
568 hadError = true;
569 }
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000570
Chris Lattner2e2766a2009-02-24 22:50:46 +0000571 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorbe69b162009-02-04 22:46:25 +0000572 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000573 }
574 }
Eli Friedman455f7622008-05-19 20:20:43 +0000575
Eli Friedman90bcb892009-05-16 11:45:48 +0000576 if (T->isScalarType() && !TopLevelObject)
Chris Lattner2e2766a2009-02-24 22:50:46 +0000577 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor3faaa812009-04-01 23:51:29 +0000578 << IList->getSourceRange()
579 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocStart()))
580 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocEnd()));
Steve Naroffc4d4a482008-05-01 22:18:59 +0000581}
582
Eli Friedman683cedf2008-05-19 19:16:24 +0000583void InitListChecker::CheckListElementTypes(InitListExpr *IList,
584 QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000585 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000586 unsigned &Index,
587 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000588 unsigned &StructuredIndex,
589 bool TopLevelObject) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000590 if (DeclType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000591 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000592 } else if (DeclType->isVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000593 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregore7ef5002009-01-30 17:31:00 +0000594 } else if (DeclType->isAggregateType()) {
595 if (DeclType->isRecordType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000596 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000597 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000598 SubobjectIsDesignatorContext, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000599 StructuredList, StructuredIndex,
600 TopLevelObject);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000601 } else if (DeclType->isArrayType()) {
Douglas Gregor5a203a62009-01-23 16:54:12 +0000602 llvm::APSInt Zero(
Chris Lattner2e2766a2009-02-24 22:50:46 +0000603 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor5a203a62009-01-23 16:54:12 +0000604 false);
Douglas Gregorf603b472009-01-28 21:54:33 +0000605 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
606 StructuredList, StructuredIndex);
Mike Stump90fc78e2009-08-04 21:02:39 +0000607 } else
Douglas Gregorf603b472009-01-28 21:54:33 +0000608 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffff5b3a82008-08-10 16:05:48 +0000609 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
610 // This type is invalid, issue a diagnostic.
Douglas Gregorf603b472009-01-28 21:54:33 +0000611 ++Index;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000612 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000613 << DeclType;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000614 hadError = true;
Douglas Gregord45210d2009-01-30 22:09:00 +0000615 } else if (DeclType->isRecordType()) {
616 // C++ [dcl.init]p14:
617 // [...] If the class is an aggregate (8.5.1), and the initializer
618 // is a brace-enclosed list, see 8.5.1.
619 //
620 // Note: 8.5.1 is handled below; here, we diagnose the case where
621 // we have an initializer list and a destination type that is not
622 // an aggregate.
623 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000624 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord45210d2009-01-30 22:09:00 +0000625 << DeclType << IList->getSourceRange();
626 hadError = true;
627 } else if (DeclType->isReferenceType()) {
628 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000629 } else {
630 // In C, all types are either scalars or aggregates, but
631 // additional handling is needed here for C++ (and possibly others?).
632 assert(0 && "Unsupported initializer type");
633 }
634}
635
Eli Friedman683cedf2008-05-19 19:16:24 +0000636void InitListChecker::CheckSubElementType(InitListExpr *IList,
637 QualType ElemType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000638 unsigned &Index,
639 InitListExpr *StructuredList,
640 unsigned &StructuredIndex) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000641 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000642 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
643 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000644 unsigned newStructuredIndex = 0;
645 InitListExpr *newStructuredList
646 = getStructuredSubobjectInit(IList, Index, ElemType,
647 StructuredList, StructuredIndex,
648 SubInitList->getSourceRange());
649 CheckExplicitInitList(SubInitList, ElemType, newIndex,
650 newStructuredList, newStructuredIndex);
651 ++StructuredIndex;
652 ++Index;
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000653 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
654 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattner45d6fd62009-02-24 22:41:04 +0000655 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregorf603b472009-01-28 21:54:33 +0000656 ++Index;
Eli Friedmand8535af2008-05-19 20:00:43 +0000657 } else if (ElemType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000658 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000659 } else if (ElemType->isReferenceType()) {
660 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedman683cedf2008-05-19 19:16:24 +0000661 } else {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000662 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000663 // C++ [dcl.init.aggr]p12:
664 // All implicit type conversions (clause 4) are considered when
665 // initializing the aggregate member with an ini- tializer from
666 // an initializer-list. If the initializer can initialize a
667 // member, the member is initialized. [...]
668 ImplicitConversionSequence ICS
Anders Carlsson06386552009-08-27 17:18:13 +0000669 = SemaRef.TryCopyInitialization(expr, ElemType,
670 /*SuppressUserConversions=*/false,
Anders Carlssone0f3ee62009-08-27 17:37:39 +0000671 /*ForceRValue=*/false,
672 /*InOverloadResolution=*/false);
Anders Carlsson06386552009-08-27 17:18:13 +0000673
Douglas Gregord45210d2009-01-30 22:09:00 +0000674 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000675 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregord45210d2009-01-30 22:09:00 +0000676 "initializing"))
677 hadError = true;
678 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
679 ++Index;
680 return;
681 }
682
683 // Fall through for subaggregate initialization
684 } else {
685 // C99 6.7.8p13:
686 //
687 // The initializer for a structure or union object that has
688 // automatic storage duration shall be either an initializer
689 // list as described below, or a single expression that has
690 // compatible structure or union type. In the latter case, the
691 // initial value of the object, including unnamed members, is
692 // that of the expression.
Eli Friedman2a553812009-06-13 10:38:46 +0000693 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman95acf982009-05-29 18:22:49 +0000694 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000695 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
696 ++Index;
697 return;
698 }
699
700 // Fall through for subaggregate initialization
701 }
702
703 // C++ [dcl.init.aggr]p12:
704 //
705 // [...] Otherwise, if the member is itself a non-empty
706 // subaggregate, brace elision is assumed and the initializer is
707 // considered for the initialization of the first member of
708 // the subaggregate.
709 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
710 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
711 StructuredIndex);
712 ++StructuredIndex;
713 } else {
714 // We cannot initialize this element, so let
715 // PerformCopyInitialization produce the appropriate diagnostic.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000716 SemaRef.PerformCopyInitialization(expr, ElemType, "initializing");
Douglas Gregord45210d2009-01-30 22:09:00 +0000717 hadError = true;
718 ++Index;
719 ++StructuredIndex;
720 }
721 }
Eli Friedman683cedf2008-05-19 19:16:24 +0000722}
723
Douglas Gregord45210d2009-01-30 22:09:00 +0000724void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor36859eb2009-01-29 00:39:20 +0000725 unsigned &Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000726 InitListExpr *StructuredList,
727 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000728 if (Index < IList->getNumInits()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000729 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000730 if (isa<InitListExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000731 SemaRef.Diag(IList->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000732 diag::err_many_braces_around_scalar_init)
733 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000734 hadError = true;
735 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000736 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000737 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000738 } else if (isa<DesignatedInitExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000739 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000740 diag::err_designator_for_scalar_init)
741 << DeclType << expr->getSourceRange();
742 hadError = true;
743 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000744 ++StructuredIndex;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000745 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000746 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000747
Eli Friedmand8535af2008-05-19 20:00:43 +0000748 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000749 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedman71de9eb2008-05-19 20:12:18 +0000750 hadError = true; // types weren't compatible.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000751 else if (savExpr != expr) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000752 // The type was promoted, update initializer list.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000753 IList->setInit(Index, expr);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000754 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000755 if (hadError)
756 ++StructuredIndex;
757 else
758 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000759 ++Index;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000760 } else {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000761 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattner9d2cf082008-11-19 05:27:50 +0000762 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000763 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000764 ++Index;
765 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000766 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000767 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000768}
769
Douglas Gregord45210d2009-01-30 22:09:00 +0000770void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
771 unsigned &Index,
772 InitListExpr *StructuredList,
773 unsigned &StructuredIndex) {
774 if (Index < IList->getNumInits()) {
775 Expr *expr = IList->getInit(Index);
776 if (isa<InitListExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000777 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord45210d2009-01-30 22:09:00 +0000778 << DeclType << IList->getSourceRange();
779 hadError = true;
780 ++Index;
781 ++StructuredIndex;
782 return;
783 }
784
785 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Anders Carlsson8f809f92009-08-27 17:30:43 +0000786 if (SemaRef.CheckReferenceInit(expr, DeclType,
787 /*SuppressUserConversions=*/false,
788 /*AllowExplicit=*/false,
789 /*ForceRValue=*/false))
Douglas Gregord45210d2009-01-30 22:09:00 +0000790 hadError = true;
791 else if (savExpr != expr) {
792 // The type was promoted, update initializer list.
793 IList->setInit(Index, expr);
794 }
795 if (hadError)
796 ++StructuredIndex;
797 else
798 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
799 ++Index;
800 } else {
Mike Stumpe127ae32009-05-16 07:39:55 +0000801 // FIXME: It would be wonderful if we could point at the actual member. In
802 // general, it would be useful to pass location information down the stack,
803 // so that we know the location (or decl) of the "current object" being
804 // initialized.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000805 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord45210d2009-01-30 22:09:00 +0000806 diag::err_init_reference_member_uninitialized)
807 << DeclType
808 << IList->getSourceRange();
809 hadError = true;
810 ++Index;
811 ++StructuredIndex;
812 return;
813 }
814}
815
Steve Naroffc4d4a482008-05-01 22:18:59 +0000816void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000817 unsigned &Index,
818 InitListExpr *StructuredList,
819 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000820 if (Index < IList->getNumInits()) {
821 const VectorType *VT = DeclType->getAsVectorType();
Nate Begemane85f43d2009-08-10 23:49:36 +0000822 unsigned maxElements = VT->getNumElements();
823 unsigned numEltsInit = 0;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000824 QualType elementType = VT->getElementType();
825
Nate Begemane85f43d2009-08-10 23:49:36 +0000826 if (!SemaRef.getLangOptions().OpenCL) {
827 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
828 // Don't attempt to go past the end of the init list
829 if (Index >= IList->getNumInits())
830 break;
831 CheckSubElementType(IList, elementType, Index,
832 StructuredList, StructuredIndex);
833 }
834 } else {
835 // OpenCL initializers allows vectors to be constructed from vectors.
836 for (unsigned i = 0; i < maxElements; ++i) {
837 // Don't attempt to go past the end of the init list
838 if (Index >= IList->getNumInits())
839 break;
840 QualType IType = IList->getInit(Index)->getType();
841 if (!IType->isVectorType()) {
842 CheckSubElementType(IList, elementType, Index,
843 StructuredList, StructuredIndex);
844 ++numEltsInit;
845 } else {
846 const VectorType *IVT = IType->getAsVectorType();
847 unsigned numIElts = IVT->getNumElements();
848 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
849 numIElts);
850 CheckSubElementType(IList, VecType, Index,
851 StructuredList, StructuredIndex);
852 numEltsInit += numIElts;
853 }
854 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000855 }
Nate Begemane85f43d2009-08-10 23:49:36 +0000856
857 // OpenCL & AltiVec require all elements to be initialized.
858 if (numEltsInit != maxElements)
859 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
860 SemaRef.Diag(IList->getSourceRange().getBegin(),
861 diag::err_vector_incorrect_num_initializers)
862 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000863 }
864}
865
866void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000867 llvm::APSInt elementIndex,
868 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000869 unsigned &Index,
870 InitListExpr *StructuredList,
871 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000872 // Check for the special-case of initializing an array with a string.
873 if (Index < IList->getNumInits()) {
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000874 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
875 SemaRef.Context)) {
876 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregorf603b472009-01-28 21:54:33 +0000877 // We place the string literal directly into the resulting
878 // initializer list. This is the only place where the structure
879 // of the structured initializer list doesn't match exactly,
880 // because doing so would involve allocating one character
881 // constant for each string.
Chris Lattner45d6fd62009-02-24 22:41:04 +0000882 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner2e2766a2009-02-24 22:50:46 +0000883 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000884 ++Index;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000885 return;
886 }
887 }
Chris Lattnera1923f62008-08-04 07:31:14 +0000888 if (const VariableArrayType *VAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000889 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman46f81662008-05-25 13:22:35 +0000890 // Check for VLAs; in standard C it would be possible to check this
891 // earlier, but I don't know where clang accepts VLAs (gcc accepts
892 // them in all sorts of strange places).
Chris Lattner2e2766a2009-02-24 22:50:46 +0000893 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000894 diag::err_variable_object_no_init)
895 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman46f81662008-05-25 13:22:35 +0000896 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000897 ++Index;
898 ++StructuredIndex;
Eli Friedman46f81662008-05-25 13:22:35 +0000899 return;
900 }
901
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000902 // We might know the maximum number of elements in advance.
Douglas Gregorf603b472009-01-28 21:54:33 +0000903 llvm::APSInt maxElements(elementIndex.getBitWidth(),
904 elementIndex.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000905 bool maxElementsKnown = false;
906 if (const ConstantArrayType *CAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000907 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000908 maxElements = CAT->getSize();
Douglas Gregor5a203a62009-01-23 16:54:12 +0000909 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000910 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000911 maxElementsKnown = true;
912 }
913
Chris Lattner2e2766a2009-02-24 22:50:46 +0000914 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnera1923f62008-08-04 07:31:14 +0000915 ->getElementType();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000916 while (Index < IList->getNumInits()) {
917 Expr *Init = IList->getInit(Index);
918 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000919 // If we're not the subobject that matches up with the '{' for
920 // the designator, we shouldn't be handling the
921 // designator. Return immediately.
922 if (!SubobjectIsDesignatorContext)
923 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000924
Douglas Gregor710f6d42009-01-22 23:26:18 +0000925 // Handle this designated initializer. elementIndex will be
926 // updated to be the next array element we'll initialize.
Douglas Gregoraa357272009-04-15 04:56:10 +0000927 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregorf603b472009-01-28 21:54:33 +0000928 DeclType, 0, &elementIndex, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000929 StructuredList, StructuredIndex, true,
930 false)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000931 hadError = true;
932 continue;
933 }
934
Douglas Gregor5a203a62009-01-23 16:54:12 +0000935 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
936 maxElements.extend(elementIndex.getBitWidth());
937 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
938 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000939 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor5a203a62009-01-23 16:54:12 +0000940
Douglas Gregor710f6d42009-01-22 23:26:18 +0000941 // If the array is of incomplete type, keep track of the number of
942 // elements in the initializer.
943 if (!maxElementsKnown && elementIndex > maxElements)
944 maxElements = elementIndex;
945
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000946 continue;
947 }
948
949 // If we know the maximum number of elements, and we've already
950 // hit it, stop consuming elements in the initializer list.
951 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000952 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000953
954 // Check this element.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000955 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000956 StructuredList, StructuredIndex);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000957 ++elementIndex;
958
959 // If the array is of incomplete type, keep track of the number of
960 // elements in the initializer.
961 if (!maxElementsKnown && elementIndex > maxElements)
962 maxElements = elementIndex;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000963 }
Eli Friedmanb4c71b32009-05-29 20:17:55 +0000964 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000965 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000966 // be calculated here.
Douglas Gregor69722702009-01-23 18:58:42 +0000967 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000968 if (maxElements == Zero) {
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000969 // Sizing an array implicitly to zero is not allowed by ISO C,
970 // but is supported by GNU.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000971 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000972 diag::ext_typecheck_zero_array_size);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000973 }
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000974
Chris Lattner2e2766a2009-02-24 22:50:46 +0000975 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000976 ArrayType::Normal, 0);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000977 }
978}
979
980void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
981 QualType DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000982 RecordDecl::field_iterator Field,
983 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000984 unsigned &Index,
985 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000986 unsigned &StructuredIndex,
987 bool TopLevelObject) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000988 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000989
Eli Friedman683cedf2008-05-19 19:16:24 +0000990 // If the record is invalid, some of it's members are invalid. To avoid
991 // confusion, we forgo checking the intializer for the entire record.
992 if (structDecl->isInvalidDecl()) {
993 hadError = true;
994 return;
995 }
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000996
997 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
998 // Value-initialize the first named member of the union.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000999 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001000 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregorc9e012a2009-01-29 17:44:32 +00001001 Field != FieldEnd; ++Field) {
1002 if (Field->getDeclName()) {
1003 StructuredList->setInitializedFieldInUnion(*Field);
1004 break;
1005 }
1006 }
1007 return;
1008 }
1009
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001010 // If structDecl is a forward declaration, this loop won't do
1011 // anything except look at designated initializers; That's okay,
1012 // because an error should get printed out elsewhere. It might be
1013 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001014 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001015 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001016 bool InitializedSomething = false;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001017 while (Index < IList->getNumInits()) {
1018 Expr *Init = IList->getInit(Index);
1019
1020 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001021 // If we're not the subobject that matches up with the '{' for
1022 // the designator, we shouldn't be handling the
1023 // designator. Return immediately.
1024 if (!SubobjectIsDesignatorContext)
1025 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001026
Douglas Gregor710f6d42009-01-22 23:26:18 +00001027 // Handle this designated initializer. Field will be updated to
1028 // the next field that we'll be initializing.
Douglas Gregoraa357272009-04-15 04:56:10 +00001029 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregorf603b472009-01-28 21:54:33 +00001030 DeclType, &Field, 0, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001031 StructuredList, StructuredIndex,
1032 true, TopLevelObject))
Douglas Gregor710f6d42009-01-22 23:26:18 +00001033 hadError = true;
1034
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001035 InitializedSomething = true;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001036 continue;
1037 }
1038
1039 if (Field == FieldEnd) {
1040 // We've run out of fields. We're done.
1041 break;
1042 }
1043
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001044 // We've already initialized a member of a union. We're done.
1045 if (InitializedSomething && DeclType->isUnionType())
1046 break;
1047
Douglas Gregor8acb7272008-12-11 16:49:14 +00001048 // If we've hit the flexible array member at the end, we're done.
1049 if (Field->getType()->isIncompleteArrayType())
1050 break;
1051
Douglas Gregor82462762009-01-29 16:53:55 +00001052 if (Field->isUnnamedBitfield()) {
Douglas Gregorf603b472009-01-28 21:54:33 +00001053 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001054 ++Field;
Eli Friedman683cedf2008-05-19 19:16:24 +00001055 continue;
Steve Naroffc4d4a482008-05-01 22:18:59 +00001056 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001057
Douglas Gregor36859eb2009-01-29 00:39:20 +00001058 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001059 StructuredList, StructuredIndex);
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001060 InitializedSomething = true;
Douglas Gregor82462762009-01-29 16:53:55 +00001061
1062 if (DeclType->isUnionType()) {
1063 // Initialize the first field within the union.
1064 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor82462762009-01-29 16:53:55 +00001065 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001066
1067 ++Field;
Steve Naroffc4d4a482008-05-01 22:18:59 +00001068 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001069
Douglas Gregorbe69b162009-02-04 22:46:25 +00001070 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001071 Index >= IList->getNumInits())
Douglas Gregorbe69b162009-02-04 22:46:25 +00001072 return;
1073
1074 // Handle GNU flexible array initializers.
1075 if (!TopLevelObject &&
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001076 (!isa<InitListExpr>(IList->getInit(Index)) ||
1077 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001078 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001079 diag::err_flexible_array_init_nonempty)
1080 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001081 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001082 << *Field;
1083 hadError = true;
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001084 ++Index;
1085 return;
1086 } else {
1087 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
1088 diag::ext_flexible_array_init)
1089 << IList->getInit(Index)->getSourceRange().getBegin();
1090 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1091 << *Field;
Douglas Gregorbe69b162009-02-04 22:46:25 +00001092 }
1093
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001094 if (isa<InitListExpr>(IList->getInit(Index)))
1095 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1096 StructuredIndex);
1097 else
1098 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1099 StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +00001100}
Steve Naroffc4d4a482008-05-01 22:18:59 +00001101
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001102/// \brief Expand a field designator that refers to a member of an
1103/// anonymous struct or union into a series of field designators that
1104/// refers to the field within the appropriate subobject.
1105///
1106/// Field/FieldIndex will be updated to point to the (new)
1107/// currently-designated field.
1108static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1109 DesignatedInitExpr *DIE,
1110 unsigned DesigIdx,
1111 FieldDecl *Field,
1112 RecordDecl::field_iterator &FieldIter,
1113 unsigned &FieldIndex) {
1114 typedef DesignatedInitExpr::Designator Designator;
1115
1116 // Build the path from the current object to the member of the
1117 // anonymous struct/union (backwards).
1118 llvm::SmallVector<FieldDecl *, 4> Path;
1119 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
1120
1121 // Build the replacement designators.
1122 llvm::SmallVector<Designator, 4> Replacements;
1123 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1124 FI = Path.rbegin(), FIEnd = Path.rend();
1125 FI != FIEnd; ++FI) {
1126 if (FI + 1 == FIEnd)
1127 Replacements.push_back(Designator((IdentifierInfo *)0,
1128 DIE->getDesignator(DesigIdx)->getDotLoc(),
1129 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1130 else
1131 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1132 SourceLocation()));
1133 Replacements.back().setField(*FI);
1134 }
1135
1136 // Expand the current designator into the set of replacement
1137 // designators, so we have a full subobject path down to where the
1138 // member of the anonymous struct/union is actually stored.
1139 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
1140 &Replacements[0] + Replacements.size());
1141
1142 // Update FieldIter/FieldIndex;
1143 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001144 FieldIter = Record->field_begin();
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001145 FieldIndex = 0;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001146 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001147 FieldIter != FEnd; ++FieldIter) {
1148 if (FieldIter->isUnnamedBitfield())
1149 continue;
1150
1151 if (*FieldIter == Path.back())
1152 return;
1153
1154 ++FieldIndex;
1155 }
1156
1157 assert(false && "Unable to find anonymous struct/union field");
1158}
1159
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001160/// @brief Check the well-formedness of a C99 designated initializer.
1161///
1162/// Determines whether the designated initializer @p DIE, which
1163/// resides at the given @p Index within the initializer list @p
1164/// IList, is well-formed for a current object of type @p DeclType
1165/// (C99 6.7.8). The actual subobject that this designator refers to
1166/// within the current subobject is returned in either
Douglas Gregorf603b472009-01-28 21:54:33 +00001167/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001168///
1169/// @param IList The initializer list in which this designated
1170/// initializer occurs.
1171///
Douglas Gregoraa357272009-04-15 04:56:10 +00001172/// @param DIE The designated initializer expression.
1173///
1174/// @param DesigIdx The index of the current designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001175///
1176/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1177/// into which the designation in @p DIE should refer.
1178///
Douglas Gregor710f6d42009-01-22 23:26:18 +00001179/// @param NextField If non-NULL and the first designator in @p DIE is
1180/// a field, this will be set to the field declaration corresponding
1181/// to the field named by the designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001182///
Douglas Gregor710f6d42009-01-22 23:26:18 +00001183/// @param NextElementIndex If non-NULL and the first designator in @p
1184/// DIE is an array designator or GNU array-range designator, this
1185/// will be set to the last index initialized by this designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001186///
1187/// @param Index Index into @p IList where the designated initializer
1188/// @p DIE occurs.
1189///
Douglas Gregorf603b472009-01-28 21:54:33 +00001190/// @param StructuredList The initializer list expression that
1191/// describes all of the subobject initializers in the order they'll
1192/// actually be initialized.
1193///
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001194/// @returns true if there was an error, false otherwise.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001195bool
1196InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
1197 DesignatedInitExpr *DIE,
Douglas Gregoraa357272009-04-15 04:56:10 +00001198 unsigned DesigIdx,
Douglas Gregor710f6d42009-01-22 23:26:18 +00001199 QualType &CurrentObjectType,
1200 RecordDecl::field_iterator *NextField,
1201 llvm::APSInt *NextElementIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +00001202 unsigned &Index,
1203 InitListExpr *StructuredList,
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001204 unsigned &StructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001205 bool FinishSubobjectInit,
1206 bool TopLevelObject) {
Douglas Gregoraa357272009-04-15 04:56:10 +00001207 if (DesigIdx == DIE->size()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001208 // Check the actual initialization for the designated object type.
1209 bool prevHadError = hadError;
Douglas Gregor36859eb2009-01-29 00:39:20 +00001210
1211 // Temporarily remove the designator expression from the
1212 // initializer list that the child calls see, so that we don't try
1213 // to re-process the designator.
1214 unsigned OldIndex = Index;
1215 IList->setInit(OldIndex, DIE->getInit());
1216
1217 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001218 StructuredList, StructuredIndex);
Douglas Gregor36859eb2009-01-29 00:39:20 +00001219
1220 // Restore the designated initializer expression in the syntactic
1221 // form of the initializer list.
1222 if (IList->getInit(OldIndex) != DIE->getInit())
1223 DIE->setInit(IList->getInit(OldIndex));
1224 IList->setInit(OldIndex, DIE);
1225
Douglas Gregor710f6d42009-01-22 23:26:18 +00001226 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001227 }
1228
Douglas Gregoraa357272009-04-15 04:56:10 +00001229 bool IsFirstDesignator = (DesigIdx == 0);
Douglas Gregorf603b472009-01-28 21:54:33 +00001230 assert((IsFirstDesignator || StructuredList) &&
1231 "Need a non-designated initializer list to start from");
1232
Douglas Gregoraa357272009-04-15 04:56:10 +00001233 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregorf603b472009-01-28 21:54:33 +00001234 // Determine the structural initializer list that corresponds to the
1235 // current subobject.
1236 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Douglas Gregorea765e12009-03-01 17:12:46 +00001237 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1238 StructuredList, StructuredIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +00001239 SourceRange(D->getStartLocation(),
1240 DIE->getSourceRange().getEnd()));
1241 assert(StructuredList && "Expected a structured initializer list");
1242
Douglas Gregor710f6d42009-01-22 23:26:18 +00001243 if (D->isFieldDesignator()) {
1244 // C99 6.7.8p7:
1245 //
1246 // If a designator has the form
1247 //
1248 // . identifier
1249 //
1250 // then the current object (defined below) shall have
1251 // structure or union type and the identifier shall be the
1252 // name of a member of that type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001253 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001254 if (!RT) {
1255 SourceLocation Loc = D->getDotLoc();
1256 if (Loc.isInvalid())
1257 Loc = D->getFieldLoc();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001258 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1259 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001260 ++Index;
1261 return true;
1262 }
1263
Douglas Gregorf603b472009-01-28 21:54:33 +00001264 // Note: we perform a linear search of the fields here, despite
1265 // the fact that we have a faster lookup method, because we always
1266 // need to compute the field's index.
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001267 FieldDecl *KnownField = D->getField();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001268 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregorf603b472009-01-28 21:54:33 +00001269 unsigned FieldIndex = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001270 RecordDecl::field_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001271 Field = RT->getDecl()->field_begin(),
1272 FieldEnd = RT->getDecl()->field_end();
Douglas Gregorf603b472009-01-28 21:54:33 +00001273 for (; Field != FieldEnd; ++Field) {
1274 if (Field->isUnnamedBitfield())
1275 continue;
1276
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001277 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregorf603b472009-01-28 21:54:33 +00001278 break;
1279
1280 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001281 }
1282
Douglas Gregorf603b472009-01-28 21:54:33 +00001283 if (Field == FieldEnd) {
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001284 // There was no normal field in the struct with the designated
1285 // name. Perform another lookup for this name, which may find
1286 // something that we can't designate (e.g., a member function),
1287 // may find nothing, or may find a member of an anonymous
1288 // struct/union.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001289 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorf603b472009-01-28 21:54:33 +00001290 if (Lookup.first == Lookup.second) {
1291 // Name lookup didn't find anything.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001292 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregorf603b472009-01-28 21:54:33 +00001293 << FieldName << CurrentObjectType;
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001294 ++Index;
1295 return true;
1296 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1297 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1298 ->isAnonymousStructOrUnion()) {
1299 // Handle an field designator that refers to a member of an
1300 // anonymous struct or union.
1301 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1302 cast<FieldDecl>(*Lookup.first),
1303 Field, FieldIndex);
Eli Friedmanbd45b552009-04-16 17:49:48 +00001304 D = DIE->getDesignator(DesigIdx);
Douglas Gregorf603b472009-01-28 21:54:33 +00001305 } else {
1306 // Name lookup found something, but it wasn't a field.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001307 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregorf603b472009-01-28 21:54:33 +00001308 << FieldName;
Chris Lattner2e2766a2009-02-24 22:50:46 +00001309 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001310 diag::note_field_designator_found);
Eli Friedmanbd45b552009-04-16 17:49:48 +00001311 ++Index;
1312 return true;
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001313 }
1314 } else if (!KnownField &&
1315 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregorf603b472009-01-28 21:54:33 +00001316 ->isAnonymousStructOrUnion()) {
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001317 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1318 Field, FieldIndex);
1319 D = DIE->getDesignator(DesigIdx);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001320 }
Douglas Gregorf603b472009-01-28 21:54:33 +00001321
1322 // All of the fields of a union are located at the same place in
1323 // the initializer list.
Douglas Gregor82462762009-01-29 16:53:55 +00001324 if (RT->getDecl()->isUnion()) {
Douglas Gregorf603b472009-01-28 21:54:33 +00001325 FieldIndex = 0;
Douglas Gregor82462762009-01-29 16:53:55 +00001326 StructuredList->setInitializedFieldInUnion(*Field);
1327 }
Douglas Gregorf603b472009-01-28 21:54:33 +00001328
Douglas Gregor710f6d42009-01-22 23:26:18 +00001329 // Update the designator with the field declaration.
Douglas Gregorf603b472009-01-28 21:54:33 +00001330 D->setField(*Field);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001331
Douglas Gregorf603b472009-01-28 21:54:33 +00001332 // Make sure that our non-designated initializer list has space
1333 // for a subobject corresponding to this field.
1334 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner2e2766a2009-02-24 22:50:46 +00001335 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +00001336
Douglas Gregorbe69b162009-02-04 22:46:25 +00001337 // This designator names a flexible array member.
1338 if (Field->getType()->isIncompleteArrayType()) {
1339 bool Invalid = false;
Douglas Gregoraa357272009-04-15 04:56:10 +00001340 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorbe69b162009-02-04 22:46:25 +00001341 // We can't designate an object within the flexible array
1342 // member (because GCC doesn't allow it).
Douglas Gregoraa357272009-04-15 04:56:10 +00001343 DesignatedInitExpr::Designator *NextD
1344 = DIE->getDesignator(DesigIdx + 1);
Chris Lattner2e2766a2009-02-24 22:50:46 +00001345 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001346 diag::err_designator_into_flexible_array_member)
1347 << SourceRange(NextD->getStartLocation(),
1348 DIE->getSourceRange().getEnd());
Chris Lattner2e2766a2009-02-24 22:50:46 +00001349 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001350 << *Field;
1351 Invalid = true;
1352 }
1353
1354 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1355 // The initializer is not an initializer list.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001356 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001357 diag::err_flexible_array_init_needs_braces)
1358 << DIE->getInit()->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001359 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001360 << *Field;
1361 Invalid = true;
1362 }
1363
1364 // Handle GNU flexible array initializers.
1365 if (!Invalid && !TopLevelObject &&
1366 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001367 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001368 diag::err_flexible_array_init_nonempty)
1369 << DIE->getSourceRange().getBegin();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001370 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001371 << *Field;
1372 Invalid = true;
1373 }
1374
1375 if (Invalid) {
1376 ++Index;
1377 return true;
1378 }
1379
1380 // Initialize the array.
1381 bool prevHadError = hadError;
1382 unsigned newStructuredIndex = FieldIndex;
1383 unsigned OldIndex = Index;
1384 IList->setInit(Index, DIE->getInit());
1385 CheckSubElementType(IList, Field->getType(), Index,
1386 StructuredList, newStructuredIndex);
1387 IList->setInit(OldIndex, DIE);
1388 if (hadError && !prevHadError) {
1389 ++Field;
1390 ++FieldIndex;
1391 if (NextField)
1392 *NextField = Field;
1393 StructuredIndex = FieldIndex;
1394 return true;
1395 }
1396 } else {
1397 // Recurse to check later designated subobjects.
1398 QualType FieldType = (*Field)->getType();
1399 unsigned newStructuredIndex = FieldIndex;
Douglas Gregoraa357272009-04-15 04:56:10 +00001400 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1401 Index, StructuredList, newStructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001402 true, false))
1403 return true;
1404 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001405
1406 // Find the position of the next field to be initialized in this
1407 // subobject.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001408 ++Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001409 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001410
1411 // If this the first designator, our caller will continue checking
1412 // the rest of this struct/class/union subobject.
1413 if (IsFirstDesignator) {
1414 if (NextField)
1415 *NextField = Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001416 StructuredIndex = FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001417 return false;
1418 }
1419
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001420 if (!FinishSubobjectInit)
1421 return false;
1422
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001423 // We've already initialized something in the union; we're done.
1424 if (RT->getDecl()->isUnion())
1425 return hadError;
1426
Douglas Gregor710f6d42009-01-22 23:26:18 +00001427 // Check the remaining fields within this class/struct/union subobject.
1428 bool prevHadError = hadError;
Douglas Gregorf603b472009-01-28 21:54:33 +00001429 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1430 StructuredList, FieldIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001431 return hadError && !prevHadError;
1432 }
1433
1434 // C99 6.7.8p6:
1435 //
1436 // If a designator has the form
1437 //
1438 // [ constant-expression ]
1439 //
1440 // then the current object (defined below) shall have array
1441 // type and the expression shall be an integer constant
1442 // expression. If the array is of unknown size, any
1443 // nonnegative value is valid.
1444 //
1445 // Additionally, cope with the GNU extension that permits
1446 // designators of the form
1447 //
1448 // [ constant-expression ... constant-expression ]
Chris Lattner2e2766a2009-02-24 22:50:46 +00001449 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001450 if (!AT) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001451 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor710f6d42009-01-22 23:26:18 +00001452 << CurrentObjectType;
1453 ++Index;
1454 return true;
1455 }
1456
1457 Expr *IndexExpr = 0;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001458 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1459 if (D->isArrayDesignator()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001460 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnereec8ae22009-04-25 21:59:05 +00001461 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001462 DesignatedEndIndex = DesignatedStartIndex;
1463 } else {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001464 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001465
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001466
Chris Lattnereec8ae22009-04-25 21:59:05 +00001467 DesignatedStartIndex =
1468 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
1469 DesignatedEndIndex =
1470 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001471 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001472
Chris Lattnereec8ae22009-04-25 21:59:05 +00001473 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregor9fddded2009-01-29 19:42:23 +00001474 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001475 }
1476
Douglas Gregor710f6d42009-01-22 23:26:18 +00001477 if (isa<ConstantArrayType>(AT)) {
1478 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001479 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1480 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1481 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1482 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1483 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001484 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor710f6d42009-01-22 23:26:18 +00001485 diag::err_array_designator_too_large)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001486 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor710f6d42009-01-22 23:26:18 +00001487 << IndexExpr->getSourceRange();
1488 ++Index;
1489 return true;
1490 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001491 } else {
1492 // Make sure the bit-widths and signedness match.
1493 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1494 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnereec8ae22009-04-25 21:59:05 +00001495 else if (DesignatedStartIndex.getBitWidth() <
1496 DesignatedEndIndex.getBitWidth())
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001497 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1498 DesignatedStartIndex.setIsUnsigned(true);
1499 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001500 }
1501
Douglas Gregorf603b472009-01-28 21:54:33 +00001502 // Make sure that our non-designated initializer list has space
1503 // for a subobject corresponding to this array element.
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001504 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Chris Lattner2e2766a2009-02-24 22:50:46 +00001505 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001506 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +00001507
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001508 // Repeatedly perform subobject initializations in the range
1509 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor710f6d42009-01-22 23:26:18 +00001510
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001511 // Move to the next designator
1512 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1513 unsigned OldIndex = Index;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001514 while (DesignatedStartIndex <= DesignatedEndIndex) {
1515 // Recurse to check later designated subobjects.
1516 QualType ElementType = AT->getElementType();
1517 Index = OldIndex;
Douglas Gregoraa357272009-04-15 04:56:10 +00001518 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1519 Index, StructuredList, ElementIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001520 (DesignatedStartIndex == DesignatedEndIndex),
1521 false))
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001522 return true;
1523
1524 // Move to the next index in the array that we'll be initializing.
1525 ++DesignatedStartIndex;
1526 ElementIndex = DesignatedStartIndex.getZExtValue();
1527 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001528
1529 // If this the first designator, our caller will continue checking
1530 // the rest of this array subobject.
1531 if (IsFirstDesignator) {
1532 if (NextElementIndex)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001533 *NextElementIndex = DesignatedStartIndex;
Douglas Gregorf603b472009-01-28 21:54:33 +00001534 StructuredIndex = ElementIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001535 return false;
1536 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001537
1538 if (!FinishSubobjectInit)
1539 return false;
1540
Douglas Gregor710f6d42009-01-22 23:26:18 +00001541 // Check the remaining elements within this array subobject.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001542 bool prevHadError = hadError;
Douglas Gregord7e76c52009-02-09 19:45:19 +00001543 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001544 StructuredList, ElementIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001545 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001546}
1547
Douglas Gregorf603b472009-01-28 21:54:33 +00001548// Get the structured initializer list for a subobject of type
1549// @p CurrentObjectType.
1550InitListExpr *
1551InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1552 QualType CurrentObjectType,
1553 InitListExpr *StructuredList,
1554 unsigned StructuredIndex,
1555 SourceRange InitRange) {
1556 Expr *ExistingInit = 0;
1557 if (!StructuredList)
1558 ExistingInit = SyntacticToSemantic[IList];
1559 else if (StructuredIndex < StructuredList->getNumInits())
1560 ExistingInit = StructuredList->getInit(StructuredIndex);
1561
1562 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1563 return Result;
1564
1565 if (ExistingInit) {
1566 // We are creating an initializer list that initializes the
1567 // subobjects of the current object, but there was already an
1568 // initialization that completely initialized the current
1569 // subobject, e.g., by a compound literal:
1570 //
1571 // struct X { int a, b; };
1572 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1573 //
1574 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1575 // designated initializer re-initializes the whole
1576 // subobject [0], overwriting previous initializers.
Douglas Gregorea765e12009-03-01 17:12:46 +00001577 SemaRef.Diag(InitRange.getBegin(),
1578 diag::warn_subobject_initializer_overrides)
Douglas Gregorf603b472009-01-28 21:54:33 +00001579 << InitRange;
Chris Lattner2e2766a2009-02-24 22:50:46 +00001580 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001581 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001582 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001583 << ExistingInit->getSourceRange();
1584 }
1585
1586 InitListExpr *Result
Douglas Gregorea765e12009-03-01 17:12:46 +00001587 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
1588 InitRange.getEnd());
1589
Douglas Gregorf603b472009-01-28 21:54:33 +00001590 Result->setType(CurrentObjectType);
1591
Douglas Gregoree0792c2009-03-20 23:58:33 +00001592 // Pre-allocate storage for the structured initializer list.
1593 unsigned NumElements = 0;
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001594 unsigned NumInits = 0;
1595 if (!StructuredList)
1596 NumInits = IList->getNumInits();
1597 else if (Index < IList->getNumInits()) {
1598 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1599 NumInits = SubList->getNumInits();
1600 }
1601
Douglas Gregoree0792c2009-03-20 23:58:33 +00001602 if (const ArrayType *AType
1603 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1604 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1605 NumElements = CAType->getSize().getZExtValue();
1606 // Simple heuristic so that we don't allocate a very large
1607 // initializer with many empty entries at the end.
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001608 if (NumInits && NumElements > NumInits)
Douglas Gregoree0792c2009-03-20 23:58:33 +00001609 NumElements = 0;
1610 }
1611 } else if (const VectorType *VType = CurrentObjectType->getAsVectorType())
1612 NumElements = VType->getNumElements();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001613 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregoree0792c2009-03-20 23:58:33 +00001614 RecordDecl *RDecl = RType->getDecl();
1615 if (RDecl->isUnion())
1616 NumElements = 1;
1617 else
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001618 NumElements = std::distance(RDecl->field_begin(),
1619 RDecl->field_end());
Douglas Gregoree0792c2009-03-20 23:58:33 +00001620 }
1621
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001622 if (NumElements < NumInits)
Douglas Gregoree0792c2009-03-20 23:58:33 +00001623 NumElements = IList->getNumInits();
1624
1625 Result->reserveInits(NumElements);
1626
Douglas Gregorf603b472009-01-28 21:54:33 +00001627 // Link this new initializer list into the structured initializer
1628 // lists.
1629 if (StructuredList)
1630 StructuredList->updateInit(StructuredIndex, Result);
1631 else {
1632 Result->setSyntacticForm(IList);
1633 SyntacticToSemantic[IList] = Result;
1634 }
1635
1636 return Result;
1637}
1638
1639/// Update the initializer at index @p StructuredIndex within the
1640/// structured initializer list to the value @p expr.
1641void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1642 unsigned &StructuredIndex,
1643 Expr *expr) {
1644 // No structured initializer list to update
1645 if (!StructuredList)
1646 return;
1647
1648 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1649 // This initializer overwrites a previous initializer. Warn.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001650 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001651 diag::warn_initializer_overrides)
1652 << expr->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001653 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001654 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001655 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001656 << PrevInit->getSourceRange();
1657 }
1658
1659 ++StructuredIndex;
1660}
1661
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001662/// Check that the given Index expression is a valid array designator
1663/// value. This is essentailly just a wrapper around
Chris Lattnereec8ae22009-04-25 21:59:05 +00001664/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001665/// and produces a reasonable diagnostic if there is a
1666/// failure. Returns true if there was an error, false otherwise. If
1667/// everything went okay, Value will receive the value of the constant
1668/// expression.
1669static bool
Chris Lattnereec8ae22009-04-25 21:59:05 +00001670CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001671 SourceLocation Loc = Index->getSourceRange().getBegin();
1672
1673 // Make sure this is an integer constant expression.
Chris Lattnereec8ae22009-04-25 21:59:05 +00001674 if (S.VerifyIntegerConstantExpression(Index, &Value))
1675 return true;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001676
Chris Lattnereec8ae22009-04-25 21:59:05 +00001677 if (Value.isSigned() && Value.isNegative())
1678 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001679 << Value.toString(10) << Index->getSourceRange();
1680
Douglas Gregore498e372009-01-23 21:04:18 +00001681 Value.setIsUnsigned(true);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001682 return false;
1683}
1684
1685Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1686 SourceLocation Loc,
Douglas Gregor5f34f0e2009-03-28 00:41:23 +00001687 bool GNUSyntax,
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001688 OwningExprResult Init) {
1689 typedef DesignatedInitExpr::Designator ASTDesignator;
1690
1691 bool Invalid = false;
1692 llvm::SmallVector<ASTDesignator, 32> Designators;
1693 llvm::SmallVector<Expr *, 32> InitExpressions;
1694
1695 // Build designators and check array designator expressions.
1696 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1697 const Designator &D = Desig.getDesignator(Idx);
1698 switch (D.getKind()) {
1699 case Designator::FieldDesignator:
1700 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1701 D.getFieldLoc()));
1702 break;
1703
1704 case Designator::ArrayDesignator: {
1705 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1706 llvm::APSInt IndexValue;
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001707 if (!Index->isTypeDependent() &&
1708 !Index->isValueDependent() &&
1709 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001710 Invalid = true;
1711 else {
1712 Designators.push_back(ASTDesignator(InitExpressions.size(),
1713 D.getLBracketLoc(),
1714 D.getRBracketLoc()));
1715 InitExpressions.push_back(Index);
1716 }
1717 break;
1718 }
1719
1720 case Designator::ArrayRangeDesignator: {
1721 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1722 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1723 llvm::APSInt StartValue;
1724 llvm::APSInt EndValue;
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001725 bool StartDependent = StartIndex->isTypeDependent() ||
1726 StartIndex->isValueDependent();
1727 bool EndDependent = EndIndex->isTypeDependent() ||
1728 EndIndex->isValueDependent();
1729 if ((!StartDependent &&
1730 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1731 (!EndDependent &&
1732 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001733 Invalid = true;
Douglas Gregorea0528d2009-01-23 22:22:29 +00001734 else {
1735 // Make sure we're comparing values with the same bit width.
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001736 if (StartDependent || EndDependent) {
1737 // Nothing to compute.
1738 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregorea0528d2009-01-23 22:22:29 +00001739 EndValue.extend(StartValue.getBitWidth());
1740 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1741 StartValue.extend(EndValue.getBitWidth());
1742
Douglas Gregor1401c062009-05-21 23:30:39 +00001743 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregorea0528d2009-01-23 22:22:29 +00001744 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1745 << StartValue.toString(10) << EndValue.toString(10)
1746 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1747 Invalid = true;
1748 } else {
1749 Designators.push_back(ASTDesignator(InitExpressions.size(),
1750 D.getLBracketLoc(),
1751 D.getEllipsisLoc(),
1752 D.getRBracketLoc()));
1753 InitExpressions.push_back(StartIndex);
1754 InitExpressions.push_back(EndIndex);
1755 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001756 }
1757 break;
1758 }
1759 }
1760 }
1761
1762 if (Invalid || Init.isInvalid())
1763 return ExprError();
1764
1765 // Clear out the expressions within the designation.
1766 Desig.ClearExprs(*this);
1767
1768 DesignatedInitExpr *DIE
Jay Foad9e6bef42009-05-21 09:52:38 +00001769 = DesignatedInitExpr::Create(Context,
1770 Designators.data(), Designators.size(),
1771 InitExpressions.data(), InitExpressions.size(),
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001772 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001773 return Owned(DIE);
1774}
Douglas Gregor849afc32009-01-29 00:45:39 +00001775
1776bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001777 InitListChecker CheckInitList(*this, InitList, DeclType);
Douglas Gregor849afc32009-01-29 00:45:39 +00001778 if (!CheckInitList.HadError())
1779 InitList = CheckInitList.getFullyStructuredList();
1780
1781 return CheckInitList.HadError();
1782}
Douglas Gregor538a4c22009-02-02 17:43:21 +00001783
1784/// \brief Diagnose any semantic errors with value-initialization of
1785/// the given type.
1786///
1787/// Value-initialization effectively zero-initializes any types
1788/// without user-declared constructors, and calls the default
1789/// constructor for a for any type that has a user-declared
1790/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1791/// a type with a user-declared constructor does not have an
1792/// accessible, non-deleted default constructor. In C, everything can
1793/// be value-initialized, which corresponds to C's notion of
1794/// initializing objects with static storage duration when no
1795/// initializer is provided for that object.
1796///
1797/// \returns true if there was an error, false otherwise.
1798bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1799 // C++ [dcl.init]p5:
1800 //
1801 // To value-initialize an object of type T means:
1802
1803 // -- if T is an array type, then each element is value-initialized;
1804 if (const ArrayType *AT = Context.getAsArrayType(Type))
1805 return CheckValueInitialization(AT->getElementType(), Loc);
1806
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001807 if (const RecordType *RT = Type->getAs<RecordType>()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001808 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Douglas Gregor538a4c22009-02-02 17:43:21 +00001809 // -- if T is a class type (clause 9) with a user-declared
1810 // constructor (12.1), then the default constructor for T is
1811 // called (and the initialization is ill-formed if T has no
1812 // accessible default constructor);
Douglas Gregor2e047592009-02-28 01:32:25 +00001813 if (ClassDecl->hasUserDeclaredConstructor())
Mike Stumpe127ae32009-05-16 07:39:55 +00001814 // FIXME: Eventually, we'll need to put the constructor decl into the
1815 // AST.
Douglas Gregor538a4c22009-02-02 17:43:21 +00001816 return PerformInitializationByConstructor(Type, 0, 0, Loc,
1817 SourceRange(Loc),
1818 DeclarationName(),
1819 IK_Direct);
1820 }
1821 }
1822
1823 if (Type->isReferenceType()) {
1824 // C++ [dcl.init]p5:
1825 // [...] A program that calls for default-initialization or
1826 // value-initialization of an entity of reference type is
1827 // ill-formed. [...]
Mike Stumpe127ae32009-05-16 07:39:55 +00001828 // FIXME: Once we have code that goes through this path, add an actual
1829 // diagnostic :)
Douglas Gregor538a4c22009-02-02 17:43:21 +00001830 }
1831
1832 return false;
1833}