blob: 405dd8489e26c8c6e463300c1d5ca005c4505d87 [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())
135 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
136
137 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
138 // of unknown size ("[]") or an object type that is not a variable array type.
139 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
140 return Diag(InitLoc, diag::err_variable_object_no_init)
141 << VAT->getSizeExpr()->getSourceRange();
142
143 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
144 if (!InitList) {
145 // FIXME: Handle wide strings
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000146 if (Expr *Str = IsStringInit(Init, DeclType, Context)) {
147 CheckStringInit(Str, DeclType, *this);
Chris Lattnerd20fac42009-02-24 23:01:39 +0000148 return false;
149 }
Chris Lattnerd3a00502009-02-24 22:27:37 +0000150
151 // C++ [dcl.init]p14:
152 // -- If the destination type is a (possibly cv-qualified) class
153 // type:
154 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
155 QualType DeclTypeC = Context.getCanonicalType(DeclType);
156 QualType InitTypeC = Context.getCanonicalType(Init->getType());
157
158 // -- If the initialization is direct-initialization, or if it is
159 // copy-initialization where the cv-unqualified version of the
160 // source type is the same class as, or a derived class of, the
161 // class of the destination, constructors are considered.
162 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
163 IsDerivedFrom(InitTypeC, DeclTypeC)) {
Anders Carlsson5868dfc2009-05-27 16:38:58 +0000164 const CXXRecordDecl *RD =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000165 cast<CXXRecordDecl>(DeclType->getAs<RecordType>()->getDecl());
Anders Carlsson5868dfc2009-05-27 16:38:58 +0000166
167 // No need to make a CXXConstructExpr if both the ctor and dtor are
168 // trivial.
169 if (RD->hasTrivialConstructor() && RD->hasTrivialDestructor())
170 return false;
171
Chris Lattnerd3a00502009-02-24 22:27:37 +0000172 CXXConstructorDecl *Constructor
173 = PerformInitializationByConstructor(DeclType, &Init, 1,
174 InitLoc, Init->getSourceRange(),
175 InitEntity,
176 DirectInit? IK_Direct : IK_Copy);
Anders Carlsson73bb5e62009-05-27 16:10:08 +0000177 if (!Constructor)
178 return true;
Anders Carlsson665e4692009-08-25 05:12:04 +0000179
180 OwningExprResult InitResult =
181 BuildCXXConstructExpr(DeclType, Constructor, &Init, 1);
182 if (InitResult.isInvalid())
183 return true;
184
185 Init = InitResult.takeAs<Expr>();
Anders Carlsson73bb5e62009-05-27 16:10:08 +0000186 return false;
Chris Lattnerd3a00502009-02-24 22:27:37 +0000187 }
188
189 // -- Otherwise (i.e., for the remaining copy-initialization
190 // cases), user-defined conversion sequences that can
191 // convert from the source type to the destination type or
192 // (when a conversion function is used) to a derived class
193 // thereof are enumerated as described in 13.3.1.4, and the
194 // best one is chosen through overload resolution
195 // (13.3). If the conversion cannot be done or is
196 // ambiguous, the initialization is ill-formed. The
197 // function selected is called with the initializer
198 // expression as its argument; if the function is a
199 // constructor, the call initializes a temporary of the
200 // destination type.
Mike Stumpe127ae32009-05-16 07:39:55 +0000201 // FIXME: We're pretending to do copy elision here; return to this when we
202 // have ASTs for such things.
Chris Lattnerd3a00502009-02-24 22:27:37 +0000203 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
204 return false;
205
206 if (InitEntity)
207 return Diag(InitLoc, diag::err_cannot_initialize_decl)
Chris Lattner6434a1b2009-06-26 04:45:06 +0000208 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
209 << Init->getType() << Init->getSourceRange();
210 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
Chris Lattnerd3a00502009-02-24 22:27:37 +0000211 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
212 << Init->getType() << Init->getSourceRange();
213 }
214
215 // C99 6.7.8p16.
216 if (DeclType->isArrayType())
217 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
Chris Lattner6434a1b2009-06-26 04:45:06 +0000218 << Init->getSourceRange();
Chris Lattnerd3a00502009-02-24 22:27:37 +0000219
Chris Lattner160da072009-02-24 22:46:58 +0000220 return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
Chris Lattnerd3a00502009-02-24 22:27:37 +0000221 }
222
223 bool hadError = CheckInitList(InitList, DeclType);
224 Init = InitList;
225 return hadError;
226}
227
228//===----------------------------------------------------------------------===//
229// Semantic checking for initializer lists.
230//===----------------------------------------------------------------------===//
231
Douglas Gregoraaa20962009-01-29 01:05:33 +0000232/// @brief Semantic checking for initializer lists.
233///
234/// The InitListChecker class contains a set of routines that each
235/// handle the initialization of a certain kind of entity, e.g.,
236/// arrays, vectors, struct/union types, scalars, etc. The
237/// InitListChecker itself performs a recursive walk of the subobject
238/// structure of the type to be initialized, while stepping through
239/// the initializer list one element at a time. The IList and Index
240/// parameters to each of the Check* routines contain the active
241/// (syntactic) initializer list and the index into that initializer
242/// list that represents the current initializer. Each routine is
243/// responsible for moving that Index forward as it consumes elements.
244///
245/// Each Check* routine also has a StructuredList/StructuredIndex
246/// arguments, which contains the current the "structured" (semantic)
247/// initializer list and the index into that initializer list where we
248/// are copying initializers as we map them over to the semantic
249/// list. Once we have completed our recursive walk of the subobject
250/// structure, we will have constructed a full semantic initializer
251/// list.
252///
253/// C99 designators cause changes in the initializer list traversal,
254/// because they make the initialization "jump" into a specific
255/// subobject and then continue the initialization from that
256/// point. CheckDesignatedInitializer() recursively steps into the
257/// designated subobject and manages backing out the recursion to
258/// initialize the subobjects after the one designated.
Chris Lattnere76e9bf2009-02-24 22:48:58 +0000259namespace {
Douglas Gregor849afc32009-01-29 00:45:39 +0000260class InitListChecker {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000261 Sema &SemaRef;
Douglas Gregor849afc32009-01-29 00:45:39 +0000262 bool hadError;
263 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
264 InitListExpr *FullyStructuredList;
265
266 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000267 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000268 unsigned &StructuredIndex,
269 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000270 void CheckExplicitInitList(InitListExpr *IList, 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 CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
275 bool SubobjectIsDesignatorContext,
276 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000277 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000278 unsigned &StructuredIndex,
279 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000280 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
281 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000282 InitListExpr *StructuredList,
283 unsigned &StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000284 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor849afc32009-01-29 00:45:39 +0000285 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000286 InitListExpr *StructuredList,
287 unsigned &StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000288 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
289 unsigned &Index,
290 InitListExpr *StructuredList,
291 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000292 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000293 InitListExpr *StructuredList,
294 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000295 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
296 RecordDecl::field_iterator Field,
297 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000298 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000299 unsigned &StructuredIndex,
300 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000301 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
302 llvm::APSInt elementIndex,
303 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000304 InitListExpr *StructuredList,
305 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000306 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregoraa357272009-04-15 04:56:10 +0000307 unsigned DesigIdx,
Douglas Gregor849afc32009-01-29 00:45:39 +0000308 QualType &CurrentObjectType,
309 RecordDecl::field_iterator *NextField,
310 llvm::APSInt *NextElementIndex,
311 unsigned &Index,
312 InitListExpr *StructuredList,
313 unsigned &StructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000314 bool FinishSubobjectInit,
315 bool TopLevelObject);
Douglas Gregor849afc32009-01-29 00:45:39 +0000316 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
317 QualType CurrentObjectType,
318 InitListExpr *StructuredList,
319 unsigned StructuredIndex,
320 SourceRange InitRange);
Douglas Gregoraaa20962009-01-29 01:05:33 +0000321 void UpdateStructuredListElement(InitListExpr *StructuredList,
322 unsigned &StructuredIndex,
Douglas Gregor849afc32009-01-29 00:45:39 +0000323 Expr *expr);
324 int numArrayElements(QualType DeclType);
325 int numStructUnionElements(QualType DeclType);
Douglas Gregord45210d2009-01-30 22:09:00 +0000326
327 void FillInValueInitializations(InitListExpr *ILE);
Douglas Gregor849afc32009-01-29 00:45:39 +0000328public:
Chris Lattner2e2766a2009-02-24 22:50:46 +0000329 InitListChecker(Sema &S, InitListExpr *IL, QualType &T);
Douglas Gregor849afc32009-01-29 00:45:39 +0000330 bool HadError() { return hadError; }
331
332 // @brief Retrieves the fully-structured initializer list used for
333 // semantic analysis and code generation.
334 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
335};
Chris Lattnere76e9bf2009-02-24 22:48:58 +0000336} // end anonymous namespace
Chris Lattner1aa25a72009-01-29 05:10:57 +0000337
Douglas Gregorf603b472009-01-28 21:54:33 +0000338/// Recursively replaces NULL values within the given initializer list
339/// with expressions that perform value-initialization of the
340/// appropriate type.
Douglas Gregord45210d2009-01-30 22:09:00 +0000341void InitListChecker::FillInValueInitializations(InitListExpr *ILE) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000342 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord45210d2009-01-30 22:09:00 +0000343 "Should not have void type");
Douglas Gregor538a4c22009-02-02 17:43:21 +0000344 SourceLocation Loc = ILE->getSourceRange().getBegin();
345 if (ILE->getSyntacticForm())
346 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
347
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000348 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000349 unsigned Init = 0, NumInits = ILE->getNumInits();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000350 for (RecordDecl::field_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000351 Field = RType->getDecl()->field_begin(),
352 FieldEnd = RType->getDecl()->field_end();
Douglas Gregorf603b472009-01-28 21:54:33 +0000353 Field != FieldEnd; ++Field) {
354 if (Field->isUnnamedBitfield())
355 continue;
356
Douglas Gregor538a4c22009-02-02 17:43:21 +0000357 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000358 if (Field->getType()->isReferenceType()) {
359 // C++ [dcl.init.aggr]p9:
360 // If an incomplete or empty initializer-list leaves a
361 // member of reference type uninitialized, the program is
362 // ill-formed.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000363 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregord45210d2009-01-30 22:09:00 +0000364 << Field->getType()
365 << ILE->getSyntacticForm()->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +0000366 SemaRef.Diag(Field->getLocation(),
Douglas Gregord45210d2009-01-30 22:09:00 +0000367 diag::note_uninit_reference_member);
368 hadError = true;
Douglas Gregor538a4c22009-02-02 17:43:21 +0000369 return;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000370 } else if (SemaRef.CheckValueInitialization(Field->getType(), Loc)) {
Douglas Gregor538a4c22009-02-02 17:43:21 +0000371 hadError = true;
372 return;
Douglas Gregord45210d2009-01-30 22:09:00 +0000373 }
Douglas Gregor538a4c22009-02-02 17:43:21 +0000374
Mike Stumpe127ae32009-05-16 07:39:55 +0000375 // FIXME: If value-initialization involves calling a constructor, should
376 // we make that call explicit in the representation (even when it means
377 // extending the initializer list)?
Douglas Gregor538a4c22009-02-02 17:43:21 +0000378 if (Init < NumInits && !hadError)
379 ILE->setInit(Init,
Chris Lattner2e2766a2009-02-24 22:50:46 +0000380 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()));
Douglas Gregor538a4c22009-02-02 17:43:21 +0000381 } else if (InitListExpr *InnerILE
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000382 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregord45210d2009-01-30 22:09:00 +0000383 FillInValueInitializations(InnerILE);
Douglas Gregorf603b472009-01-28 21:54:33 +0000384 ++Init;
Douglas Gregord45210d2009-01-30 22:09:00 +0000385
386 // Only look at the first initialization of a union.
387 if (RType->getDecl()->isUnion())
388 break;
Douglas Gregorf603b472009-01-28 21:54:33 +0000389 }
390
391 return;
392 }
393
394 QualType ElementType;
395
Douglas Gregor538a4c22009-02-02 17:43:21 +0000396 unsigned NumInits = ILE->getNumInits();
397 unsigned NumElements = NumInits;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000398 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000399 ElementType = AType->getElementType();
Douglas Gregor538a4c22009-02-02 17:43:21 +0000400 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
401 NumElements = CAType->getSize().getZExtValue();
402 } else if (const VectorType *VType = ILE->getType()->getAsVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000403 ElementType = VType->getElementType();
Douglas Gregor538a4c22009-02-02 17:43:21 +0000404 NumElements = VType->getNumElements();
405 } else
Douglas Gregorf603b472009-01-28 21:54:33 +0000406 ElementType = ILE->getType();
407
Douglas Gregor538a4c22009-02-02 17:43:21 +0000408 for (unsigned Init = 0; Init != NumElements; ++Init) {
409 if (Init >= NumInits || !ILE->getInit(Init)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000410 if (SemaRef.CheckValueInitialization(ElementType, Loc)) {
Douglas Gregor538a4c22009-02-02 17:43:21 +0000411 hadError = true;
412 return;
413 }
414
Mike Stumpe127ae32009-05-16 07:39:55 +0000415 // FIXME: If value-initialization involves calling a constructor, should
416 // we make that call explicit in the representation (even when it means
417 // extending the initializer list)?
Douglas Gregor538a4c22009-02-02 17:43:21 +0000418 if (Init < NumInits && !hadError)
419 ILE->setInit(Init,
Chris Lattner2e2766a2009-02-24 22:50:46 +0000420 new (SemaRef.Context) ImplicitValueInitExpr(ElementType));
Mike Stump90fc78e2009-08-04 21:02:39 +0000421 } else if (InitListExpr *InnerILE
422 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregord45210d2009-01-30 22:09:00 +0000423 FillInValueInitializations(InnerILE);
Douglas Gregorf603b472009-01-28 21:54:33 +0000424 }
425}
426
Chris Lattner1aa25a72009-01-29 05:10:57 +0000427
Chris Lattner2e2766a2009-02-24 22:50:46 +0000428InitListChecker::InitListChecker(Sema &S, InitListExpr *IL, QualType &T)
429 : SemaRef(S) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000430 hadError = false;
Eli Friedmand8535af2008-05-19 20:00:43 +0000431
Eli Friedman683cedf2008-05-19 19:16:24 +0000432 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000433 unsigned newStructuredIndex = 0;
434 FullyStructuredList
Douglas Gregorea765e12009-03-01 17:12:46 +0000435 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregorbe69b162009-02-04 22:46:25 +0000436 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
437 /*TopLevelObject=*/true);
Eli Friedmand8535af2008-05-19 20:00:43 +0000438
Douglas Gregord45210d2009-01-30 22:09:00 +0000439 if (!hadError)
440 FillInValueInitializations(FullyStructuredList);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000441}
442
443int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman46f81662008-05-25 13:22:35 +0000444 // FIXME: use a proper constant
445 int maxElements = 0x7FFFFFFF;
Chris Lattnera1923f62008-08-04 07:31:14 +0000446 if (const ConstantArrayType *CAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000447 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000448 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
449 }
450 return maxElements;
451}
452
453int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000454 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregorf603b472009-01-28 21:54:33 +0000455 int InitializableMembers = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000456 for (RecordDecl::field_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000457 Field = structDecl->field_begin(),
458 FieldEnd = structDecl->field_end();
Douglas Gregorf603b472009-01-28 21:54:33 +0000459 Field != FieldEnd; ++Field) {
460 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
461 ++InitializableMembers;
462 }
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000463 if (structDecl->isUnion())
Eli Friedman9f5250b2008-05-25 14:03:31 +0000464 return std::min(InitializableMembers, 1);
465 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000466}
467
468void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregorf603b472009-01-28 21:54:33 +0000469 QualType T, unsigned &Index,
470 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000471 unsigned &StructuredIndex,
472 bool TopLevelObject) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000473 int maxElements = 0;
474
475 if (T->isArrayType())
476 maxElements = numArrayElements(T);
477 else if (T->isStructureType() || T->isUnionType())
478 maxElements = numStructUnionElements(T);
Eli Friedman683cedf2008-05-19 19:16:24 +0000479 else if (T->isVectorType())
480 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000481 else
482 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman683cedf2008-05-19 19:16:24 +0000483
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000484 if (maxElements == 0) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000485 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000486 diag::err_implicit_empty_initializer);
Douglas Gregorf603b472009-01-28 21:54:33 +0000487 ++Index;
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000488 hadError = true;
489 return;
490 }
491
Douglas Gregorf603b472009-01-28 21:54:33 +0000492 // Build a structured initializer list corresponding to this subobject.
493 InitListExpr *StructuredSubobjectInitList
494 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
495 StructuredIndex,
Douglas Gregorea765e12009-03-01 17:12:46 +0000496 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
497 ParentIList->getSourceRange().getEnd()));
Douglas Gregorf603b472009-01-28 21:54:33 +0000498 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman683cedf2008-05-19 19:16:24 +0000499
Douglas Gregorf603b472009-01-28 21:54:33 +0000500 // Check the element types and build the structural subobject.
Douglas Gregor538a4c22009-02-02 17:43:21 +0000501 unsigned StartIndex = Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000502 CheckListElementTypes(ParentIList, T, false, Index,
503 StructuredSubobjectInitList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000504 StructuredSubobjectInitIndex,
505 TopLevelObject);
Douglas Gregor538a4c22009-02-02 17:43:21 +0000506 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregorcd2c5272009-03-20 00:32:56 +0000507 StructuredSubobjectInitList->setType(T);
508
Douglas Gregorea765e12009-03-01 17:12:46 +0000509 // Update the structured sub-object initializer so that it's ending
Douglas Gregor538a4c22009-02-02 17:43:21 +0000510 // range corresponds with the end of the last initializer it used.
511 if (EndIndex < ParentIList->getNumInits()) {
512 SourceLocation EndLoc
513 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
514 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
515 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000516}
517
Steve Naroff56099522008-05-06 00:23:44 +0000518void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregorf603b472009-01-28 21:54:33 +0000519 unsigned &Index,
520 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000521 unsigned &StructuredIndex,
522 bool TopLevelObject) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000523 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregorf603b472009-01-28 21:54:33 +0000524 SyntacticToSemantic[IList] = StructuredList;
525 StructuredList->setSyntacticForm(IList);
526 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000527 StructuredIndex, TopLevelObject);
Steve Naroff56099522008-05-06 00:23:44 +0000528 IList->setType(T);
Douglas Gregorf603b472009-01-28 21:54:33 +0000529 StructuredList->setType(T);
Eli Friedman46f81662008-05-25 13:22:35 +0000530 if (hadError)
531 return;
Eli Friedmand8535af2008-05-19 20:00:43 +0000532
Eli Friedman46f81662008-05-25 13:22:35 +0000533 if (Index < IList->getNumInits()) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000534 // We have leftover initializers
Eli Friedman579534a2009-05-29 20:20:05 +0000535 if (StructuredIndex == 1 &&
536 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000537 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedman579534a2009-05-29 20:20:05 +0000538 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000539 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedman579534a2009-05-29 20:20:05 +0000540 hadError = true;
541 }
Eli Friedman71de9eb2008-05-19 20:12:18 +0000542 // Special-case
Chris Lattner2e2766a2009-02-24 22:50:46 +0000543 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattner9d2cf082008-11-19 05:27:50 +0000544 << IList->getInit(Index)->getSourceRange();
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000545 } else if (!T->isIncompleteType()) {
Douglas Gregor09f078c2009-01-30 22:26:29 +0000546 // Don't complain for incomplete types, since we'll get an error
547 // elsewhere
Douglas Gregorbe69b162009-02-04 22:46:25 +0000548 QualType CurrentObjectType = StructuredList->getType();
549 int initKind =
550 CurrentObjectType->isArrayType()? 0 :
551 CurrentObjectType->isVectorType()? 1 :
552 CurrentObjectType->isScalarType()? 2 :
553 CurrentObjectType->isUnionType()? 3 :
554 4;
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000555
556 unsigned DK = diag::warn_excess_initializers;
Eli Friedman579534a2009-05-29 20:20:05 +0000557 if (SemaRef.getLangOptions().CPlusPlus) {
558 DK = diag::err_excess_initializers;
559 hadError = true;
560 }
Nate Begeman48fd8c92009-07-07 21:53:06 +0000561 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
562 DK = diag::err_excess_initializers;
563 hadError = true;
564 }
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000565
Chris Lattner2e2766a2009-02-24 22:50:46 +0000566 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorbe69b162009-02-04 22:46:25 +0000567 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000568 }
569 }
Eli Friedman455f7622008-05-19 20:20:43 +0000570
Eli Friedman90bcb892009-05-16 11:45:48 +0000571 if (T->isScalarType() && !TopLevelObject)
Chris Lattner2e2766a2009-02-24 22:50:46 +0000572 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor3faaa812009-04-01 23:51:29 +0000573 << IList->getSourceRange()
574 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocStart()))
575 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocEnd()));
Steve Naroffc4d4a482008-05-01 22:18:59 +0000576}
577
Eli Friedman683cedf2008-05-19 19:16:24 +0000578void InitListChecker::CheckListElementTypes(InitListExpr *IList,
579 QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000580 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000581 unsigned &Index,
582 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000583 unsigned &StructuredIndex,
584 bool TopLevelObject) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000585 if (DeclType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000586 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000587 } else if (DeclType->isVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000588 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregore7ef5002009-01-30 17:31:00 +0000589 } else if (DeclType->isAggregateType()) {
590 if (DeclType->isRecordType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000591 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000592 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000593 SubobjectIsDesignatorContext, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000594 StructuredList, StructuredIndex,
595 TopLevelObject);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000596 } else if (DeclType->isArrayType()) {
Douglas Gregor5a203a62009-01-23 16:54:12 +0000597 llvm::APSInt Zero(
Chris Lattner2e2766a2009-02-24 22:50:46 +0000598 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor5a203a62009-01-23 16:54:12 +0000599 false);
Douglas Gregorf603b472009-01-28 21:54:33 +0000600 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
601 StructuredList, StructuredIndex);
Mike Stump90fc78e2009-08-04 21:02:39 +0000602 } else
Douglas Gregorf603b472009-01-28 21:54:33 +0000603 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffff5b3a82008-08-10 16:05:48 +0000604 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
605 // This type is invalid, issue a diagnostic.
Douglas Gregorf603b472009-01-28 21:54:33 +0000606 ++Index;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000607 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000608 << DeclType;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000609 hadError = true;
Douglas Gregord45210d2009-01-30 22:09:00 +0000610 } else if (DeclType->isRecordType()) {
611 // C++ [dcl.init]p14:
612 // [...] If the class is an aggregate (8.5.1), and the initializer
613 // is a brace-enclosed list, see 8.5.1.
614 //
615 // Note: 8.5.1 is handled below; here, we diagnose the case where
616 // we have an initializer list and a destination type that is not
617 // an aggregate.
618 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000619 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord45210d2009-01-30 22:09:00 +0000620 << DeclType << IList->getSourceRange();
621 hadError = true;
622 } else if (DeclType->isReferenceType()) {
623 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000624 } else {
625 // In C, all types are either scalars or aggregates, but
626 // additional handling is needed here for C++ (and possibly others?).
627 assert(0 && "Unsupported initializer type");
628 }
629}
630
Eli Friedman683cedf2008-05-19 19:16:24 +0000631void InitListChecker::CheckSubElementType(InitListExpr *IList,
632 QualType ElemType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000633 unsigned &Index,
634 InitListExpr *StructuredList,
635 unsigned &StructuredIndex) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000636 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000637 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
638 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000639 unsigned newStructuredIndex = 0;
640 InitListExpr *newStructuredList
641 = getStructuredSubobjectInit(IList, Index, ElemType,
642 StructuredList, StructuredIndex,
643 SubInitList->getSourceRange());
644 CheckExplicitInitList(SubInitList, ElemType, newIndex,
645 newStructuredList, newStructuredIndex);
646 ++StructuredIndex;
647 ++Index;
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000648 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
649 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattner45d6fd62009-02-24 22:41:04 +0000650 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregorf603b472009-01-28 21:54:33 +0000651 ++Index;
Eli Friedmand8535af2008-05-19 20:00:43 +0000652 } else if (ElemType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000653 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000654 } else if (ElemType->isReferenceType()) {
655 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedman683cedf2008-05-19 19:16:24 +0000656 } else {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000657 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000658 // C++ [dcl.init.aggr]p12:
659 // All implicit type conversions (clause 4) are considered when
660 // initializing the aggregate member with an ini- tializer from
661 // an initializer-list. If the initializer can initialize a
662 // member, the member is initialized. [...]
663 ImplicitConversionSequence ICS
Chris Lattner2e2766a2009-02-24 22:50:46 +0000664 = SemaRef.TryCopyInitialization(expr, ElemType);
Douglas Gregord45210d2009-01-30 22:09:00 +0000665 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000666 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregord45210d2009-01-30 22:09:00 +0000667 "initializing"))
668 hadError = true;
669 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
670 ++Index;
671 return;
672 }
673
674 // Fall through for subaggregate initialization
675 } else {
676 // C99 6.7.8p13:
677 //
678 // The initializer for a structure or union object that has
679 // automatic storage duration shall be either an initializer
680 // list as described below, or a single expression that has
681 // compatible structure or union type. In the latter case, the
682 // initial value of the object, including unnamed members, is
683 // that of the expression.
Eli Friedman2a553812009-06-13 10:38:46 +0000684 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman95acf982009-05-29 18:22:49 +0000685 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000686 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
687 ++Index;
688 return;
689 }
690
691 // Fall through for subaggregate initialization
692 }
693
694 // C++ [dcl.init.aggr]p12:
695 //
696 // [...] Otherwise, if the member is itself a non-empty
697 // subaggregate, brace elision is assumed and the initializer is
698 // considered for the initialization of the first member of
699 // the subaggregate.
700 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
701 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
702 StructuredIndex);
703 ++StructuredIndex;
704 } else {
705 // We cannot initialize this element, so let
706 // PerformCopyInitialization produce the appropriate diagnostic.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000707 SemaRef.PerformCopyInitialization(expr, ElemType, "initializing");
Douglas Gregord45210d2009-01-30 22:09:00 +0000708 hadError = true;
709 ++Index;
710 ++StructuredIndex;
711 }
712 }
Eli Friedman683cedf2008-05-19 19:16:24 +0000713}
714
Douglas Gregord45210d2009-01-30 22:09:00 +0000715void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor36859eb2009-01-29 00:39:20 +0000716 unsigned &Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000717 InitListExpr *StructuredList,
718 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000719 if (Index < IList->getNumInits()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000720 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000721 if (isa<InitListExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000722 SemaRef.Diag(IList->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000723 diag::err_many_braces_around_scalar_init)
724 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000725 hadError = true;
726 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000727 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000728 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000729 } else if (isa<DesignatedInitExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000730 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000731 diag::err_designator_for_scalar_init)
732 << DeclType << expr->getSourceRange();
733 hadError = true;
734 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000735 ++StructuredIndex;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000736 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000737 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000738
Eli Friedmand8535af2008-05-19 20:00:43 +0000739 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000740 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedman71de9eb2008-05-19 20:12:18 +0000741 hadError = true; // types weren't compatible.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000742 else if (savExpr != expr) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000743 // The type was promoted, update initializer list.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000744 IList->setInit(Index, expr);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000745 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000746 if (hadError)
747 ++StructuredIndex;
748 else
749 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000750 ++Index;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000751 } else {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000752 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattner9d2cf082008-11-19 05:27:50 +0000753 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000754 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000755 ++Index;
756 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000757 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000758 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000759}
760
Douglas Gregord45210d2009-01-30 22:09:00 +0000761void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
762 unsigned &Index,
763 InitListExpr *StructuredList,
764 unsigned &StructuredIndex) {
765 if (Index < IList->getNumInits()) {
766 Expr *expr = IList->getInit(Index);
767 if (isa<InitListExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000768 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord45210d2009-01-30 22:09:00 +0000769 << DeclType << IList->getSourceRange();
770 hadError = true;
771 ++Index;
772 ++StructuredIndex;
773 return;
774 }
775
776 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000777 if (SemaRef.CheckReferenceInit(expr, DeclType))
Douglas Gregord45210d2009-01-30 22:09:00 +0000778 hadError = true;
779 else if (savExpr != expr) {
780 // The type was promoted, update initializer list.
781 IList->setInit(Index, expr);
782 }
783 if (hadError)
784 ++StructuredIndex;
785 else
786 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
787 ++Index;
788 } else {
Mike Stumpe127ae32009-05-16 07:39:55 +0000789 // FIXME: It would be wonderful if we could point at the actual member. In
790 // general, it would be useful to pass location information down the stack,
791 // so that we know the location (or decl) of the "current object" being
792 // initialized.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000793 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord45210d2009-01-30 22:09:00 +0000794 diag::err_init_reference_member_uninitialized)
795 << DeclType
796 << IList->getSourceRange();
797 hadError = true;
798 ++Index;
799 ++StructuredIndex;
800 return;
801 }
802}
803
Steve Naroffc4d4a482008-05-01 22:18:59 +0000804void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000805 unsigned &Index,
806 InitListExpr *StructuredList,
807 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000808 if (Index < IList->getNumInits()) {
809 const VectorType *VT = DeclType->getAsVectorType();
Nate Begemane85f43d2009-08-10 23:49:36 +0000810 unsigned maxElements = VT->getNumElements();
811 unsigned numEltsInit = 0;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000812 QualType elementType = VT->getElementType();
813
Nate Begemane85f43d2009-08-10 23:49:36 +0000814 if (!SemaRef.getLangOptions().OpenCL) {
815 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
816 // Don't attempt to go past the end of the init list
817 if (Index >= IList->getNumInits())
818 break;
819 CheckSubElementType(IList, elementType, Index,
820 StructuredList, StructuredIndex);
821 }
822 } else {
823 // OpenCL initializers allows vectors to be constructed from vectors.
824 for (unsigned i = 0; i < maxElements; ++i) {
825 // Don't attempt to go past the end of the init list
826 if (Index >= IList->getNumInits())
827 break;
828 QualType IType = IList->getInit(Index)->getType();
829 if (!IType->isVectorType()) {
830 CheckSubElementType(IList, elementType, Index,
831 StructuredList, StructuredIndex);
832 ++numEltsInit;
833 } else {
834 const VectorType *IVT = IType->getAsVectorType();
835 unsigned numIElts = IVT->getNumElements();
836 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
837 numIElts);
838 CheckSubElementType(IList, VecType, Index,
839 StructuredList, StructuredIndex);
840 numEltsInit += numIElts;
841 }
842 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000843 }
Nate Begemane85f43d2009-08-10 23:49:36 +0000844
845 // OpenCL & AltiVec require all elements to be initialized.
846 if (numEltsInit != maxElements)
847 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
848 SemaRef.Diag(IList->getSourceRange().getBegin(),
849 diag::err_vector_incorrect_num_initializers)
850 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000851 }
852}
853
854void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000855 llvm::APSInt elementIndex,
856 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000857 unsigned &Index,
858 InitListExpr *StructuredList,
859 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000860 // Check for the special-case of initializing an array with a string.
861 if (Index < IList->getNumInits()) {
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000862 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
863 SemaRef.Context)) {
864 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregorf603b472009-01-28 21:54:33 +0000865 // We place the string literal directly into the resulting
866 // initializer list. This is the only place where the structure
867 // of the structured initializer list doesn't match exactly,
868 // because doing so would involve allocating one character
869 // constant for each string.
Chris Lattner45d6fd62009-02-24 22:41:04 +0000870 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner2e2766a2009-02-24 22:50:46 +0000871 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000872 ++Index;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000873 return;
874 }
875 }
Chris Lattnera1923f62008-08-04 07:31:14 +0000876 if (const VariableArrayType *VAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000877 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman46f81662008-05-25 13:22:35 +0000878 // Check for VLAs; in standard C it would be possible to check this
879 // earlier, but I don't know where clang accepts VLAs (gcc accepts
880 // them in all sorts of strange places).
Chris Lattner2e2766a2009-02-24 22:50:46 +0000881 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000882 diag::err_variable_object_no_init)
883 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman46f81662008-05-25 13:22:35 +0000884 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000885 ++Index;
886 ++StructuredIndex;
Eli Friedman46f81662008-05-25 13:22:35 +0000887 return;
888 }
889
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000890 // We might know the maximum number of elements in advance.
Douglas Gregorf603b472009-01-28 21:54:33 +0000891 llvm::APSInt maxElements(elementIndex.getBitWidth(),
892 elementIndex.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000893 bool maxElementsKnown = false;
894 if (const ConstantArrayType *CAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000895 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000896 maxElements = CAT->getSize();
Douglas Gregor5a203a62009-01-23 16:54:12 +0000897 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000898 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000899 maxElementsKnown = true;
900 }
901
Chris Lattner2e2766a2009-02-24 22:50:46 +0000902 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnera1923f62008-08-04 07:31:14 +0000903 ->getElementType();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000904 while (Index < IList->getNumInits()) {
905 Expr *Init = IList->getInit(Index);
906 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000907 // If we're not the subobject that matches up with the '{' for
908 // the designator, we shouldn't be handling the
909 // designator. Return immediately.
910 if (!SubobjectIsDesignatorContext)
911 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000912
Douglas Gregor710f6d42009-01-22 23:26:18 +0000913 // Handle this designated initializer. elementIndex will be
914 // updated to be the next array element we'll initialize.
Douglas Gregoraa357272009-04-15 04:56:10 +0000915 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregorf603b472009-01-28 21:54:33 +0000916 DeclType, 0, &elementIndex, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000917 StructuredList, StructuredIndex, true,
918 false)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000919 hadError = true;
920 continue;
921 }
922
Douglas Gregor5a203a62009-01-23 16:54:12 +0000923 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
924 maxElements.extend(elementIndex.getBitWidth());
925 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
926 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000927 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor5a203a62009-01-23 16:54:12 +0000928
Douglas Gregor710f6d42009-01-22 23:26:18 +0000929 // If the array is of incomplete type, keep track of the number of
930 // elements in the initializer.
931 if (!maxElementsKnown && elementIndex > maxElements)
932 maxElements = elementIndex;
933
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000934 continue;
935 }
936
937 // If we know the maximum number of elements, and we've already
938 // hit it, stop consuming elements in the initializer list.
939 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000940 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000941
942 // Check this element.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000943 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000944 StructuredList, StructuredIndex);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000945 ++elementIndex;
946
947 // If the array is of incomplete type, keep track of the number of
948 // elements in the initializer.
949 if (!maxElementsKnown && elementIndex > maxElements)
950 maxElements = elementIndex;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000951 }
Eli Friedmanb4c71b32009-05-29 20:17:55 +0000952 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000953 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000954 // be calculated here.
Douglas Gregor69722702009-01-23 18:58:42 +0000955 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000956 if (maxElements == Zero) {
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000957 // Sizing an array implicitly to zero is not allowed by ISO C,
958 // but is supported by GNU.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000959 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000960 diag::ext_typecheck_zero_array_size);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000961 }
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000962
Chris Lattner2e2766a2009-02-24 22:50:46 +0000963 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000964 ArrayType::Normal, 0);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000965 }
966}
967
968void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
969 QualType DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000970 RecordDecl::field_iterator Field,
971 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000972 unsigned &Index,
973 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000974 unsigned &StructuredIndex,
975 bool TopLevelObject) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000976 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000977
Eli Friedman683cedf2008-05-19 19:16:24 +0000978 // If the record is invalid, some of it's members are invalid. To avoid
979 // confusion, we forgo checking the intializer for the entire record.
980 if (structDecl->isInvalidDecl()) {
981 hadError = true;
982 return;
983 }
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000984
985 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
986 // Value-initialize the first named member of the union.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000987 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000988 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000989 Field != FieldEnd; ++Field) {
990 if (Field->getDeclName()) {
991 StructuredList->setInitializedFieldInUnion(*Field);
992 break;
993 }
994 }
995 return;
996 }
997
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000998 // If structDecl is a forward declaration, this loop won't do
999 // anything except look at designated initializers; That's okay,
1000 // because an error should get printed out elsewhere. It might be
1001 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001002 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001003 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001004 bool InitializedSomething = false;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001005 while (Index < IList->getNumInits()) {
1006 Expr *Init = IList->getInit(Index);
1007
1008 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001009 // If we're not the subobject that matches up with the '{' for
1010 // the designator, we shouldn't be handling the
1011 // designator. Return immediately.
1012 if (!SubobjectIsDesignatorContext)
1013 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001014
Douglas Gregor710f6d42009-01-22 23:26:18 +00001015 // Handle this designated initializer. Field will be updated to
1016 // the next field that we'll be initializing.
Douglas Gregoraa357272009-04-15 04:56:10 +00001017 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregorf603b472009-01-28 21:54:33 +00001018 DeclType, &Field, 0, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001019 StructuredList, StructuredIndex,
1020 true, TopLevelObject))
Douglas Gregor710f6d42009-01-22 23:26:18 +00001021 hadError = true;
1022
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001023 InitializedSomething = true;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001024 continue;
1025 }
1026
1027 if (Field == FieldEnd) {
1028 // We've run out of fields. We're done.
1029 break;
1030 }
1031
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001032 // We've already initialized a member of a union. We're done.
1033 if (InitializedSomething && DeclType->isUnionType())
1034 break;
1035
Douglas Gregor8acb7272008-12-11 16:49:14 +00001036 // If we've hit the flexible array member at the end, we're done.
1037 if (Field->getType()->isIncompleteArrayType())
1038 break;
1039
Douglas Gregor82462762009-01-29 16:53:55 +00001040 if (Field->isUnnamedBitfield()) {
Douglas Gregorf603b472009-01-28 21:54:33 +00001041 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001042 ++Field;
Eli Friedman683cedf2008-05-19 19:16:24 +00001043 continue;
Steve Naroffc4d4a482008-05-01 22:18:59 +00001044 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001045
Douglas Gregor36859eb2009-01-29 00:39:20 +00001046 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001047 StructuredList, StructuredIndex);
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001048 InitializedSomething = true;
Douglas Gregor82462762009-01-29 16:53:55 +00001049
1050 if (DeclType->isUnionType()) {
1051 // Initialize the first field within the union.
1052 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor82462762009-01-29 16:53:55 +00001053 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001054
1055 ++Field;
Steve Naroffc4d4a482008-05-01 22:18:59 +00001056 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001057
Douglas Gregorbe69b162009-02-04 22:46:25 +00001058 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001059 Index >= IList->getNumInits())
Douglas Gregorbe69b162009-02-04 22:46:25 +00001060 return;
1061
1062 // Handle GNU flexible array initializers.
1063 if (!TopLevelObject &&
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001064 (!isa<InitListExpr>(IList->getInit(Index)) ||
1065 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001066 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001067 diag::err_flexible_array_init_nonempty)
1068 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001069 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001070 << *Field;
1071 hadError = true;
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001072 ++Index;
1073 return;
1074 } else {
1075 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
1076 diag::ext_flexible_array_init)
1077 << IList->getInit(Index)->getSourceRange().getBegin();
1078 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1079 << *Field;
Douglas Gregorbe69b162009-02-04 22:46:25 +00001080 }
1081
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001082 if (isa<InitListExpr>(IList->getInit(Index)))
1083 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1084 StructuredIndex);
1085 else
1086 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1087 StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +00001088}
Steve Naroffc4d4a482008-05-01 22:18:59 +00001089
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001090/// \brief Expand a field designator that refers to a member of an
1091/// anonymous struct or union into a series of field designators that
1092/// refers to the field within the appropriate subobject.
1093///
1094/// Field/FieldIndex will be updated to point to the (new)
1095/// currently-designated field.
1096static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1097 DesignatedInitExpr *DIE,
1098 unsigned DesigIdx,
1099 FieldDecl *Field,
1100 RecordDecl::field_iterator &FieldIter,
1101 unsigned &FieldIndex) {
1102 typedef DesignatedInitExpr::Designator Designator;
1103
1104 // Build the path from the current object to the member of the
1105 // anonymous struct/union (backwards).
1106 llvm::SmallVector<FieldDecl *, 4> Path;
1107 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
1108
1109 // Build the replacement designators.
1110 llvm::SmallVector<Designator, 4> Replacements;
1111 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1112 FI = Path.rbegin(), FIEnd = Path.rend();
1113 FI != FIEnd; ++FI) {
1114 if (FI + 1 == FIEnd)
1115 Replacements.push_back(Designator((IdentifierInfo *)0,
1116 DIE->getDesignator(DesigIdx)->getDotLoc(),
1117 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1118 else
1119 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1120 SourceLocation()));
1121 Replacements.back().setField(*FI);
1122 }
1123
1124 // Expand the current designator into the set of replacement
1125 // designators, so we have a full subobject path down to where the
1126 // member of the anonymous struct/union is actually stored.
1127 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
1128 &Replacements[0] + Replacements.size());
1129
1130 // Update FieldIter/FieldIndex;
1131 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001132 FieldIter = Record->field_begin();
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001133 FieldIndex = 0;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001134 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001135 FieldIter != FEnd; ++FieldIter) {
1136 if (FieldIter->isUnnamedBitfield())
1137 continue;
1138
1139 if (*FieldIter == Path.back())
1140 return;
1141
1142 ++FieldIndex;
1143 }
1144
1145 assert(false && "Unable to find anonymous struct/union field");
1146}
1147
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001148/// @brief Check the well-formedness of a C99 designated initializer.
1149///
1150/// Determines whether the designated initializer @p DIE, which
1151/// resides at the given @p Index within the initializer list @p
1152/// IList, is well-formed for a current object of type @p DeclType
1153/// (C99 6.7.8). The actual subobject that this designator refers to
1154/// within the current subobject is returned in either
Douglas Gregorf603b472009-01-28 21:54:33 +00001155/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001156///
1157/// @param IList The initializer list in which this designated
1158/// initializer occurs.
1159///
Douglas Gregoraa357272009-04-15 04:56:10 +00001160/// @param DIE The designated initializer expression.
1161///
1162/// @param DesigIdx The index of the current designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001163///
1164/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1165/// into which the designation in @p DIE should refer.
1166///
Douglas Gregor710f6d42009-01-22 23:26:18 +00001167/// @param NextField If non-NULL and the first designator in @p DIE is
1168/// a field, this will be set to the field declaration corresponding
1169/// to the field named by the designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001170///
Douglas Gregor710f6d42009-01-22 23:26:18 +00001171/// @param NextElementIndex If non-NULL and the first designator in @p
1172/// DIE is an array designator or GNU array-range designator, this
1173/// will be set to the last index initialized by this designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001174///
1175/// @param Index Index into @p IList where the designated initializer
1176/// @p DIE occurs.
1177///
Douglas Gregorf603b472009-01-28 21:54:33 +00001178/// @param StructuredList The initializer list expression that
1179/// describes all of the subobject initializers in the order they'll
1180/// actually be initialized.
1181///
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001182/// @returns true if there was an error, false otherwise.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001183bool
1184InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
1185 DesignatedInitExpr *DIE,
Douglas Gregoraa357272009-04-15 04:56:10 +00001186 unsigned DesigIdx,
Douglas Gregor710f6d42009-01-22 23:26:18 +00001187 QualType &CurrentObjectType,
1188 RecordDecl::field_iterator *NextField,
1189 llvm::APSInt *NextElementIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +00001190 unsigned &Index,
1191 InitListExpr *StructuredList,
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001192 unsigned &StructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001193 bool FinishSubobjectInit,
1194 bool TopLevelObject) {
Douglas Gregoraa357272009-04-15 04:56:10 +00001195 if (DesigIdx == DIE->size()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001196 // Check the actual initialization for the designated object type.
1197 bool prevHadError = hadError;
Douglas Gregor36859eb2009-01-29 00:39:20 +00001198
1199 // Temporarily remove the designator expression from the
1200 // initializer list that the child calls see, so that we don't try
1201 // to re-process the designator.
1202 unsigned OldIndex = Index;
1203 IList->setInit(OldIndex, DIE->getInit());
1204
1205 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001206 StructuredList, StructuredIndex);
Douglas Gregor36859eb2009-01-29 00:39:20 +00001207
1208 // Restore the designated initializer expression in the syntactic
1209 // form of the initializer list.
1210 if (IList->getInit(OldIndex) != DIE->getInit())
1211 DIE->setInit(IList->getInit(OldIndex));
1212 IList->setInit(OldIndex, DIE);
1213
Douglas Gregor710f6d42009-01-22 23:26:18 +00001214 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001215 }
1216
Douglas Gregoraa357272009-04-15 04:56:10 +00001217 bool IsFirstDesignator = (DesigIdx == 0);
Douglas Gregorf603b472009-01-28 21:54:33 +00001218 assert((IsFirstDesignator || StructuredList) &&
1219 "Need a non-designated initializer list to start from");
1220
Douglas Gregoraa357272009-04-15 04:56:10 +00001221 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregorf603b472009-01-28 21:54:33 +00001222 // Determine the structural initializer list that corresponds to the
1223 // current subobject.
1224 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Douglas Gregorea765e12009-03-01 17:12:46 +00001225 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1226 StructuredList, StructuredIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +00001227 SourceRange(D->getStartLocation(),
1228 DIE->getSourceRange().getEnd()));
1229 assert(StructuredList && "Expected a structured initializer list");
1230
Douglas Gregor710f6d42009-01-22 23:26:18 +00001231 if (D->isFieldDesignator()) {
1232 // C99 6.7.8p7:
1233 //
1234 // If a designator has the form
1235 //
1236 // . identifier
1237 //
1238 // then the current object (defined below) shall have
1239 // structure or union type and the identifier shall be the
1240 // name of a member of that type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001241 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001242 if (!RT) {
1243 SourceLocation Loc = D->getDotLoc();
1244 if (Loc.isInvalid())
1245 Loc = D->getFieldLoc();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001246 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1247 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001248 ++Index;
1249 return true;
1250 }
1251
Douglas Gregorf603b472009-01-28 21:54:33 +00001252 // Note: we perform a linear search of the fields here, despite
1253 // the fact that we have a faster lookup method, because we always
1254 // need to compute the field's index.
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001255 FieldDecl *KnownField = D->getField();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001256 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregorf603b472009-01-28 21:54:33 +00001257 unsigned FieldIndex = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001258 RecordDecl::field_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001259 Field = RT->getDecl()->field_begin(),
1260 FieldEnd = RT->getDecl()->field_end();
Douglas Gregorf603b472009-01-28 21:54:33 +00001261 for (; Field != FieldEnd; ++Field) {
1262 if (Field->isUnnamedBitfield())
1263 continue;
1264
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001265 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregorf603b472009-01-28 21:54:33 +00001266 break;
1267
1268 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001269 }
1270
Douglas Gregorf603b472009-01-28 21:54:33 +00001271 if (Field == FieldEnd) {
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001272 // There was no normal field in the struct with the designated
1273 // name. Perform another lookup for this name, which may find
1274 // something that we can't designate (e.g., a member function),
1275 // may find nothing, or may find a member of an anonymous
1276 // struct/union.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001277 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorf603b472009-01-28 21:54:33 +00001278 if (Lookup.first == Lookup.second) {
1279 // Name lookup didn't find anything.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001280 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregorf603b472009-01-28 21:54:33 +00001281 << FieldName << CurrentObjectType;
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001282 ++Index;
1283 return true;
1284 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1285 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1286 ->isAnonymousStructOrUnion()) {
1287 // Handle an field designator that refers to a member of an
1288 // anonymous struct or union.
1289 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1290 cast<FieldDecl>(*Lookup.first),
1291 Field, FieldIndex);
Eli Friedmanbd45b552009-04-16 17:49:48 +00001292 D = DIE->getDesignator(DesigIdx);
Douglas Gregorf603b472009-01-28 21:54:33 +00001293 } else {
1294 // Name lookup found something, but it wasn't a field.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001295 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregorf603b472009-01-28 21:54:33 +00001296 << FieldName;
Chris Lattner2e2766a2009-02-24 22:50:46 +00001297 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001298 diag::note_field_designator_found);
Eli Friedmanbd45b552009-04-16 17:49:48 +00001299 ++Index;
1300 return true;
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001301 }
1302 } else if (!KnownField &&
1303 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregorf603b472009-01-28 21:54:33 +00001304 ->isAnonymousStructOrUnion()) {
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001305 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1306 Field, FieldIndex);
1307 D = DIE->getDesignator(DesigIdx);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001308 }
Douglas Gregorf603b472009-01-28 21:54:33 +00001309
1310 // All of the fields of a union are located at the same place in
1311 // the initializer list.
Douglas Gregor82462762009-01-29 16:53:55 +00001312 if (RT->getDecl()->isUnion()) {
Douglas Gregorf603b472009-01-28 21:54:33 +00001313 FieldIndex = 0;
Douglas Gregor82462762009-01-29 16:53:55 +00001314 StructuredList->setInitializedFieldInUnion(*Field);
1315 }
Douglas Gregorf603b472009-01-28 21:54:33 +00001316
Douglas Gregor710f6d42009-01-22 23:26:18 +00001317 // Update the designator with the field declaration.
Douglas Gregorf603b472009-01-28 21:54:33 +00001318 D->setField(*Field);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001319
Douglas Gregorf603b472009-01-28 21:54:33 +00001320 // Make sure that our non-designated initializer list has space
1321 // for a subobject corresponding to this field.
1322 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner2e2766a2009-02-24 22:50:46 +00001323 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +00001324
Douglas Gregorbe69b162009-02-04 22:46:25 +00001325 // This designator names a flexible array member.
1326 if (Field->getType()->isIncompleteArrayType()) {
1327 bool Invalid = false;
Douglas Gregoraa357272009-04-15 04:56:10 +00001328 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorbe69b162009-02-04 22:46:25 +00001329 // We can't designate an object within the flexible array
1330 // member (because GCC doesn't allow it).
Douglas Gregoraa357272009-04-15 04:56:10 +00001331 DesignatedInitExpr::Designator *NextD
1332 = DIE->getDesignator(DesigIdx + 1);
Chris Lattner2e2766a2009-02-24 22:50:46 +00001333 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001334 diag::err_designator_into_flexible_array_member)
1335 << SourceRange(NextD->getStartLocation(),
1336 DIE->getSourceRange().getEnd());
Chris Lattner2e2766a2009-02-24 22:50:46 +00001337 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001338 << *Field;
1339 Invalid = true;
1340 }
1341
1342 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1343 // The initializer is not an initializer list.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001344 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001345 diag::err_flexible_array_init_needs_braces)
1346 << DIE->getInit()->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001347 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001348 << *Field;
1349 Invalid = true;
1350 }
1351
1352 // Handle GNU flexible array initializers.
1353 if (!Invalid && !TopLevelObject &&
1354 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001355 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001356 diag::err_flexible_array_init_nonempty)
1357 << DIE->getSourceRange().getBegin();
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 if (Invalid) {
1364 ++Index;
1365 return true;
1366 }
1367
1368 // Initialize the array.
1369 bool prevHadError = hadError;
1370 unsigned newStructuredIndex = FieldIndex;
1371 unsigned OldIndex = Index;
1372 IList->setInit(Index, DIE->getInit());
1373 CheckSubElementType(IList, Field->getType(), Index,
1374 StructuredList, newStructuredIndex);
1375 IList->setInit(OldIndex, DIE);
1376 if (hadError && !prevHadError) {
1377 ++Field;
1378 ++FieldIndex;
1379 if (NextField)
1380 *NextField = Field;
1381 StructuredIndex = FieldIndex;
1382 return true;
1383 }
1384 } else {
1385 // Recurse to check later designated subobjects.
1386 QualType FieldType = (*Field)->getType();
1387 unsigned newStructuredIndex = FieldIndex;
Douglas Gregoraa357272009-04-15 04:56:10 +00001388 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1389 Index, StructuredList, newStructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001390 true, false))
1391 return true;
1392 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001393
1394 // Find the position of the next field to be initialized in this
1395 // subobject.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001396 ++Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001397 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001398
1399 // If this the first designator, our caller will continue checking
1400 // the rest of this struct/class/union subobject.
1401 if (IsFirstDesignator) {
1402 if (NextField)
1403 *NextField = Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001404 StructuredIndex = FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001405 return false;
1406 }
1407
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001408 if (!FinishSubobjectInit)
1409 return false;
1410
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001411 // We've already initialized something in the union; we're done.
1412 if (RT->getDecl()->isUnion())
1413 return hadError;
1414
Douglas Gregor710f6d42009-01-22 23:26:18 +00001415 // Check the remaining fields within this class/struct/union subobject.
1416 bool prevHadError = hadError;
Douglas Gregorf603b472009-01-28 21:54:33 +00001417 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1418 StructuredList, FieldIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001419 return hadError && !prevHadError;
1420 }
1421
1422 // C99 6.7.8p6:
1423 //
1424 // If a designator has the form
1425 //
1426 // [ constant-expression ]
1427 //
1428 // then the current object (defined below) shall have array
1429 // type and the expression shall be an integer constant
1430 // expression. If the array is of unknown size, any
1431 // nonnegative value is valid.
1432 //
1433 // Additionally, cope with the GNU extension that permits
1434 // designators of the form
1435 //
1436 // [ constant-expression ... constant-expression ]
Chris Lattner2e2766a2009-02-24 22:50:46 +00001437 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001438 if (!AT) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001439 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor710f6d42009-01-22 23:26:18 +00001440 << CurrentObjectType;
1441 ++Index;
1442 return true;
1443 }
1444
1445 Expr *IndexExpr = 0;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001446 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1447 if (D->isArrayDesignator()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001448 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnereec8ae22009-04-25 21:59:05 +00001449 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001450 DesignatedEndIndex = DesignatedStartIndex;
1451 } else {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001452 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001453
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001454
Chris Lattnereec8ae22009-04-25 21:59:05 +00001455 DesignatedStartIndex =
1456 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
1457 DesignatedEndIndex =
1458 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001459 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001460
Chris Lattnereec8ae22009-04-25 21:59:05 +00001461 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregor9fddded2009-01-29 19:42:23 +00001462 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001463 }
1464
Douglas Gregor710f6d42009-01-22 23:26:18 +00001465 if (isa<ConstantArrayType>(AT)) {
1466 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001467 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1468 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1469 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1470 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1471 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001472 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor710f6d42009-01-22 23:26:18 +00001473 diag::err_array_designator_too_large)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001474 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor710f6d42009-01-22 23:26:18 +00001475 << IndexExpr->getSourceRange();
1476 ++Index;
1477 return true;
1478 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001479 } else {
1480 // Make sure the bit-widths and signedness match.
1481 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1482 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnereec8ae22009-04-25 21:59:05 +00001483 else if (DesignatedStartIndex.getBitWidth() <
1484 DesignatedEndIndex.getBitWidth())
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001485 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1486 DesignatedStartIndex.setIsUnsigned(true);
1487 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001488 }
1489
Douglas Gregorf603b472009-01-28 21:54:33 +00001490 // Make sure that our non-designated initializer list has space
1491 // for a subobject corresponding to this array element.
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001492 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Chris Lattner2e2766a2009-02-24 22:50:46 +00001493 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001494 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +00001495
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001496 // Repeatedly perform subobject initializations in the range
1497 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor710f6d42009-01-22 23:26:18 +00001498
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001499 // Move to the next designator
1500 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1501 unsigned OldIndex = Index;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001502 while (DesignatedStartIndex <= DesignatedEndIndex) {
1503 // Recurse to check later designated subobjects.
1504 QualType ElementType = AT->getElementType();
1505 Index = OldIndex;
Douglas Gregoraa357272009-04-15 04:56:10 +00001506 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1507 Index, StructuredList, ElementIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001508 (DesignatedStartIndex == DesignatedEndIndex),
1509 false))
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001510 return true;
1511
1512 // Move to the next index in the array that we'll be initializing.
1513 ++DesignatedStartIndex;
1514 ElementIndex = DesignatedStartIndex.getZExtValue();
1515 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001516
1517 // If this the first designator, our caller will continue checking
1518 // the rest of this array subobject.
1519 if (IsFirstDesignator) {
1520 if (NextElementIndex)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001521 *NextElementIndex = DesignatedStartIndex;
Douglas Gregorf603b472009-01-28 21:54:33 +00001522 StructuredIndex = ElementIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001523 return false;
1524 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001525
1526 if (!FinishSubobjectInit)
1527 return false;
1528
Douglas Gregor710f6d42009-01-22 23:26:18 +00001529 // Check the remaining elements within this array subobject.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001530 bool prevHadError = hadError;
Douglas Gregord7e76c52009-02-09 19:45:19 +00001531 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001532 StructuredList, ElementIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001533 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001534}
1535
Douglas Gregorf603b472009-01-28 21:54:33 +00001536// Get the structured initializer list for a subobject of type
1537// @p CurrentObjectType.
1538InitListExpr *
1539InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1540 QualType CurrentObjectType,
1541 InitListExpr *StructuredList,
1542 unsigned StructuredIndex,
1543 SourceRange InitRange) {
1544 Expr *ExistingInit = 0;
1545 if (!StructuredList)
1546 ExistingInit = SyntacticToSemantic[IList];
1547 else if (StructuredIndex < StructuredList->getNumInits())
1548 ExistingInit = StructuredList->getInit(StructuredIndex);
1549
1550 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1551 return Result;
1552
1553 if (ExistingInit) {
1554 // We are creating an initializer list that initializes the
1555 // subobjects of the current object, but there was already an
1556 // initialization that completely initialized the current
1557 // subobject, e.g., by a compound literal:
1558 //
1559 // struct X { int a, b; };
1560 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1561 //
1562 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1563 // designated initializer re-initializes the whole
1564 // subobject [0], overwriting previous initializers.
Douglas Gregorea765e12009-03-01 17:12:46 +00001565 SemaRef.Diag(InitRange.getBegin(),
1566 diag::warn_subobject_initializer_overrides)
Douglas Gregorf603b472009-01-28 21:54:33 +00001567 << InitRange;
Chris Lattner2e2766a2009-02-24 22:50:46 +00001568 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001569 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001570 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001571 << ExistingInit->getSourceRange();
1572 }
1573
1574 InitListExpr *Result
Douglas Gregorea765e12009-03-01 17:12:46 +00001575 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
1576 InitRange.getEnd());
1577
Douglas Gregorf603b472009-01-28 21:54:33 +00001578 Result->setType(CurrentObjectType);
1579
Douglas Gregoree0792c2009-03-20 23:58:33 +00001580 // Pre-allocate storage for the structured initializer list.
1581 unsigned NumElements = 0;
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001582 unsigned NumInits = 0;
1583 if (!StructuredList)
1584 NumInits = IList->getNumInits();
1585 else if (Index < IList->getNumInits()) {
1586 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1587 NumInits = SubList->getNumInits();
1588 }
1589
Douglas Gregoree0792c2009-03-20 23:58:33 +00001590 if (const ArrayType *AType
1591 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1592 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1593 NumElements = CAType->getSize().getZExtValue();
1594 // Simple heuristic so that we don't allocate a very large
1595 // initializer with many empty entries at the end.
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001596 if (NumInits && NumElements > NumInits)
Douglas Gregoree0792c2009-03-20 23:58:33 +00001597 NumElements = 0;
1598 }
1599 } else if (const VectorType *VType = CurrentObjectType->getAsVectorType())
1600 NumElements = VType->getNumElements();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001601 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregoree0792c2009-03-20 23:58:33 +00001602 RecordDecl *RDecl = RType->getDecl();
1603 if (RDecl->isUnion())
1604 NumElements = 1;
1605 else
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001606 NumElements = std::distance(RDecl->field_begin(),
1607 RDecl->field_end());
Douglas Gregoree0792c2009-03-20 23:58:33 +00001608 }
1609
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001610 if (NumElements < NumInits)
Douglas Gregoree0792c2009-03-20 23:58:33 +00001611 NumElements = IList->getNumInits();
1612
1613 Result->reserveInits(NumElements);
1614
Douglas Gregorf603b472009-01-28 21:54:33 +00001615 // Link this new initializer list into the structured initializer
1616 // lists.
1617 if (StructuredList)
1618 StructuredList->updateInit(StructuredIndex, Result);
1619 else {
1620 Result->setSyntacticForm(IList);
1621 SyntacticToSemantic[IList] = Result;
1622 }
1623
1624 return Result;
1625}
1626
1627/// Update the initializer at index @p StructuredIndex within the
1628/// structured initializer list to the value @p expr.
1629void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1630 unsigned &StructuredIndex,
1631 Expr *expr) {
1632 // No structured initializer list to update
1633 if (!StructuredList)
1634 return;
1635
1636 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1637 // This initializer overwrites a previous initializer. Warn.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001638 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001639 diag::warn_initializer_overrides)
1640 << expr->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001641 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001642 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001643 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001644 << PrevInit->getSourceRange();
1645 }
1646
1647 ++StructuredIndex;
1648}
1649
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001650/// Check that the given Index expression is a valid array designator
1651/// value. This is essentailly just a wrapper around
Chris Lattnereec8ae22009-04-25 21:59:05 +00001652/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001653/// and produces a reasonable diagnostic if there is a
1654/// failure. Returns true if there was an error, false otherwise. If
1655/// everything went okay, Value will receive the value of the constant
1656/// expression.
1657static bool
Chris Lattnereec8ae22009-04-25 21:59:05 +00001658CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001659 SourceLocation Loc = Index->getSourceRange().getBegin();
1660
1661 // Make sure this is an integer constant expression.
Chris Lattnereec8ae22009-04-25 21:59:05 +00001662 if (S.VerifyIntegerConstantExpression(Index, &Value))
1663 return true;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001664
Chris Lattnereec8ae22009-04-25 21:59:05 +00001665 if (Value.isSigned() && Value.isNegative())
1666 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001667 << Value.toString(10) << Index->getSourceRange();
1668
Douglas Gregore498e372009-01-23 21:04:18 +00001669 Value.setIsUnsigned(true);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001670 return false;
1671}
1672
1673Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1674 SourceLocation Loc,
Douglas Gregor5f34f0e2009-03-28 00:41:23 +00001675 bool GNUSyntax,
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001676 OwningExprResult Init) {
1677 typedef DesignatedInitExpr::Designator ASTDesignator;
1678
1679 bool Invalid = false;
1680 llvm::SmallVector<ASTDesignator, 32> Designators;
1681 llvm::SmallVector<Expr *, 32> InitExpressions;
1682
1683 // Build designators and check array designator expressions.
1684 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1685 const Designator &D = Desig.getDesignator(Idx);
1686 switch (D.getKind()) {
1687 case Designator::FieldDesignator:
1688 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1689 D.getFieldLoc()));
1690 break;
1691
1692 case Designator::ArrayDesignator: {
1693 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1694 llvm::APSInt IndexValue;
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001695 if (!Index->isTypeDependent() &&
1696 !Index->isValueDependent() &&
1697 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001698 Invalid = true;
1699 else {
1700 Designators.push_back(ASTDesignator(InitExpressions.size(),
1701 D.getLBracketLoc(),
1702 D.getRBracketLoc()));
1703 InitExpressions.push_back(Index);
1704 }
1705 break;
1706 }
1707
1708 case Designator::ArrayRangeDesignator: {
1709 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1710 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1711 llvm::APSInt StartValue;
1712 llvm::APSInt EndValue;
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001713 bool StartDependent = StartIndex->isTypeDependent() ||
1714 StartIndex->isValueDependent();
1715 bool EndDependent = EndIndex->isTypeDependent() ||
1716 EndIndex->isValueDependent();
1717 if ((!StartDependent &&
1718 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1719 (!EndDependent &&
1720 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001721 Invalid = true;
Douglas Gregorea0528d2009-01-23 22:22:29 +00001722 else {
1723 // Make sure we're comparing values with the same bit width.
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001724 if (StartDependent || EndDependent) {
1725 // Nothing to compute.
1726 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregorea0528d2009-01-23 22:22:29 +00001727 EndValue.extend(StartValue.getBitWidth());
1728 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1729 StartValue.extend(EndValue.getBitWidth());
1730
Douglas Gregor1401c062009-05-21 23:30:39 +00001731 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregorea0528d2009-01-23 22:22:29 +00001732 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1733 << StartValue.toString(10) << EndValue.toString(10)
1734 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1735 Invalid = true;
1736 } else {
1737 Designators.push_back(ASTDesignator(InitExpressions.size(),
1738 D.getLBracketLoc(),
1739 D.getEllipsisLoc(),
1740 D.getRBracketLoc()));
1741 InitExpressions.push_back(StartIndex);
1742 InitExpressions.push_back(EndIndex);
1743 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001744 }
1745 break;
1746 }
1747 }
1748 }
1749
1750 if (Invalid || Init.isInvalid())
1751 return ExprError();
1752
1753 // Clear out the expressions within the designation.
1754 Desig.ClearExprs(*this);
1755
1756 DesignatedInitExpr *DIE
Jay Foad9e6bef42009-05-21 09:52:38 +00001757 = DesignatedInitExpr::Create(Context,
1758 Designators.data(), Designators.size(),
1759 InitExpressions.data(), InitExpressions.size(),
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001760 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001761 return Owned(DIE);
1762}
Douglas Gregor849afc32009-01-29 00:45:39 +00001763
1764bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001765 InitListChecker CheckInitList(*this, InitList, DeclType);
Douglas Gregor849afc32009-01-29 00:45:39 +00001766 if (!CheckInitList.HadError())
1767 InitList = CheckInitList.getFullyStructuredList();
1768
1769 return CheckInitList.HadError();
1770}
Douglas Gregor538a4c22009-02-02 17:43:21 +00001771
1772/// \brief Diagnose any semantic errors with value-initialization of
1773/// the given type.
1774///
1775/// Value-initialization effectively zero-initializes any types
1776/// without user-declared constructors, and calls the default
1777/// constructor for a for any type that has a user-declared
1778/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1779/// a type with a user-declared constructor does not have an
1780/// accessible, non-deleted default constructor. In C, everything can
1781/// be value-initialized, which corresponds to C's notion of
1782/// initializing objects with static storage duration when no
1783/// initializer is provided for that object.
1784///
1785/// \returns true if there was an error, false otherwise.
1786bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1787 // C++ [dcl.init]p5:
1788 //
1789 // To value-initialize an object of type T means:
1790
1791 // -- if T is an array type, then each element is value-initialized;
1792 if (const ArrayType *AT = Context.getAsArrayType(Type))
1793 return CheckValueInitialization(AT->getElementType(), Loc);
1794
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001795 if (const RecordType *RT = Type->getAs<RecordType>()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001796 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Douglas Gregor538a4c22009-02-02 17:43:21 +00001797 // -- if T is a class type (clause 9) with a user-declared
1798 // constructor (12.1), then the default constructor for T is
1799 // called (and the initialization is ill-formed if T has no
1800 // accessible default constructor);
Douglas Gregor2e047592009-02-28 01:32:25 +00001801 if (ClassDecl->hasUserDeclaredConstructor())
Mike Stumpe127ae32009-05-16 07:39:55 +00001802 // FIXME: Eventually, we'll need to put the constructor decl into the
1803 // AST.
Douglas Gregor538a4c22009-02-02 17:43:21 +00001804 return PerformInitializationByConstructor(Type, 0, 0, Loc,
1805 SourceRange(Loc),
1806 DeclarationName(),
1807 IK_Direct);
1808 }
1809 }
1810
1811 if (Type->isReferenceType()) {
1812 // C++ [dcl.init]p5:
1813 // [...] A program that calls for default-initialization or
1814 // value-initialization of an entity of reference type is
1815 // ill-formed. [...]
Mike Stumpe127ae32009-05-16 07:39:55 +00001816 // FIXME: Once we have code that goes through this path, add an actual
1817 // diagnostic :)
Douglas Gregor538a4c22009-02-02 17:43:21 +00001818 }
1819
1820 return false;
1821}