blob: 936d996ea49ca45014cafb77e41411cc3f9952a1 [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(),
185 DeclType, Constructor, &Init, 1);
Anders Carlsson665e4692009-08-25 05:12:04 +0000186 if (InitResult.isInvalid())
187 return true;
188
189 Init = InitResult.takeAs<Expr>();
Anders Carlsson73bb5e62009-05-27 16:10:08 +0000190 return false;
Chris Lattnerd3a00502009-02-24 22:27:37 +0000191 }
192
193 // -- Otherwise (i.e., for the remaining copy-initialization
194 // cases), user-defined conversion sequences that can
195 // convert from the source type to the destination type or
196 // (when a conversion function is used) to a derived class
197 // thereof are enumerated as described in 13.3.1.4, and the
198 // best one is chosen through overload resolution
199 // (13.3). If the conversion cannot be done or is
200 // ambiguous, the initialization is ill-formed. The
201 // function selected is called with the initializer
202 // expression as its argument; if the function is a
203 // constructor, the call initializes a temporary of the
204 // destination type.
Mike Stumpe127ae32009-05-16 07:39:55 +0000205 // FIXME: We're pretending to do copy elision here; return to this when we
206 // have ASTs for such things.
Chris Lattnerd3a00502009-02-24 22:27:37 +0000207 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
208 return false;
209
210 if (InitEntity)
211 return Diag(InitLoc, diag::err_cannot_initialize_decl)
Chris Lattner6434a1b2009-06-26 04:45:06 +0000212 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
213 << Init->getType() << Init->getSourceRange();
214 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
Chris Lattnerd3a00502009-02-24 22:27:37 +0000215 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
216 << Init->getType() << Init->getSourceRange();
217 }
218
219 // C99 6.7.8p16.
220 if (DeclType->isArrayType())
221 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
Chris Lattner6434a1b2009-06-26 04:45:06 +0000222 << Init->getSourceRange();
Chris Lattnerd3a00502009-02-24 22:27:37 +0000223
Chris Lattner160da072009-02-24 22:46:58 +0000224 return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
Chris Lattnerd3a00502009-02-24 22:27:37 +0000225 }
226
227 bool hadError = CheckInitList(InitList, DeclType);
228 Init = InitList;
229 return hadError;
230}
231
232//===----------------------------------------------------------------------===//
233// Semantic checking for initializer lists.
234//===----------------------------------------------------------------------===//
235
Douglas Gregoraaa20962009-01-29 01:05:33 +0000236/// @brief Semantic checking for initializer lists.
237///
238/// The InitListChecker class contains a set of routines that each
239/// handle the initialization of a certain kind of entity, e.g.,
240/// arrays, vectors, struct/union types, scalars, etc. The
241/// InitListChecker itself performs a recursive walk of the subobject
242/// structure of the type to be initialized, while stepping through
243/// the initializer list one element at a time. The IList and Index
244/// parameters to each of the Check* routines contain the active
245/// (syntactic) initializer list and the index into that initializer
246/// list that represents the current initializer. Each routine is
247/// responsible for moving that Index forward as it consumes elements.
248///
249/// Each Check* routine also has a StructuredList/StructuredIndex
250/// arguments, which contains the current the "structured" (semantic)
251/// initializer list and the index into that initializer list where we
252/// are copying initializers as we map them over to the semantic
253/// list. Once we have completed our recursive walk of the subobject
254/// structure, we will have constructed a full semantic initializer
255/// list.
256///
257/// C99 designators cause changes in the initializer list traversal,
258/// because they make the initialization "jump" into a specific
259/// subobject and then continue the initialization from that
260/// point. CheckDesignatedInitializer() recursively steps into the
261/// designated subobject and manages backing out the recursion to
262/// initialize the subobjects after the one designated.
Chris Lattnere76e9bf2009-02-24 22:48:58 +0000263namespace {
Douglas Gregor849afc32009-01-29 00:45:39 +0000264class InitListChecker {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000265 Sema &SemaRef;
Douglas Gregor849afc32009-01-29 00:45:39 +0000266 bool hadError;
267 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
268 InitListExpr *FullyStructuredList;
269
270 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000271 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000272 unsigned &StructuredIndex,
273 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000274 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000275 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000276 unsigned &StructuredIndex,
277 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000278 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
279 bool SubobjectIsDesignatorContext,
280 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000281 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000282 unsigned &StructuredIndex,
283 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000284 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
285 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000286 InitListExpr *StructuredList,
287 unsigned &StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000288 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor849afc32009-01-29 00:45:39 +0000289 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000290 InitListExpr *StructuredList,
291 unsigned &StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000292 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
293 unsigned &Index,
294 InitListExpr *StructuredList,
295 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000296 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000297 InitListExpr *StructuredList,
298 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000299 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
300 RecordDecl::field_iterator Field,
301 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000302 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000303 unsigned &StructuredIndex,
304 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000305 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
306 llvm::APSInt elementIndex,
307 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000308 InitListExpr *StructuredList,
309 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000310 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregoraa357272009-04-15 04:56:10 +0000311 unsigned DesigIdx,
Douglas Gregor849afc32009-01-29 00:45:39 +0000312 QualType &CurrentObjectType,
313 RecordDecl::field_iterator *NextField,
314 llvm::APSInt *NextElementIndex,
315 unsigned &Index,
316 InitListExpr *StructuredList,
317 unsigned &StructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000318 bool FinishSubobjectInit,
319 bool TopLevelObject);
Douglas Gregor849afc32009-01-29 00:45:39 +0000320 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
321 QualType CurrentObjectType,
322 InitListExpr *StructuredList,
323 unsigned StructuredIndex,
324 SourceRange InitRange);
Douglas Gregoraaa20962009-01-29 01:05:33 +0000325 void UpdateStructuredListElement(InitListExpr *StructuredList,
326 unsigned &StructuredIndex,
Douglas Gregor849afc32009-01-29 00:45:39 +0000327 Expr *expr);
328 int numArrayElements(QualType DeclType);
329 int numStructUnionElements(QualType DeclType);
Douglas Gregord45210d2009-01-30 22:09:00 +0000330
331 void FillInValueInitializations(InitListExpr *ILE);
Douglas Gregor849afc32009-01-29 00:45:39 +0000332public:
Chris Lattner2e2766a2009-02-24 22:50:46 +0000333 InitListChecker(Sema &S, InitListExpr *IL, QualType &T);
Douglas Gregor849afc32009-01-29 00:45:39 +0000334 bool HadError() { return hadError; }
335
336 // @brief Retrieves the fully-structured initializer list used for
337 // semantic analysis and code generation.
338 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
339};
Chris Lattnere76e9bf2009-02-24 22:48:58 +0000340} // end anonymous namespace
Chris Lattner1aa25a72009-01-29 05:10:57 +0000341
Douglas Gregorf603b472009-01-28 21:54:33 +0000342/// Recursively replaces NULL values within the given initializer list
343/// with expressions that perform value-initialization of the
344/// appropriate type.
Douglas Gregord45210d2009-01-30 22:09:00 +0000345void InitListChecker::FillInValueInitializations(InitListExpr *ILE) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000346 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord45210d2009-01-30 22:09:00 +0000347 "Should not have void type");
Douglas Gregor538a4c22009-02-02 17:43:21 +0000348 SourceLocation Loc = ILE->getSourceRange().getBegin();
349 if (ILE->getSyntacticForm())
350 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
351
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000352 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000353 unsigned Init = 0, NumInits = ILE->getNumInits();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000354 for (RecordDecl::field_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000355 Field = RType->getDecl()->field_begin(),
356 FieldEnd = RType->getDecl()->field_end();
Douglas Gregorf603b472009-01-28 21:54:33 +0000357 Field != FieldEnd; ++Field) {
358 if (Field->isUnnamedBitfield())
359 continue;
360
Douglas Gregor538a4c22009-02-02 17:43:21 +0000361 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000362 if (Field->getType()->isReferenceType()) {
363 // C++ [dcl.init.aggr]p9:
364 // If an incomplete or empty initializer-list leaves a
365 // member of reference type uninitialized, the program is
366 // ill-formed.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000367 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregord45210d2009-01-30 22:09:00 +0000368 << Field->getType()
369 << ILE->getSyntacticForm()->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +0000370 SemaRef.Diag(Field->getLocation(),
Douglas Gregord45210d2009-01-30 22:09:00 +0000371 diag::note_uninit_reference_member);
372 hadError = true;
Douglas Gregor538a4c22009-02-02 17:43:21 +0000373 return;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000374 } else if (SemaRef.CheckValueInitialization(Field->getType(), Loc)) {
Douglas Gregor538a4c22009-02-02 17:43:21 +0000375 hadError = true;
376 return;
Douglas Gregord45210d2009-01-30 22:09:00 +0000377 }
Douglas Gregor538a4c22009-02-02 17:43:21 +0000378
Mike Stumpe127ae32009-05-16 07:39:55 +0000379 // FIXME: If value-initialization involves calling a constructor, should
380 // we make that call explicit in the representation (even when it means
381 // extending the initializer list)?
Douglas Gregor538a4c22009-02-02 17:43:21 +0000382 if (Init < NumInits && !hadError)
383 ILE->setInit(Init,
Chris Lattner2e2766a2009-02-24 22:50:46 +0000384 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()));
Douglas Gregor538a4c22009-02-02 17:43:21 +0000385 } else if (InitListExpr *InnerILE
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000386 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregord45210d2009-01-30 22:09:00 +0000387 FillInValueInitializations(InnerILE);
Douglas Gregorf603b472009-01-28 21:54:33 +0000388 ++Init;
Douglas Gregord45210d2009-01-30 22:09:00 +0000389
390 // Only look at the first initialization of a union.
391 if (RType->getDecl()->isUnion())
392 break;
Douglas Gregorf603b472009-01-28 21:54:33 +0000393 }
394
395 return;
396 }
397
398 QualType ElementType;
399
Douglas Gregor538a4c22009-02-02 17:43:21 +0000400 unsigned NumInits = ILE->getNumInits();
401 unsigned NumElements = NumInits;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000402 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000403 ElementType = AType->getElementType();
Douglas Gregor538a4c22009-02-02 17:43:21 +0000404 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
405 NumElements = CAType->getSize().getZExtValue();
406 } else if (const VectorType *VType = ILE->getType()->getAsVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000407 ElementType = VType->getElementType();
Douglas Gregor538a4c22009-02-02 17:43:21 +0000408 NumElements = VType->getNumElements();
409 } else
Douglas Gregorf603b472009-01-28 21:54:33 +0000410 ElementType = ILE->getType();
411
Douglas Gregor538a4c22009-02-02 17:43:21 +0000412 for (unsigned Init = 0; Init != NumElements; ++Init) {
413 if (Init >= NumInits || !ILE->getInit(Init)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000414 if (SemaRef.CheckValueInitialization(ElementType, Loc)) {
Douglas Gregor538a4c22009-02-02 17:43:21 +0000415 hadError = true;
416 return;
417 }
418
Mike Stumpe127ae32009-05-16 07:39:55 +0000419 // FIXME: If value-initialization involves calling a constructor, should
420 // we make that call explicit in the representation (even when it means
421 // extending the initializer list)?
Douglas Gregor538a4c22009-02-02 17:43:21 +0000422 if (Init < NumInits && !hadError)
423 ILE->setInit(Init,
Chris Lattner2e2766a2009-02-24 22:50:46 +0000424 new (SemaRef.Context) ImplicitValueInitExpr(ElementType));
Mike Stump90fc78e2009-08-04 21:02:39 +0000425 } else if (InitListExpr *InnerILE
426 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregord45210d2009-01-30 22:09:00 +0000427 FillInValueInitializations(InnerILE);
Douglas Gregorf603b472009-01-28 21:54:33 +0000428 }
429}
430
Chris Lattner1aa25a72009-01-29 05:10:57 +0000431
Chris Lattner2e2766a2009-02-24 22:50:46 +0000432InitListChecker::InitListChecker(Sema &S, InitListExpr *IL, QualType &T)
433 : SemaRef(S) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000434 hadError = false;
Eli Friedmand8535af2008-05-19 20:00:43 +0000435
Eli Friedman683cedf2008-05-19 19:16:24 +0000436 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000437 unsigned newStructuredIndex = 0;
438 FullyStructuredList
Douglas Gregorea765e12009-03-01 17:12:46 +0000439 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregorbe69b162009-02-04 22:46:25 +0000440 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
441 /*TopLevelObject=*/true);
Eli Friedmand8535af2008-05-19 20:00:43 +0000442
Douglas Gregord45210d2009-01-30 22:09:00 +0000443 if (!hadError)
444 FillInValueInitializations(FullyStructuredList);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000445}
446
447int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman46f81662008-05-25 13:22:35 +0000448 // FIXME: use a proper constant
449 int maxElements = 0x7FFFFFFF;
Chris Lattnera1923f62008-08-04 07:31:14 +0000450 if (const ConstantArrayType *CAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000451 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000452 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
453 }
454 return maxElements;
455}
456
457int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000458 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregorf603b472009-01-28 21:54:33 +0000459 int InitializableMembers = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000460 for (RecordDecl::field_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000461 Field = structDecl->field_begin(),
462 FieldEnd = structDecl->field_end();
Douglas Gregorf603b472009-01-28 21:54:33 +0000463 Field != FieldEnd; ++Field) {
464 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
465 ++InitializableMembers;
466 }
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000467 if (structDecl->isUnion())
Eli Friedman9f5250b2008-05-25 14:03:31 +0000468 return std::min(InitializableMembers, 1);
469 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000470}
471
472void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregorf603b472009-01-28 21:54:33 +0000473 QualType T, unsigned &Index,
474 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000475 unsigned &StructuredIndex,
476 bool TopLevelObject) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000477 int maxElements = 0;
478
479 if (T->isArrayType())
480 maxElements = numArrayElements(T);
481 else if (T->isStructureType() || T->isUnionType())
482 maxElements = numStructUnionElements(T);
Eli Friedman683cedf2008-05-19 19:16:24 +0000483 else if (T->isVectorType())
484 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000485 else
486 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman683cedf2008-05-19 19:16:24 +0000487
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000488 if (maxElements == 0) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000489 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000490 diag::err_implicit_empty_initializer);
Douglas Gregorf603b472009-01-28 21:54:33 +0000491 ++Index;
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000492 hadError = true;
493 return;
494 }
495
Douglas Gregorf603b472009-01-28 21:54:33 +0000496 // Build a structured initializer list corresponding to this subobject.
497 InitListExpr *StructuredSubobjectInitList
498 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
499 StructuredIndex,
Douglas Gregorea765e12009-03-01 17:12:46 +0000500 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
501 ParentIList->getSourceRange().getEnd()));
Douglas Gregorf603b472009-01-28 21:54:33 +0000502 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman683cedf2008-05-19 19:16:24 +0000503
Douglas Gregorf603b472009-01-28 21:54:33 +0000504 // Check the element types and build the structural subobject.
Douglas Gregor538a4c22009-02-02 17:43:21 +0000505 unsigned StartIndex = Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000506 CheckListElementTypes(ParentIList, T, false, Index,
507 StructuredSubobjectInitList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000508 StructuredSubobjectInitIndex,
509 TopLevelObject);
Douglas Gregor538a4c22009-02-02 17:43:21 +0000510 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregorcd2c5272009-03-20 00:32:56 +0000511 StructuredSubobjectInitList->setType(T);
512
Douglas Gregorea765e12009-03-01 17:12:46 +0000513 // Update the structured sub-object initializer so that it's ending
Douglas Gregor538a4c22009-02-02 17:43:21 +0000514 // range corresponds with the end of the last initializer it used.
515 if (EndIndex < ParentIList->getNumInits()) {
516 SourceLocation EndLoc
517 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
518 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
519 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000520}
521
Steve Naroff56099522008-05-06 00:23:44 +0000522void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregorf603b472009-01-28 21:54:33 +0000523 unsigned &Index,
524 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000525 unsigned &StructuredIndex,
526 bool TopLevelObject) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000527 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregorf603b472009-01-28 21:54:33 +0000528 SyntacticToSemantic[IList] = StructuredList;
529 StructuredList->setSyntacticForm(IList);
530 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000531 StructuredIndex, TopLevelObject);
Steve Naroff56099522008-05-06 00:23:44 +0000532 IList->setType(T);
Douglas Gregorf603b472009-01-28 21:54:33 +0000533 StructuredList->setType(T);
Eli Friedman46f81662008-05-25 13:22:35 +0000534 if (hadError)
535 return;
Eli Friedmand8535af2008-05-19 20:00:43 +0000536
Eli Friedman46f81662008-05-25 13:22:35 +0000537 if (Index < IList->getNumInits()) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000538 // We have leftover initializers
Eli Friedman579534a2009-05-29 20:20:05 +0000539 if (StructuredIndex == 1 &&
540 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000541 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedman579534a2009-05-29 20:20:05 +0000542 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000543 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedman579534a2009-05-29 20:20:05 +0000544 hadError = true;
545 }
Eli Friedman71de9eb2008-05-19 20:12:18 +0000546 // Special-case
Chris Lattner2e2766a2009-02-24 22:50:46 +0000547 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattner9d2cf082008-11-19 05:27:50 +0000548 << IList->getInit(Index)->getSourceRange();
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000549 } else if (!T->isIncompleteType()) {
Douglas Gregor09f078c2009-01-30 22:26:29 +0000550 // Don't complain for incomplete types, since we'll get an error
551 // elsewhere
Douglas Gregorbe69b162009-02-04 22:46:25 +0000552 QualType CurrentObjectType = StructuredList->getType();
553 int initKind =
554 CurrentObjectType->isArrayType()? 0 :
555 CurrentObjectType->isVectorType()? 1 :
556 CurrentObjectType->isScalarType()? 2 :
557 CurrentObjectType->isUnionType()? 3 :
558 4;
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000559
560 unsigned DK = diag::warn_excess_initializers;
Eli Friedman579534a2009-05-29 20:20:05 +0000561 if (SemaRef.getLangOptions().CPlusPlus) {
562 DK = diag::err_excess_initializers;
563 hadError = true;
564 }
Nate Begeman48fd8c92009-07-07 21:53:06 +0000565 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
566 DK = diag::err_excess_initializers;
567 hadError = true;
568 }
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000569
Chris Lattner2e2766a2009-02-24 22:50:46 +0000570 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorbe69b162009-02-04 22:46:25 +0000571 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000572 }
573 }
Eli Friedman455f7622008-05-19 20:20:43 +0000574
Eli Friedman90bcb892009-05-16 11:45:48 +0000575 if (T->isScalarType() && !TopLevelObject)
Chris Lattner2e2766a2009-02-24 22:50:46 +0000576 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor3faaa812009-04-01 23:51:29 +0000577 << IList->getSourceRange()
578 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocStart()))
579 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocEnd()));
Steve Naroffc4d4a482008-05-01 22:18:59 +0000580}
581
Eli Friedman683cedf2008-05-19 19:16:24 +0000582void InitListChecker::CheckListElementTypes(InitListExpr *IList,
583 QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000584 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000585 unsigned &Index,
586 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000587 unsigned &StructuredIndex,
588 bool TopLevelObject) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000589 if (DeclType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000590 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000591 } else if (DeclType->isVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000592 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregore7ef5002009-01-30 17:31:00 +0000593 } else if (DeclType->isAggregateType()) {
594 if (DeclType->isRecordType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000595 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000596 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000597 SubobjectIsDesignatorContext, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000598 StructuredList, StructuredIndex,
599 TopLevelObject);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000600 } else if (DeclType->isArrayType()) {
Douglas Gregor5a203a62009-01-23 16:54:12 +0000601 llvm::APSInt Zero(
Chris Lattner2e2766a2009-02-24 22:50:46 +0000602 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor5a203a62009-01-23 16:54:12 +0000603 false);
Douglas Gregorf603b472009-01-28 21:54:33 +0000604 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
605 StructuredList, StructuredIndex);
Mike Stump90fc78e2009-08-04 21:02:39 +0000606 } else
Douglas Gregorf603b472009-01-28 21:54:33 +0000607 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffff5b3a82008-08-10 16:05:48 +0000608 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
609 // This type is invalid, issue a diagnostic.
Douglas Gregorf603b472009-01-28 21:54:33 +0000610 ++Index;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000611 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000612 << DeclType;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000613 hadError = true;
Douglas Gregord45210d2009-01-30 22:09:00 +0000614 } else if (DeclType->isRecordType()) {
615 // C++ [dcl.init]p14:
616 // [...] If the class is an aggregate (8.5.1), and the initializer
617 // is a brace-enclosed list, see 8.5.1.
618 //
619 // Note: 8.5.1 is handled below; here, we diagnose the case where
620 // we have an initializer list and a destination type that is not
621 // an aggregate.
622 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000623 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord45210d2009-01-30 22:09:00 +0000624 << DeclType << IList->getSourceRange();
625 hadError = true;
626 } else if (DeclType->isReferenceType()) {
627 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000628 } else {
629 // In C, all types are either scalars or aggregates, but
630 // additional handling is needed here for C++ (and possibly others?).
631 assert(0 && "Unsupported initializer type");
632 }
633}
634
Eli Friedman683cedf2008-05-19 19:16:24 +0000635void InitListChecker::CheckSubElementType(InitListExpr *IList,
636 QualType ElemType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000637 unsigned &Index,
638 InitListExpr *StructuredList,
639 unsigned &StructuredIndex) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000640 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000641 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
642 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000643 unsigned newStructuredIndex = 0;
644 InitListExpr *newStructuredList
645 = getStructuredSubobjectInit(IList, Index, ElemType,
646 StructuredList, StructuredIndex,
647 SubInitList->getSourceRange());
648 CheckExplicitInitList(SubInitList, ElemType, newIndex,
649 newStructuredList, newStructuredIndex);
650 ++StructuredIndex;
651 ++Index;
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000652 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
653 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattner45d6fd62009-02-24 22:41:04 +0000654 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregorf603b472009-01-28 21:54:33 +0000655 ++Index;
Eli Friedmand8535af2008-05-19 20:00:43 +0000656 } else if (ElemType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000657 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000658 } else if (ElemType->isReferenceType()) {
659 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedman683cedf2008-05-19 19:16:24 +0000660 } else {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000661 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000662 // C++ [dcl.init.aggr]p12:
663 // All implicit type conversions (clause 4) are considered when
664 // initializing the aggregate member with an ini- tializer from
665 // an initializer-list. If the initializer can initialize a
666 // member, the member is initialized. [...]
667 ImplicitConversionSequence ICS
Anders Carlsson06386552009-08-27 17:18:13 +0000668 = SemaRef.TryCopyInitialization(expr, ElemType,
669 /*SuppressUserConversions=*/false,
Anders Carlssone0f3ee62009-08-27 17:37:39 +0000670 /*ForceRValue=*/false,
671 /*InOverloadResolution=*/false);
Anders Carlsson06386552009-08-27 17:18:13 +0000672
Douglas Gregord45210d2009-01-30 22:09:00 +0000673 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000674 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregord45210d2009-01-30 22:09:00 +0000675 "initializing"))
676 hadError = true;
677 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
678 ++Index;
679 return;
680 }
681
682 // Fall through for subaggregate initialization
683 } else {
684 // C99 6.7.8p13:
685 //
686 // The initializer for a structure or union object that has
687 // automatic storage duration shall be either an initializer
688 // list as described below, or a single expression that has
689 // compatible structure or union type. In the latter case, the
690 // initial value of the object, including unnamed members, is
691 // that of the expression.
Eli Friedman2a553812009-06-13 10:38:46 +0000692 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman95acf982009-05-29 18:22:49 +0000693 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000694 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
695 ++Index;
696 return;
697 }
698
699 // Fall through for subaggregate initialization
700 }
701
702 // C++ [dcl.init.aggr]p12:
703 //
704 // [...] Otherwise, if the member is itself a non-empty
705 // subaggregate, brace elision is assumed and the initializer is
706 // considered for the initialization of the first member of
707 // the subaggregate.
708 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
709 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
710 StructuredIndex);
711 ++StructuredIndex;
712 } else {
713 // We cannot initialize this element, so let
714 // PerformCopyInitialization produce the appropriate diagnostic.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000715 SemaRef.PerformCopyInitialization(expr, ElemType, "initializing");
Douglas Gregord45210d2009-01-30 22:09:00 +0000716 hadError = true;
717 ++Index;
718 ++StructuredIndex;
719 }
720 }
Eli Friedman683cedf2008-05-19 19:16:24 +0000721}
722
Douglas Gregord45210d2009-01-30 22:09:00 +0000723void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor36859eb2009-01-29 00:39:20 +0000724 unsigned &Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000725 InitListExpr *StructuredList,
726 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000727 if (Index < IList->getNumInits()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000728 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000729 if (isa<InitListExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000730 SemaRef.Diag(IList->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000731 diag::err_many_braces_around_scalar_init)
732 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000733 hadError = true;
734 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000735 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000736 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000737 } else if (isa<DesignatedInitExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000738 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000739 diag::err_designator_for_scalar_init)
740 << DeclType << expr->getSourceRange();
741 hadError = true;
742 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000743 ++StructuredIndex;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000744 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000745 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000746
Eli Friedmand8535af2008-05-19 20:00:43 +0000747 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000748 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedman71de9eb2008-05-19 20:12:18 +0000749 hadError = true; // types weren't compatible.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000750 else if (savExpr != expr) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000751 // The type was promoted, update initializer list.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000752 IList->setInit(Index, expr);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000753 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000754 if (hadError)
755 ++StructuredIndex;
756 else
757 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000758 ++Index;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000759 } else {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000760 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattner9d2cf082008-11-19 05:27:50 +0000761 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000762 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000763 ++Index;
764 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000765 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000766 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000767}
768
Douglas Gregord45210d2009-01-30 22:09:00 +0000769void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
770 unsigned &Index,
771 InitListExpr *StructuredList,
772 unsigned &StructuredIndex) {
773 if (Index < IList->getNumInits()) {
774 Expr *expr = IList->getInit(Index);
775 if (isa<InitListExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000776 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord45210d2009-01-30 22:09:00 +0000777 << DeclType << IList->getSourceRange();
778 hadError = true;
779 ++Index;
780 ++StructuredIndex;
781 return;
782 }
783
784 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Anders Carlsson8f809f92009-08-27 17:30:43 +0000785 if (SemaRef.CheckReferenceInit(expr, DeclType,
786 /*SuppressUserConversions=*/false,
787 /*AllowExplicit=*/false,
788 /*ForceRValue=*/false))
Douglas Gregord45210d2009-01-30 22:09:00 +0000789 hadError = true;
790 else if (savExpr != expr) {
791 // The type was promoted, update initializer list.
792 IList->setInit(Index, expr);
793 }
794 if (hadError)
795 ++StructuredIndex;
796 else
797 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
798 ++Index;
799 } else {
Mike Stumpe127ae32009-05-16 07:39:55 +0000800 // FIXME: It would be wonderful if we could point at the actual member. In
801 // general, it would be useful to pass location information down the stack,
802 // so that we know the location (or decl) of the "current object" being
803 // initialized.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000804 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord45210d2009-01-30 22:09:00 +0000805 diag::err_init_reference_member_uninitialized)
806 << DeclType
807 << IList->getSourceRange();
808 hadError = true;
809 ++Index;
810 ++StructuredIndex;
811 return;
812 }
813}
814
Steve Naroffc4d4a482008-05-01 22:18:59 +0000815void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000816 unsigned &Index,
817 InitListExpr *StructuredList,
818 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000819 if (Index < IList->getNumInits()) {
820 const VectorType *VT = DeclType->getAsVectorType();
Nate Begemane85f43d2009-08-10 23:49:36 +0000821 unsigned maxElements = VT->getNumElements();
822 unsigned numEltsInit = 0;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000823 QualType elementType = VT->getElementType();
824
Nate Begemane85f43d2009-08-10 23:49:36 +0000825 if (!SemaRef.getLangOptions().OpenCL) {
826 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
827 // Don't attempt to go past the end of the init list
828 if (Index >= IList->getNumInits())
829 break;
830 CheckSubElementType(IList, elementType, Index,
831 StructuredList, StructuredIndex);
832 }
833 } else {
834 // OpenCL initializers allows vectors to be constructed from vectors.
835 for (unsigned i = 0; i < maxElements; ++i) {
836 // Don't attempt to go past the end of the init list
837 if (Index >= IList->getNumInits())
838 break;
839 QualType IType = IList->getInit(Index)->getType();
840 if (!IType->isVectorType()) {
841 CheckSubElementType(IList, elementType, Index,
842 StructuredList, StructuredIndex);
843 ++numEltsInit;
844 } else {
845 const VectorType *IVT = IType->getAsVectorType();
846 unsigned numIElts = IVT->getNumElements();
847 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
848 numIElts);
849 CheckSubElementType(IList, VecType, Index,
850 StructuredList, StructuredIndex);
851 numEltsInit += numIElts;
852 }
853 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000854 }
Nate Begemane85f43d2009-08-10 23:49:36 +0000855
856 // OpenCL & AltiVec require all elements to be initialized.
857 if (numEltsInit != maxElements)
858 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
859 SemaRef.Diag(IList->getSourceRange().getBegin(),
860 diag::err_vector_incorrect_num_initializers)
861 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000862 }
863}
864
865void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000866 llvm::APSInt elementIndex,
867 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000868 unsigned &Index,
869 InitListExpr *StructuredList,
870 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000871 // Check for the special-case of initializing an array with a string.
872 if (Index < IList->getNumInits()) {
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000873 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
874 SemaRef.Context)) {
875 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregorf603b472009-01-28 21:54:33 +0000876 // We place the string literal directly into the resulting
877 // initializer list. This is the only place where the structure
878 // of the structured initializer list doesn't match exactly,
879 // because doing so would involve allocating one character
880 // constant for each string.
Chris Lattner45d6fd62009-02-24 22:41:04 +0000881 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner2e2766a2009-02-24 22:50:46 +0000882 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000883 ++Index;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000884 return;
885 }
886 }
Chris Lattnera1923f62008-08-04 07:31:14 +0000887 if (const VariableArrayType *VAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000888 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman46f81662008-05-25 13:22:35 +0000889 // Check for VLAs; in standard C it would be possible to check this
890 // earlier, but I don't know where clang accepts VLAs (gcc accepts
891 // them in all sorts of strange places).
Chris Lattner2e2766a2009-02-24 22:50:46 +0000892 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000893 diag::err_variable_object_no_init)
894 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman46f81662008-05-25 13:22:35 +0000895 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000896 ++Index;
897 ++StructuredIndex;
Eli Friedman46f81662008-05-25 13:22:35 +0000898 return;
899 }
900
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000901 // We might know the maximum number of elements in advance.
Douglas Gregorf603b472009-01-28 21:54:33 +0000902 llvm::APSInt maxElements(elementIndex.getBitWidth(),
903 elementIndex.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000904 bool maxElementsKnown = false;
905 if (const ConstantArrayType *CAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000906 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000907 maxElements = CAT->getSize();
Douglas Gregor5a203a62009-01-23 16:54:12 +0000908 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000909 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000910 maxElementsKnown = true;
911 }
912
Chris Lattner2e2766a2009-02-24 22:50:46 +0000913 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnera1923f62008-08-04 07:31:14 +0000914 ->getElementType();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000915 while (Index < IList->getNumInits()) {
916 Expr *Init = IList->getInit(Index);
917 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000918 // If we're not the subobject that matches up with the '{' for
919 // the designator, we shouldn't be handling the
920 // designator. Return immediately.
921 if (!SubobjectIsDesignatorContext)
922 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000923
Douglas Gregor710f6d42009-01-22 23:26:18 +0000924 // Handle this designated initializer. elementIndex will be
925 // updated to be the next array element we'll initialize.
Douglas Gregoraa357272009-04-15 04:56:10 +0000926 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregorf603b472009-01-28 21:54:33 +0000927 DeclType, 0, &elementIndex, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000928 StructuredList, StructuredIndex, true,
929 false)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000930 hadError = true;
931 continue;
932 }
933
Douglas Gregor5a203a62009-01-23 16:54:12 +0000934 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
935 maxElements.extend(elementIndex.getBitWidth());
936 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
937 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000938 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor5a203a62009-01-23 16:54:12 +0000939
Douglas Gregor710f6d42009-01-22 23:26:18 +0000940 // If the array is of incomplete type, keep track of the number of
941 // elements in the initializer.
942 if (!maxElementsKnown && elementIndex > maxElements)
943 maxElements = elementIndex;
944
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000945 continue;
946 }
947
948 // If we know the maximum number of elements, and we've already
949 // hit it, stop consuming elements in the initializer list.
950 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000951 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000952
953 // Check this element.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000954 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000955 StructuredList, StructuredIndex);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000956 ++elementIndex;
957
958 // If the array is of incomplete type, keep track of the number of
959 // elements in the initializer.
960 if (!maxElementsKnown && elementIndex > maxElements)
961 maxElements = elementIndex;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000962 }
Eli Friedmanb4c71b32009-05-29 20:17:55 +0000963 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000964 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000965 // be calculated here.
Douglas Gregor69722702009-01-23 18:58:42 +0000966 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000967 if (maxElements == Zero) {
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000968 // Sizing an array implicitly to zero is not allowed by ISO C,
969 // but is supported by GNU.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000970 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000971 diag::ext_typecheck_zero_array_size);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000972 }
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000973
Chris Lattner2e2766a2009-02-24 22:50:46 +0000974 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000975 ArrayType::Normal, 0);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000976 }
977}
978
979void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
980 QualType DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000981 RecordDecl::field_iterator Field,
982 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000983 unsigned &Index,
984 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000985 unsigned &StructuredIndex,
986 bool TopLevelObject) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000987 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000988
Eli Friedman683cedf2008-05-19 19:16:24 +0000989 // If the record is invalid, some of it's members are invalid. To avoid
990 // confusion, we forgo checking the intializer for the entire record.
991 if (structDecl->isInvalidDecl()) {
992 hadError = true;
993 return;
994 }
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000995
996 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
997 // Value-initialize the first named member of the union.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000998 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000999 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregorc9e012a2009-01-29 17:44:32 +00001000 Field != FieldEnd; ++Field) {
1001 if (Field->getDeclName()) {
1002 StructuredList->setInitializedFieldInUnion(*Field);
1003 break;
1004 }
1005 }
1006 return;
1007 }
1008
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001009 // If structDecl is a forward declaration, this loop won't do
1010 // anything except look at designated initializers; That's okay,
1011 // because an error should get printed out elsewhere. It might be
1012 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001013 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001014 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001015 bool InitializedSomething = false;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001016 while (Index < IList->getNumInits()) {
1017 Expr *Init = IList->getInit(Index);
1018
1019 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001020 // If we're not the subobject that matches up with the '{' for
1021 // the designator, we shouldn't be handling the
1022 // designator. Return immediately.
1023 if (!SubobjectIsDesignatorContext)
1024 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001025
Douglas Gregor710f6d42009-01-22 23:26:18 +00001026 // Handle this designated initializer. Field will be updated to
1027 // the next field that we'll be initializing.
Douglas Gregoraa357272009-04-15 04:56:10 +00001028 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregorf603b472009-01-28 21:54:33 +00001029 DeclType, &Field, 0, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001030 StructuredList, StructuredIndex,
1031 true, TopLevelObject))
Douglas Gregor710f6d42009-01-22 23:26:18 +00001032 hadError = true;
1033
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001034 InitializedSomething = true;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001035 continue;
1036 }
1037
1038 if (Field == FieldEnd) {
1039 // We've run out of fields. We're done.
1040 break;
1041 }
1042
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001043 // We've already initialized a member of a union. We're done.
1044 if (InitializedSomething && DeclType->isUnionType())
1045 break;
1046
Douglas Gregor8acb7272008-12-11 16:49:14 +00001047 // If we've hit the flexible array member at the end, we're done.
1048 if (Field->getType()->isIncompleteArrayType())
1049 break;
1050
Douglas Gregor82462762009-01-29 16:53:55 +00001051 if (Field->isUnnamedBitfield()) {
Douglas Gregorf603b472009-01-28 21:54:33 +00001052 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001053 ++Field;
Eli Friedman683cedf2008-05-19 19:16:24 +00001054 continue;
Steve Naroffc4d4a482008-05-01 22:18:59 +00001055 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001056
Douglas Gregor36859eb2009-01-29 00:39:20 +00001057 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001058 StructuredList, StructuredIndex);
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001059 InitializedSomething = true;
Douglas Gregor82462762009-01-29 16:53:55 +00001060
1061 if (DeclType->isUnionType()) {
1062 // Initialize the first field within the union.
1063 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor82462762009-01-29 16:53:55 +00001064 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001065
1066 ++Field;
Steve Naroffc4d4a482008-05-01 22:18:59 +00001067 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001068
Douglas Gregorbe69b162009-02-04 22:46:25 +00001069 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001070 Index >= IList->getNumInits())
Douglas Gregorbe69b162009-02-04 22:46:25 +00001071 return;
1072
1073 // Handle GNU flexible array initializers.
1074 if (!TopLevelObject &&
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001075 (!isa<InitListExpr>(IList->getInit(Index)) ||
1076 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001077 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001078 diag::err_flexible_array_init_nonempty)
1079 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001080 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001081 << *Field;
1082 hadError = true;
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001083 ++Index;
1084 return;
1085 } else {
1086 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
1087 diag::ext_flexible_array_init)
1088 << IList->getInit(Index)->getSourceRange().getBegin();
1089 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1090 << *Field;
Douglas Gregorbe69b162009-02-04 22:46:25 +00001091 }
1092
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001093 if (isa<InitListExpr>(IList->getInit(Index)))
1094 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1095 StructuredIndex);
1096 else
1097 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1098 StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +00001099}
Steve Naroffc4d4a482008-05-01 22:18:59 +00001100
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001101/// \brief Expand a field designator that refers to a member of an
1102/// anonymous struct or union into a series of field designators that
1103/// refers to the field within the appropriate subobject.
1104///
1105/// Field/FieldIndex will be updated to point to the (new)
1106/// currently-designated field.
1107static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1108 DesignatedInitExpr *DIE,
1109 unsigned DesigIdx,
1110 FieldDecl *Field,
1111 RecordDecl::field_iterator &FieldIter,
1112 unsigned &FieldIndex) {
1113 typedef DesignatedInitExpr::Designator Designator;
1114
1115 // Build the path from the current object to the member of the
1116 // anonymous struct/union (backwards).
1117 llvm::SmallVector<FieldDecl *, 4> Path;
1118 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
1119
1120 // Build the replacement designators.
1121 llvm::SmallVector<Designator, 4> Replacements;
1122 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1123 FI = Path.rbegin(), FIEnd = Path.rend();
1124 FI != FIEnd; ++FI) {
1125 if (FI + 1 == FIEnd)
1126 Replacements.push_back(Designator((IdentifierInfo *)0,
1127 DIE->getDesignator(DesigIdx)->getDotLoc(),
1128 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1129 else
1130 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1131 SourceLocation()));
1132 Replacements.back().setField(*FI);
1133 }
1134
1135 // Expand the current designator into the set of replacement
1136 // designators, so we have a full subobject path down to where the
1137 // member of the anonymous struct/union is actually stored.
1138 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
1139 &Replacements[0] + Replacements.size());
1140
1141 // Update FieldIter/FieldIndex;
1142 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001143 FieldIter = Record->field_begin();
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001144 FieldIndex = 0;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001145 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001146 FieldIter != FEnd; ++FieldIter) {
1147 if (FieldIter->isUnnamedBitfield())
1148 continue;
1149
1150 if (*FieldIter == Path.back())
1151 return;
1152
1153 ++FieldIndex;
1154 }
1155
1156 assert(false && "Unable to find anonymous struct/union field");
1157}
1158
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001159/// @brief Check the well-formedness of a C99 designated initializer.
1160///
1161/// Determines whether the designated initializer @p DIE, which
1162/// resides at the given @p Index within the initializer list @p
1163/// IList, is well-formed for a current object of type @p DeclType
1164/// (C99 6.7.8). The actual subobject that this designator refers to
1165/// within the current subobject is returned in either
Douglas Gregorf603b472009-01-28 21:54:33 +00001166/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001167///
1168/// @param IList The initializer list in which this designated
1169/// initializer occurs.
1170///
Douglas Gregoraa357272009-04-15 04:56:10 +00001171/// @param DIE The designated initializer expression.
1172///
1173/// @param DesigIdx The index of the current designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001174///
1175/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1176/// into which the designation in @p DIE should refer.
1177///
Douglas Gregor710f6d42009-01-22 23:26:18 +00001178/// @param NextField If non-NULL and the first designator in @p DIE is
1179/// a field, this will be set to the field declaration corresponding
1180/// to the field named by the designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001181///
Douglas Gregor710f6d42009-01-22 23:26:18 +00001182/// @param NextElementIndex If non-NULL and the first designator in @p
1183/// DIE is an array designator or GNU array-range designator, this
1184/// will be set to the last index initialized by this designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001185///
1186/// @param Index Index into @p IList where the designated initializer
1187/// @p DIE occurs.
1188///
Douglas Gregorf603b472009-01-28 21:54:33 +00001189/// @param StructuredList The initializer list expression that
1190/// describes all of the subobject initializers in the order they'll
1191/// actually be initialized.
1192///
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001193/// @returns true if there was an error, false otherwise.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001194bool
1195InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
1196 DesignatedInitExpr *DIE,
Douglas Gregoraa357272009-04-15 04:56:10 +00001197 unsigned DesigIdx,
Douglas Gregor710f6d42009-01-22 23:26:18 +00001198 QualType &CurrentObjectType,
1199 RecordDecl::field_iterator *NextField,
1200 llvm::APSInt *NextElementIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +00001201 unsigned &Index,
1202 InitListExpr *StructuredList,
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001203 unsigned &StructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001204 bool FinishSubobjectInit,
1205 bool TopLevelObject) {
Douglas Gregoraa357272009-04-15 04:56:10 +00001206 if (DesigIdx == DIE->size()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001207 // Check the actual initialization for the designated object type.
1208 bool prevHadError = hadError;
Douglas Gregor36859eb2009-01-29 00:39:20 +00001209
1210 // Temporarily remove the designator expression from the
1211 // initializer list that the child calls see, so that we don't try
1212 // to re-process the designator.
1213 unsigned OldIndex = Index;
1214 IList->setInit(OldIndex, DIE->getInit());
1215
1216 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001217 StructuredList, StructuredIndex);
Douglas Gregor36859eb2009-01-29 00:39:20 +00001218
1219 // Restore the designated initializer expression in the syntactic
1220 // form of the initializer list.
1221 if (IList->getInit(OldIndex) != DIE->getInit())
1222 DIE->setInit(IList->getInit(OldIndex));
1223 IList->setInit(OldIndex, DIE);
1224
Douglas Gregor710f6d42009-01-22 23:26:18 +00001225 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001226 }
1227
Douglas Gregoraa357272009-04-15 04:56:10 +00001228 bool IsFirstDesignator = (DesigIdx == 0);
Douglas Gregorf603b472009-01-28 21:54:33 +00001229 assert((IsFirstDesignator || StructuredList) &&
1230 "Need a non-designated initializer list to start from");
1231
Douglas Gregoraa357272009-04-15 04:56:10 +00001232 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregorf603b472009-01-28 21:54:33 +00001233 // Determine the structural initializer list that corresponds to the
1234 // current subobject.
1235 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Douglas Gregorea765e12009-03-01 17:12:46 +00001236 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1237 StructuredList, StructuredIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +00001238 SourceRange(D->getStartLocation(),
1239 DIE->getSourceRange().getEnd()));
1240 assert(StructuredList && "Expected a structured initializer list");
1241
Douglas Gregor710f6d42009-01-22 23:26:18 +00001242 if (D->isFieldDesignator()) {
1243 // C99 6.7.8p7:
1244 //
1245 // If a designator has the form
1246 //
1247 // . identifier
1248 //
1249 // then the current object (defined below) shall have
1250 // structure or union type and the identifier shall be the
1251 // name of a member of that type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001252 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001253 if (!RT) {
1254 SourceLocation Loc = D->getDotLoc();
1255 if (Loc.isInvalid())
1256 Loc = D->getFieldLoc();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001257 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1258 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001259 ++Index;
1260 return true;
1261 }
1262
Douglas Gregorf603b472009-01-28 21:54:33 +00001263 // Note: we perform a linear search of the fields here, despite
1264 // the fact that we have a faster lookup method, because we always
1265 // need to compute the field's index.
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001266 FieldDecl *KnownField = D->getField();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001267 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregorf603b472009-01-28 21:54:33 +00001268 unsigned FieldIndex = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001269 RecordDecl::field_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001270 Field = RT->getDecl()->field_begin(),
1271 FieldEnd = RT->getDecl()->field_end();
Douglas Gregorf603b472009-01-28 21:54:33 +00001272 for (; Field != FieldEnd; ++Field) {
1273 if (Field->isUnnamedBitfield())
1274 continue;
1275
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001276 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregorf603b472009-01-28 21:54:33 +00001277 break;
1278
1279 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001280 }
1281
Douglas Gregorf603b472009-01-28 21:54:33 +00001282 if (Field == FieldEnd) {
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001283 // There was no normal field in the struct with the designated
1284 // name. Perform another lookup for this name, which may find
1285 // something that we can't designate (e.g., a member function),
1286 // may find nothing, or may find a member of an anonymous
1287 // struct/union.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001288 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorf603b472009-01-28 21:54:33 +00001289 if (Lookup.first == Lookup.second) {
1290 // Name lookup didn't find anything.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001291 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregorf603b472009-01-28 21:54:33 +00001292 << FieldName << CurrentObjectType;
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001293 ++Index;
1294 return true;
1295 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1296 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1297 ->isAnonymousStructOrUnion()) {
1298 // Handle an field designator that refers to a member of an
1299 // anonymous struct or union.
1300 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1301 cast<FieldDecl>(*Lookup.first),
1302 Field, FieldIndex);
Eli Friedmanbd45b552009-04-16 17:49:48 +00001303 D = DIE->getDesignator(DesigIdx);
Douglas Gregorf603b472009-01-28 21:54:33 +00001304 } else {
1305 // Name lookup found something, but it wasn't a field.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001306 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregorf603b472009-01-28 21:54:33 +00001307 << FieldName;
Chris Lattner2e2766a2009-02-24 22:50:46 +00001308 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001309 diag::note_field_designator_found);
Eli Friedmanbd45b552009-04-16 17:49:48 +00001310 ++Index;
1311 return true;
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001312 }
1313 } else if (!KnownField &&
1314 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregorf603b472009-01-28 21:54:33 +00001315 ->isAnonymousStructOrUnion()) {
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001316 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1317 Field, FieldIndex);
1318 D = DIE->getDesignator(DesigIdx);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001319 }
Douglas Gregorf603b472009-01-28 21:54:33 +00001320
1321 // All of the fields of a union are located at the same place in
1322 // the initializer list.
Douglas Gregor82462762009-01-29 16:53:55 +00001323 if (RT->getDecl()->isUnion()) {
Douglas Gregorf603b472009-01-28 21:54:33 +00001324 FieldIndex = 0;
Douglas Gregor82462762009-01-29 16:53:55 +00001325 StructuredList->setInitializedFieldInUnion(*Field);
1326 }
Douglas Gregorf603b472009-01-28 21:54:33 +00001327
Douglas Gregor710f6d42009-01-22 23:26:18 +00001328 // Update the designator with the field declaration.
Douglas Gregorf603b472009-01-28 21:54:33 +00001329 D->setField(*Field);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001330
Douglas Gregorf603b472009-01-28 21:54:33 +00001331 // Make sure that our non-designated initializer list has space
1332 // for a subobject corresponding to this field.
1333 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner2e2766a2009-02-24 22:50:46 +00001334 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +00001335
Douglas Gregorbe69b162009-02-04 22:46:25 +00001336 // This designator names a flexible array member.
1337 if (Field->getType()->isIncompleteArrayType()) {
1338 bool Invalid = false;
Douglas Gregoraa357272009-04-15 04:56:10 +00001339 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorbe69b162009-02-04 22:46:25 +00001340 // We can't designate an object within the flexible array
1341 // member (because GCC doesn't allow it).
Douglas Gregoraa357272009-04-15 04:56:10 +00001342 DesignatedInitExpr::Designator *NextD
1343 = DIE->getDesignator(DesigIdx + 1);
Chris Lattner2e2766a2009-02-24 22:50:46 +00001344 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001345 diag::err_designator_into_flexible_array_member)
1346 << SourceRange(NextD->getStartLocation(),
1347 DIE->getSourceRange().getEnd());
Chris Lattner2e2766a2009-02-24 22:50:46 +00001348 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001349 << *Field;
1350 Invalid = true;
1351 }
1352
1353 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1354 // The initializer is not an initializer list.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001355 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001356 diag::err_flexible_array_init_needs_braces)
1357 << DIE->getInit()->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001358 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001359 << *Field;
1360 Invalid = true;
1361 }
1362
1363 // Handle GNU flexible array initializers.
1364 if (!Invalid && !TopLevelObject &&
1365 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001366 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001367 diag::err_flexible_array_init_nonempty)
1368 << DIE->getSourceRange().getBegin();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001369 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001370 << *Field;
1371 Invalid = true;
1372 }
1373
1374 if (Invalid) {
1375 ++Index;
1376 return true;
1377 }
1378
1379 // Initialize the array.
1380 bool prevHadError = hadError;
1381 unsigned newStructuredIndex = FieldIndex;
1382 unsigned OldIndex = Index;
1383 IList->setInit(Index, DIE->getInit());
1384 CheckSubElementType(IList, Field->getType(), Index,
1385 StructuredList, newStructuredIndex);
1386 IList->setInit(OldIndex, DIE);
1387 if (hadError && !prevHadError) {
1388 ++Field;
1389 ++FieldIndex;
1390 if (NextField)
1391 *NextField = Field;
1392 StructuredIndex = FieldIndex;
1393 return true;
1394 }
1395 } else {
1396 // Recurse to check later designated subobjects.
1397 QualType FieldType = (*Field)->getType();
1398 unsigned newStructuredIndex = FieldIndex;
Douglas Gregoraa357272009-04-15 04:56:10 +00001399 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1400 Index, StructuredList, newStructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001401 true, false))
1402 return true;
1403 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001404
1405 // Find the position of the next field to be initialized in this
1406 // subobject.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001407 ++Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001408 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001409
1410 // If this the first designator, our caller will continue checking
1411 // the rest of this struct/class/union subobject.
1412 if (IsFirstDesignator) {
1413 if (NextField)
1414 *NextField = Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001415 StructuredIndex = FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001416 return false;
1417 }
1418
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001419 if (!FinishSubobjectInit)
1420 return false;
1421
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001422 // We've already initialized something in the union; we're done.
1423 if (RT->getDecl()->isUnion())
1424 return hadError;
1425
Douglas Gregor710f6d42009-01-22 23:26:18 +00001426 // Check the remaining fields within this class/struct/union subobject.
1427 bool prevHadError = hadError;
Douglas Gregorf603b472009-01-28 21:54:33 +00001428 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1429 StructuredList, FieldIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001430 return hadError && !prevHadError;
1431 }
1432
1433 // C99 6.7.8p6:
1434 //
1435 // If a designator has the form
1436 //
1437 // [ constant-expression ]
1438 //
1439 // then the current object (defined below) shall have array
1440 // type and the expression shall be an integer constant
1441 // expression. If the array is of unknown size, any
1442 // nonnegative value is valid.
1443 //
1444 // Additionally, cope with the GNU extension that permits
1445 // designators of the form
1446 //
1447 // [ constant-expression ... constant-expression ]
Chris Lattner2e2766a2009-02-24 22:50:46 +00001448 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001449 if (!AT) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001450 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor710f6d42009-01-22 23:26:18 +00001451 << CurrentObjectType;
1452 ++Index;
1453 return true;
1454 }
1455
1456 Expr *IndexExpr = 0;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001457 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1458 if (D->isArrayDesignator()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001459 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnereec8ae22009-04-25 21:59:05 +00001460 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001461 DesignatedEndIndex = DesignatedStartIndex;
1462 } else {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001463 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001464
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001465
Chris Lattnereec8ae22009-04-25 21:59:05 +00001466 DesignatedStartIndex =
1467 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
1468 DesignatedEndIndex =
1469 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001470 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001471
Chris Lattnereec8ae22009-04-25 21:59:05 +00001472 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregor9fddded2009-01-29 19:42:23 +00001473 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001474 }
1475
Douglas Gregor710f6d42009-01-22 23:26:18 +00001476 if (isa<ConstantArrayType>(AT)) {
1477 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001478 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1479 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1480 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1481 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1482 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001483 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor710f6d42009-01-22 23:26:18 +00001484 diag::err_array_designator_too_large)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001485 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor710f6d42009-01-22 23:26:18 +00001486 << IndexExpr->getSourceRange();
1487 ++Index;
1488 return true;
1489 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001490 } else {
1491 // Make sure the bit-widths and signedness match.
1492 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1493 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnereec8ae22009-04-25 21:59:05 +00001494 else if (DesignatedStartIndex.getBitWidth() <
1495 DesignatedEndIndex.getBitWidth())
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001496 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1497 DesignatedStartIndex.setIsUnsigned(true);
1498 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001499 }
1500
Douglas Gregorf603b472009-01-28 21:54:33 +00001501 // Make sure that our non-designated initializer list has space
1502 // for a subobject corresponding to this array element.
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001503 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Chris Lattner2e2766a2009-02-24 22:50:46 +00001504 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001505 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +00001506
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001507 // Repeatedly perform subobject initializations in the range
1508 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor710f6d42009-01-22 23:26:18 +00001509
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001510 // Move to the next designator
1511 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1512 unsigned OldIndex = Index;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001513 while (DesignatedStartIndex <= DesignatedEndIndex) {
1514 // Recurse to check later designated subobjects.
1515 QualType ElementType = AT->getElementType();
1516 Index = OldIndex;
Douglas Gregoraa357272009-04-15 04:56:10 +00001517 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1518 Index, StructuredList, ElementIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001519 (DesignatedStartIndex == DesignatedEndIndex),
1520 false))
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001521 return true;
1522
1523 // Move to the next index in the array that we'll be initializing.
1524 ++DesignatedStartIndex;
1525 ElementIndex = DesignatedStartIndex.getZExtValue();
1526 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001527
1528 // If this the first designator, our caller will continue checking
1529 // the rest of this array subobject.
1530 if (IsFirstDesignator) {
1531 if (NextElementIndex)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001532 *NextElementIndex = DesignatedStartIndex;
Douglas Gregorf603b472009-01-28 21:54:33 +00001533 StructuredIndex = ElementIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001534 return false;
1535 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001536
1537 if (!FinishSubobjectInit)
1538 return false;
1539
Douglas Gregor710f6d42009-01-22 23:26:18 +00001540 // Check the remaining elements within this array subobject.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001541 bool prevHadError = hadError;
Douglas Gregord7e76c52009-02-09 19:45:19 +00001542 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001543 StructuredList, ElementIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001544 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001545}
1546
Douglas Gregorf603b472009-01-28 21:54:33 +00001547// Get the structured initializer list for a subobject of type
1548// @p CurrentObjectType.
1549InitListExpr *
1550InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1551 QualType CurrentObjectType,
1552 InitListExpr *StructuredList,
1553 unsigned StructuredIndex,
1554 SourceRange InitRange) {
1555 Expr *ExistingInit = 0;
1556 if (!StructuredList)
1557 ExistingInit = SyntacticToSemantic[IList];
1558 else if (StructuredIndex < StructuredList->getNumInits())
1559 ExistingInit = StructuredList->getInit(StructuredIndex);
1560
1561 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1562 return Result;
1563
1564 if (ExistingInit) {
1565 // We are creating an initializer list that initializes the
1566 // subobjects of the current object, but there was already an
1567 // initialization that completely initialized the current
1568 // subobject, e.g., by a compound literal:
1569 //
1570 // struct X { int a, b; };
1571 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1572 //
1573 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1574 // designated initializer re-initializes the whole
1575 // subobject [0], overwriting previous initializers.
Douglas Gregorea765e12009-03-01 17:12:46 +00001576 SemaRef.Diag(InitRange.getBegin(),
1577 diag::warn_subobject_initializer_overrides)
Douglas Gregorf603b472009-01-28 21:54:33 +00001578 << InitRange;
Chris Lattner2e2766a2009-02-24 22:50:46 +00001579 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001580 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001581 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001582 << ExistingInit->getSourceRange();
1583 }
1584
1585 InitListExpr *Result
Douglas Gregorea765e12009-03-01 17:12:46 +00001586 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
1587 InitRange.getEnd());
1588
Douglas Gregorf603b472009-01-28 21:54:33 +00001589 Result->setType(CurrentObjectType);
1590
Douglas Gregoree0792c2009-03-20 23:58:33 +00001591 // Pre-allocate storage for the structured initializer list.
1592 unsigned NumElements = 0;
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001593 unsigned NumInits = 0;
1594 if (!StructuredList)
1595 NumInits = IList->getNumInits();
1596 else if (Index < IList->getNumInits()) {
1597 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1598 NumInits = SubList->getNumInits();
1599 }
1600
Douglas Gregoree0792c2009-03-20 23:58:33 +00001601 if (const ArrayType *AType
1602 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1603 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1604 NumElements = CAType->getSize().getZExtValue();
1605 // Simple heuristic so that we don't allocate a very large
1606 // initializer with many empty entries at the end.
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001607 if (NumInits && NumElements > NumInits)
Douglas Gregoree0792c2009-03-20 23:58:33 +00001608 NumElements = 0;
1609 }
1610 } else if (const VectorType *VType = CurrentObjectType->getAsVectorType())
1611 NumElements = VType->getNumElements();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001612 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregoree0792c2009-03-20 23:58:33 +00001613 RecordDecl *RDecl = RType->getDecl();
1614 if (RDecl->isUnion())
1615 NumElements = 1;
1616 else
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001617 NumElements = std::distance(RDecl->field_begin(),
1618 RDecl->field_end());
Douglas Gregoree0792c2009-03-20 23:58:33 +00001619 }
1620
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001621 if (NumElements < NumInits)
Douglas Gregoree0792c2009-03-20 23:58:33 +00001622 NumElements = IList->getNumInits();
1623
1624 Result->reserveInits(NumElements);
1625
Douglas Gregorf603b472009-01-28 21:54:33 +00001626 // Link this new initializer list into the structured initializer
1627 // lists.
1628 if (StructuredList)
1629 StructuredList->updateInit(StructuredIndex, Result);
1630 else {
1631 Result->setSyntacticForm(IList);
1632 SyntacticToSemantic[IList] = Result;
1633 }
1634
1635 return Result;
1636}
1637
1638/// Update the initializer at index @p StructuredIndex within the
1639/// structured initializer list to the value @p expr.
1640void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1641 unsigned &StructuredIndex,
1642 Expr *expr) {
1643 // No structured initializer list to update
1644 if (!StructuredList)
1645 return;
1646
1647 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1648 // This initializer overwrites a previous initializer. Warn.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001649 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001650 diag::warn_initializer_overrides)
1651 << expr->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001652 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001653 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001654 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001655 << PrevInit->getSourceRange();
1656 }
1657
1658 ++StructuredIndex;
1659}
1660
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001661/// Check that the given Index expression is a valid array designator
1662/// value. This is essentailly just a wrapper around
Chris Lattnereec8ae22009-04-25 21:59:05 +00001663/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001664/// and produces a reasonable diagnostic if there is a
1665/// failure. Returns true if there was an error, false otherwise. If
1666/// everything went okay, Value will receive the value of the constant
1667/// expression.
1668static bool
Chris Lattnereec8ae22009-04-25 21:59:05 +00001669CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001670 SourceLocation Loc = Index->getSourceRange().getBegin();
1671
1672 // Make sure this is an integer constant expression.
Chris Lattnereec8ae22009-04-25 21:59:05 +00001673 if (S.VerifyIntegerConstantExpression(Index, &Value))
1674 return true;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001675
Chris Lattnereec8ae22009-04-25 21:59:05 +00001676 if (Value.isSigned() && Value.isNegative())
1677 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001678 << Value.toString(10) << Index->getSourceRange();
1679
Douglas Gregore498e372009-01-23 21:04:18 +00001680 Value.setIsUnsigned(true);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001681 return false;
1682}
1683
1684Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1685 SourceLocation Loc,
Douglas Gregor5f34f0e2009-03-28 00:41:23 +00001686 bool GNUSyntax,
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001687 OwningExprResult Init) {
1688 typedef DesignatedInitExpr::Designator ASTDesignator;
1689
1690 bool Invalid = false;
1691 llvm::SmallVector<ASTDesignator, 32> Designators;
1692 llvm::SmallVector<Expr *, 32> InitExpressions;
1693
1694 // Build designators and check array designator expressions.
1695 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1696 const Designator &D = Desig.getDesignator(Idx);
1697 switch (D.getKind()) {
1698 case Designator::FieldDesignator:
1699 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1700 D.getFieldLoc()));
1701 break;
1702
1703 case Designator::ArrayDesignator: {
1704 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1705 llvm::APSInt IndexValue;
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001706 if (!Index->isTypeDependent() &&
1707 !Index->isValueDependent() &&
1708 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001709 Invalid = true;
1710 else {
1711 Designators.push_back(ASTDesignator(InitExpressions.size(),
1712 D.getLBracketLoc(),
1713 D.getRBracketLoc()));
1714 InitExpressions.push_back(Index);
1715 }
1716 break;
1717 }
1718
1719 case Designator::ArrayRangeDesignator: {
1720 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1721 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1722 llvm::APSInt StartValue;
1723 llvm::APSInt EndValue;
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001724 bool StartDependent = StartIndex->isTypeDependent() ||
1725 StartIndex->isValueDependent();
1726 bool EndDependent = EndIndex->isTypeDependent() ||
1727 EndIndex->isValueDependent();
1728 if ((!StartDependent &&
1729 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1730 (!EndDependent &&
1731 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001732 Invalid = true;
Douglas Gregorea0528d2009-01-23 22:22:29 +00001733 else {
1734 // Make sure we're comparing values with the same bit width.
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001735 if (StartDependent || EndDependent) {
1736 // Nothing to compute.
1737 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregorea0528d2009-01-23 22:22:29 +00001738 EndValue.extend(StartValue.getBitWidth());
1739 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1740 StartValue.extend(EndValue.getBitWidth());
1741
Douglas Gregor1401c062009-05-21 23:30:39 +00001742 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregorea0528d2009-01-23 22:22:29 +00001743 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1744 << StartValue.toString(10) << EndValue.toString(10)
1745 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1746 Invalid = true;
1747 } else {
1748 Designators.push_back(ASTDesignator(InitExpressions.size(),
1749 D.getLBracketLoc(),
1750 D.getEllipsisLoc(),
1751 D.getRBracketLoc()));
1752 InitExpressions.push_back(StartIndex);
1753 InitExpressions.push_back(EndIndex);
1754 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001755 }
1756 break;
1757 }
1758 }
1759 }
1760
1761 if (Invalid || Init.isInvalid())
1762 return ExprError();
1763
1764 // Clear out the expressions within the designation.
1765 Desig.ClearExprs(*this);
1766
1767 DesignatedInitExpr *DIE
Jay Foad9e6bef42009-05-21 09:52:38 +00001768 = DesignatedInitExpr::Create(Context,
1769 Designators.data(), Designators.size(),
1770 InitExpressions.data(), InitExpressions.size(),
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001771 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001772 return Owned(DIE);
1773}
Douglas Gregor849afc32009-01-29 00:45:39 +00001774
1775bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001776 InitListChecker CheckInitList(*this, InitList, DeclType);
Douglas Gregor849afc32009-01-29 00:45:39 +00001777 if (!CheckInitList.HadError())
1778 InitList = CheckInitList.getFullyStructuredList();
1779
1780 return CheckInitList.HadError();
1781}
Douglas Gregor538a4c22009-02-02 17:43:21 +00001782
1783/// \brief Diagnose any semantic errors with value-initialization of
1784/// the given type.
1785///
1786/// Value-initialization effectively zero-initializes any types
1787/// without user-declared constructors, and calls the default
1788/// constructor for a for any type that has a user-declared
1789/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1790/// a type with a user-declared constructor does not have an
1791/// accessible, non-deleted default constructor. In C, everything can
1792/// be value-initialized, which corresponds to C's notion of
1793/// initializing objects with static storage duration when no
1794/// initializer is provided for that object.
1795///
1796/// \returns true if there was an error, false otherwise.
1797bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1798 // C++ [dcl.init]p5:
1799 //
1800 // To value-initialize an object of type T means:
1801
1802 // -- if T is an array type, then each element is value-initialized;
1803 if (const ArrayType *AT = Context.getAsArrayType(Type))
1804 return CheckValueInitialization(AT->getElementType(), Loc);
1805
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001806 if (const RecordType *RT = Type->getAs<RecordType>()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001807 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Douglas Gregor538a4c22009-02-02 17:43:21 +00001808 // -- if T is a class type (clause 9) with a user-declared
1809 // constructor (12.1), then the default constructor for T is
1810 // called (and the initialization is ill-formed if T has no
1811 // accessible default constructor);
Douglas Gregor2e047592009-02-28 01:32:25 +00001812 if (ClassDecl->hasUserDeclaredConstructor())
Mike Stumpe127ae32009-05-16 07:39:55 +00001813 // FIXME: Eventually, we'll need to put the constructor decl into the
1814 // AST.
Douglas Gregor538a4c22009-02-02 17:43:21 +00001815 return PerformInitializationByConstructor(Type, 0, 0, Loc,
1816 SourceRange(Loc),
1817 DeclarationName(),
1818 IK_Direct);
1819 }
1820 }
1821
1822 if (Type->isReferenceType()) {
1823 // C++ [dcl.init]p5:
1824 // [...] A program that calls for default-initialization or
1825 // value-initialization of an entity of reference type is
1826 // ill-formed. [...]
Mike Stumpe127ae32009-05-16 07:39:55 +00001827 // FIXME: Once we have code that goes through this path, add an actual
1828 // diagnostic :)
Douglas Gregor538a4c22009-02-02 17:43:21 +00001829 }
1830
1831 return false;
1832}