blob: fb000089832a54cf40d9e69518c5db558805dbf8 [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
Anders Carlsson06386552009-08-27 17:18:13 +0000664 = SemaRef.TryCopyInitialization(expr, ElemType,
665 /*SuppressUserConversions=*/false,
666 /*ForceRValue=*/false);
667
Douglas Gregord45210d2009-01-30 22:09:00 +0000668 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000669 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregord45210d2009-01-30 22:09:00 +0000670 "initializing"))
671 hadError = true;
672 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
673 ++Index;
674 return;
675 }
676
677 // Fall through for subaggregate initialization
678 } else {
679 // C99 6.7.8p13:
680 //
681 // The initializer for a structure or union object that has
682 // automatic storage duration shall be either an initializer
683 // list as described below, or a single expression that has
684 // compatible structure or union type. In the latter case, the
685 // initial value of the object, including unnamed members, is
686 // that of the expression.
Eli Friedman2a553812009-06-13 10:38:46 +0000687 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman95acf982009-05-29 18:22:49 +0000688 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000689 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
690 ++Index;
691 return;
692 }
693
694 // Fall through for subaggregate initialization
695 }
696
697 // C++ [dcl.init.aggr]p12:
698 //
699 // [...] Otherwise, if the member is itself a non-empty
700 // subaggregate, brace elision is assumed and the initializer is
701 // considered for the initialization of the first member of
702 // the subaggregate.
703 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
704 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
705 StructuredIndex);
706 ++StructuredIndex;
707 } else {
708 // We cannot initialize this element, so let
709 // PerformCopyInitialization produce the appropriate diagnostic.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000710 SemaRef.PerformCopyInitialization(expr, ElemType, "initializing");
Douglas Gregord45210d2009-01-30 22:09:00 +0000711 hadError = true;
712 ++Index;
713 ++StructuredIndex;
714 }
715 }
Eli Friedman683cedf2008-05-19 19:16:24 +0000716}
717
Douglas Gregord45210d2009-01-30 22:09:00 +0000718void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor36859eb2009-01-29 00:39:20 +0000719 unsigned &Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000720 InitListExpr *StructuredList,
721 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000722 if (Index < IList->getNumInits()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000723 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000724 if (isa<InitListExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000725 SemaRef.Diag(IList->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000726 diag::err_many_braces_around_scalar_init)
727 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000728 hadError = true;
729 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000730 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000731 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000732 } else if (isa<DesignatedInitExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000733 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000734 diag::err_designator_for_scalar_init)
735 << DeclType << expr->getSourceRange();
736 hadError = true;
737 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000738 ++StructuredIndex;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000739 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000740 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000741
Eli Friedmand8535af2008-05-19 20:00:43 +0000742 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000743 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedman71de9eb2008-05-19 20:12:18 +0000744 hadError = true; // types weren't compatible.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000745 else if (savExpr != expr) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000746 // The type was promoted, update initializer list.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000747 IList->setInit(Index, expr);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000748 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000749 if (hadError)
750 ++StructuredIndex;
751 else
752 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000753 ++Index;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000754 } else {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000755 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattner9d2cf082008-11-19 05:27:50 +0000756 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000757 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000758 ++Index;
759 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000760 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000761 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000762}
763
Douglas Gregord45210d2009-01-30 22:09:00 +0000764void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
765 unsigned &Index,
766 InitListExpr *StructuredList,
767 unsigned &StructuredIndex) {
768 if (Index < IList->getNumInits()) {
769 Expr *expr = IList->getInit(Index);
770 if (isa<InitListExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000771 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord45210d2009-01-30 22:09:00 +0000772 << DeclType << IList->getSourceRange();
773 hadError = true;
774 ++Index;
775 ++StructuredIndex;
776 return;
777 }
778
779 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000780 if (SemaRef.CheckReferenceInit(expr, DeclType))
Douglas Gregord45210d2009-01-30 22:09:00 +0000781 hadError = true;
782 else if (savExpr != expr) {
783 // The type was promoted, update initializer list.
784 IList->setInit(Index, expr);
785 }
786 if (hadError)
787 ++StructuredIndex;
788 else
789 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
790 ++Index;
791 } else {
Mike Stumpe127ae32009-05-16 07:39:55 +0000792 // FIXME: It would be wonderful if we could point at the actual member. In
793 // general, it would be useful to pass location information down the stack,
794 // so that we know the location (or decl) of the "current object" being
795 // initialized.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000796 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord45210d2009-01-30 22:09:00 +0000797 diag::err_init_reference_member_uninitialized)
798 << DeclType
799 << IList->getSourceRange();
800 hadError = true;
801 ++Index;
802 ++StructuredIndex;
803 return;
804 }
805}
806
Steve Naroffc4d4a482008-05-01 22:18:59 +0000807void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000808 unsigned &Index,
809 InitListExpr *StructuredList,
810 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000811 if (Index < IList->getNumInits()) {
812 const VectorType *VT = DeclType->getAsVectorType();
Nate Begemane85f43d2009-08-10 23:49:36 +0000813 unsigned maxElements = VT->getNumElements();
814 unsigned numEltsInit = 0;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000815 QualType elementType = VT->getElementType();
816
Nate Begemane85f43d2009-08-10 23:49:36 +0000817 if (!SemaRef.getLangOptions().OpenCL) {
818 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
819 // Don't attempt to go past the end of the init list
820 if (Index >= IList->getNumInits())
821 break;
822 CheckSubElementType(IList, elementType, Index,
823 StructuredList, StructuredIndex);
824 }
825 } else {
826 // OpenCL initializers allows vectors to be constructed from vectors.
827 for (unsigned i = 0; i < maxElements; ++i) {
828 // Don't attempt to go past the end of the init list
829 if (Index >= IList->getNumInits())
830 break;
831 QualType IType = IList->getInit(Index)->getType();
832 if (!IType->isVectorType()) {
833 CheckSubElementType(IList, elementType, Index,
834 StructuredList, StructuredIndex);
835 ++numEltsInit;
836 } else {
837 const VectorType *IVT = IType->getAsVectorType();
838 unsigned numIElts = IVT->getNumElements();
839 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
840 numIElts);
841 CheckSubElementType(IList, VecType, Index,
842 StructuredList, StructuredIndex);
843 numEltsInit += numIElts;
844 }
845 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000846 }
Nate Begemane85f43d2009-08-10 23:49:36 +0000847
848 // OpenCL & AltiVec require all elements to be initialized.
849 if (numEltsInit != maxElements)
850 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
851 SemaRef.Diag(IList->getSourceRange().getBegin(),
852 diag::err_vector_incorrect_num_initializers)
853 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000854 }
855}
856
857void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000858 llvm::APSInt elementIndex,
859 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000860 unsigned &Index,
861 InitListExpr *StructuredList,
862 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000863 // Check for the special-case of initializing an array with a string.
864 if (Index < IList->getNumInits()) {
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000865 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
866 SemaRef.Context)) {
867 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregorf603b472009-01-28 21:54:33 +0000868 // We place the string literal directly into the resulting
869 // initializer list. This is the only place where the structure
870 // of the structured initializer list doesn't match exactly,
871 // because doing so would involve allocating one character
872 // constant for each string.
Chris Lattner45d6fd62009-02-24 22:41:04 +0000873 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner2e2766a2009-02-24 22:50:46 +0000874 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000875 ++Index;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000876 return;
877 }
878 }
Chris Lattnera1923f62008-08-04 07:31:14 +0000879 if (const VariableArrayType *VAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000880 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman46f81662008-05-25 13:22:35 +0000881 // Check for VLAs; in standard C it would be possible to check this
882 // earlier, but I don't know where clang accepts VLAs (gcc accepts
883 // them in all sorts of strange places).
Chris Lattner2e2766a2009-02-24 22:50:46 +0000884 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000885 diag::err_variable_object_no_init)
886 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman46f81662008-05-25 13:22:35 +0000887 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000888 ++Index;
889 ++StructuredIndex;
Eli Friedman46f81662008-05-25 13:22:35 +0000890 return;
891 }
892
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000893 // We might know the maximum number of elements in advance.
Douglas Gregorf603b472009-01-28 21:54:33 +0000894 llvm::APSInt maxElements(elementIndex.getBitWidth(),
895 elementIndex.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000896 bool maxElementsKnown = false;
897 if (const ConstantArrayType *CAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000898 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000899 maxElements = CAT->getSize();
Douglas Gregor5a203a62009-01-23 16:54:12 +0000900 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000901 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000902 maxElementsKnown = true;
903 }
904
Chris Lattner2e2766a2009-02-24 22:50:46 +0000905 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnera1923f62008-08-04 07:31:14 +0000906 ->getElementType();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000907 while (Index < IList->getNumInits()) {
908 Expr *Init = IList->getInit(Index);
909 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000910 // If we're not the subobject that matches up with the '{' for
911 // the designator, we shouldn't be handling the
912 // designator. Return immediately.
913 if (!SubobjectIsDesignatorContext)
914 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000915
Douglas Gregor710f6d42009-01-22 23:26:18 +0000916 // Handle this designated initializer. elementIndex will be
917 // updated to be the next array element we'll initialize.
Douglas Gregoraa357272009-04-15 04:56:10 +0000918 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregorf603b472009-01-28 21:54:33 +0000919 DeclType, 0, &elementIndex, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000920 StructuredList, StructuredIndex, true,
921 false)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000922 hadError = true;
923 continue;
924 }
925
Douglas Gregor5a203a62009-01-23 16:54:12 +0000926 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
927 maxElements.extend(elementIndex.getBitWidth());
928 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
929 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000930 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor5a203a62009-01-23 16:54:12 +0000931
Douglas Gregor710f6d42009-01-22 23:26:18 +0000932 // If the array is of incomplete type, keep track of the number of
933 // elements in the initializer.
934 if (!maxElementsKnown && elementIndex > maxElements)
935 maxElements = elementIndex;
936
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000937 continue;
938 }
939
940 // If we know the maximum number of elements, and we've already
941 // hit it, stop consuming elements in the initializer list.
942 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000943 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000944
945 // Check this element.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000946 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000947 StructuredList, StructuredIndex);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000948 ++elementIndex;
949
950 // If the array is of incomplete type, keep track of the number of
951 // elements in the initializer.
952 if (!maxElementsKnown && elementIndex > maxElements)
953 maxElements = elementIndex;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000954 }
Eli Friedmanb4c71b32009-05-29 20:17:55 +0000955 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000956 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000957 // be calculated here.
Douglas Gregor69722702009-01-23 18:58:42 +0000958 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000959 if (maxElements == Zero) {
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000960 // Sizing an array implicitly to zero is not allowed by ISO C,
961 // but is supported by GNU.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000962 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000963 diag::ext_typecheck_zero_array_size);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000964 }
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000965
Chris Lattner2e2766a2009-02-24 22:50:46 +0000966 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000967 ArrayType::Normal, 0);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000968 }
969}
970
971void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
972 QualType DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000973 RecordDecl::field_iterator Field,
974 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000975 unsigned &Index,
976 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000977 unsigned &StructuredIndex,
978 bool TopLevelObject) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000979 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000980
Eli Friedman683cedf2008-05-19 19:16:24 +0000981 // If the record is invalid, some of it's members are invalid. To avoid
982 // confusion, we forgo checking the intializer for the entire record.
983 if (structDecl->isInvalidDecl()) {
984 hadError = true;
985 return;
986 }
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000987
988 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
989 // Value-initialize the first named member of the union.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000990 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000991 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000992 Field != FieldEnd; ++Field) {
993 if (Field->getDeclName()) {
994 StructuredList->setInitializedFieldInUnion(*Field);
995 break;
996 }
997 }
998 return;
999 }
1000
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001001 // If structDecl is a forward declaration, this loop won't do
1002 // anything except look at designated initializers; That's okay,
1003 // because an error should get printed out elsewhere. It might be
1004 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001005 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001006 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001007 bool InitializedSomething = false;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001008 while (Index < IList->getNumInits()) {
1009 Expr *Init = IList->getInit(Index);
1010
1011 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001012 // If we're not the subobject that matches up with the '{' for
1013 // the designator, we shouldn't be handling the
1014 // designator. Return immediately.
1015 if (!SubobjectIsDesignatorContext)
1016 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001017
Douglas Gregor710f6d42009-01-22 23:26:18 +00001018 // Handle this designated initializer. Field will be updated to
1019 // the next field that we'll be initializing.
Douglas Gregoraa357272009-04-15 04:56:10 +00001020 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregorf603b472009-01-28 21:54:33 +00001021 DeclType, &Field, 0, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001022 StructuredList, StructuredIndex,
1023 true, TopLevelObject))
Douglas Gregor710f6d42009-01-22 23:26:18 +00001024 hadError = true;
1025
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001026 InitializedSomething = true;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001027 continue;
1028 }
1029
1030 if (Field == FieldEnd) {
1031 // We've run out of fields. We're done.
1032 break;
1033 }
1034
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001035 // We've already initialized a member of a union. We're done.
1036 if (InitializedSomething && DeclType->isUnionType())
1037 break;
1038
Douglas Gregor8acb7272008-12-11 16:49:14 +00001039 // If we've hit the flexible array member at the end, we're done.
1040 if (Field->getType()->isIncompleteArrayType())
1041 break;
1042
Douglas Gregor82462762009-01-29 16:53:55 +00001043 if (Field->isUnnamedBitfield()) {
Douglas Gregorf603b472009-01-28 21:54:33 +00001044 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001045 ++Field;
Eli Friedman683cedf2008-05-19 19:16:24 +00001046 continue;
Steve Naroffc4d4a482008-05-01 22:18:59 +00001047 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001048
Douglas Gregor36859eb2009-01-29 00:39:20 +00001049 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001050 StructuredList, StructuredIndex);
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001051 InitializedSomething = true;
Douglas Gregor82462762009-01-29 16:53:55 +00001052
1053 if (DeclType->isUnionType()) {
1054 // Initialize the first field within the union.
1055 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor82462762009-01-29 16:53:55 +00001056 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001057
1058 ++Field;
Steve Naroffc4d4a482008-05-01 22:18:59 +00001059 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001060
Douglas Gregorbe69b162009-02-04 22:46:25 +00001061 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001062 Index >= IList->getNumInits())
Douglas Gregorbe69b162009-02-04 22:46:25 +00001063 return;
1064
1065 // Handle GNU flexible array initializers.
1066 if (!TopLevelObject &&
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001067 (!isa<InitListExpr>(IList->getInit(Index)) ||
1068 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001069 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001070 diag::err_flexible_array_init_nonempty)
1071 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001072 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001073 << *Field;
1074 hadError = true;
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001075 ++Index;
1076 return;
1077 } else {
1078 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
1079 diag::ext_flexible_array_init)
1080 << IList->getInit(Index)->getSourceRange().getBegin();
1081 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1082 << *Field;
Douglas Gregorbe69b162009-02-04 22:46:25 +00001083 }
1084
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001085 if (isa<InitListExpr>(IList->getInit(Index)))
1086 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1087 StructuredIndex);
1088 else
1089 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1090 StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +00001091}
Steve Naroffc4d4a482008-05-01 22:18:59 +00001092
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001093/// \brief Expand a field designator that refers to a member of an
1094/// anonymous struct or union into a series of field designators that
1095/// refers to the field within the appropriate subobject.
1096///
1097/// Field/FieldIndex will be updated to point to the (new)
1098/// currently-designated field.
1099static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1100 DesignatedInitExpr *DIE,
1101 unsigned DesigIdx,
1102 FieldDecl *Field,
1103 RecordDecl::field_iterator &FieldIter,
1104 unsigned &FieldIndex) {
1105 typedef DesignatedInitExpr::Designator Designator;
1106
1107 // Build the path from the current object to the member of the
1108 // anonymous struct/union (backwards).
1109 llvm::SmallVector<FieldDecl *, 4> Path;
1110 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
1111
1112 // Build the replacement designators.
1113 llvm::SmallVector<Designator, 4> Replacements;
1114 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1115 FI = Path.rbegin(), FIEnd = Path.rend();
1116 FI != FIEnd; ++FI) {
1117 if (FI + 1 == FIEnd)
1118 Replacements.push_back(Designator((IdentifierInfo *)0,
1119 DIE->getDesignator(DesigIdx)->getDotLoc(),
1120 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1121 else
1122 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1123 SourceLocation()));
1124 Replacements.back().setField(*FI);
1125 }
1126
1127 // Expand the current designator into the set of replacement
1128 // designators, so we have a full subobject path down to where the
1129 // member of the anonymous struct/union is actually stored.
1130 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
1131 &Replacements[0] + Replacements.size());
1132
1133 // Update FieldIter/FieldIndex;
1134 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001135 FieldIter = Record->field_begin();
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001136 FieldIndex = 0;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001137 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001138 FieldIter != FEnd; ++FieldIter) {
1139 if (FieldIter->isUnnamedBitfield())
1140 continue;
1141
1142 if (*FieldIter == Path.back())
1143 return;
1144
1145 ++FieldIndex;
1146 }
1147
1148 assert(false && "Unable to find anonymous struct/union field");
1149}
1150
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001151/// @brief Check the well-formedness of a C99 designated initializer.
1152///
1153/// Determines whether the designated initializer @p DIE, which
1154/// resides at the given @p Index within the initializer list @p
1155/// IList, is well-formed for a current object of type @p DeclType
1156/// (C99 6.7.8). The actual subobject that this designator refers to
1157/// within the current subobject is returned in either
Douglas Gregorf603b472009-01-28 21:54:33 +00001158/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001159///
1160/// @param IList The initializer list in which this designated
1161/// initializer occurs.
1162///
Douglas Gregoraa357272009-04-15 04:56:10 +00001163/// @param DIE The designated initializer expression.
1164///
1165/// @param DesigIdx The index of the current designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001166///
1167/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1168/// into which the designation in @p DIE should refer.
1169///
Douglas Gregor710f6d42009-01-22 23:26:18 +00001170/// @param NextField If non-NULL and the first designator in @p DIE is
1171/// a field, this will be set to the field declaration corresponding
1172/// to the field named by the designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001173///
Douglas Gregor710f6d42009-01-22 23:26:18 +00001174/// @param NextElementIndex If non-NULL and the first designator in @p
1175/// DIE is an array designator or GNU array-range designator, this
1176/// will be set to the last index initialized by this designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001177///
1178/// @param Index Index into @p IList where the designated initializer
1179/// @p DIE occurs.
1180///
Douglas Gregorf603b472009-01-28 21:54:33 +00001181/// @param StructuredList The initializer list expression that
1182/// describes all of the subobject initializers in the order they'll
1183/// actually be initialized.
1184///
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001185/// @returns true if there was an error, false otherwise.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001186bool
1187InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
1188 DesignatedInitExpr *DIE,
Douglas Gregoraa357272009-04-15 04:56:10 +00001189 unsigned DesigIdx,
Douglas Gregor710f6d42009-01-22 23:26:18 +00001190 QualType &CurrentObjectType,
1191 RecordDecl::field_iterator *NextField,
1192 llvm::APSInt *NextElementIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +00001193 unsigned &Index,
1194 InitListExpr *StructuredList,
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001195 unsigned &StructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001196 bool FinishSubobjectInit,
1197 bool TopLevelObject) {
Douglas Gregoraa357272009-04-15 04:56:10 +00001198 if (DesigIdx == DIE->size()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001199 // Check the actual initialization for the designated object type.
1200 bool prevHadError = hadError;
Douglas Gregor36859eb2009-01-29 00:39:20 +00001201
1202 // Temporarily remove the designator expression from the
1203 // initializer list that the child calls see, so that we don't try
1204 // to re-process the designator.
1205 unsigned OldIndex = Index;
1206 IList->setInit(OldIndex, DIE->getInit());
1207
1208 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001209 StructuredList, StructuredIndex);
Douglas Gregor36859eb2009-01-29 00:39:20 +00001210
1211 // Restore the designated initializer expression in the syntactic
1212 // form of the initializer list.
1213 if (IList->getInit(OldIndex) != DIE->getInit())
1214 DIE->setInit(IList->getInit(OldIndex));
1215 IList->setInit(OldIndex, DIE);
1216
Douglas Gregor710f6d42009-01-22 23:26:18 +00001217 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001218 }
1219
Douglas Gregoraa357272009-04-15 04:56:10 +00001220 bool IsFirstDesignator = (DesigIdx == 0);
Douglas Gregorf603b472009-01-28 21:54:33 +00001221 assert((IsFirstDesignator || StructuredList) &&
1222 "Need a non-designated initializer list to start from");
1223
Douglas Gregoraa357272009-04-15 04:56:10 +00001224 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregorf603b472009-01-28 21:54:33 +00001225 // Determine the structural initializer list that corresponds to the
1226 // current subobject.
1227 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Douglas Gregorea765e12009-03-01 17:12:46 +00001228 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1229 StructuredList, StructuredIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +00001230 SourceRange(D->getStartLocation(),
1231 DIE->getSourceRange().getEnd()));
1232 assert(StructuredList && "Expected a structured initializer list");
1233
Douglas Gregor710f6d42009-01-22 23:26:18 +00001234 if (D->isFieldDesignator()) {
1235 // C99 6.7.8p7:
1236 //
1237 // If a designator has the form
1238 //
1239 // . identifier
1240 //
1241 // then the current object (defined below) shall have
1242 // structure or union type and the identifier shall be the
1243 // name of a member of that type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001244 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001245 if (!RT) {
1246 SourceLocation Loc = D->getDotLoc();
1247 if (Loc.isInvalid())
1248 Loc = D->getFieldLoc();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001249 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1250 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001251 ++Index;
1252 return true;
1253 }
1254
Douglas Gregorf603b472009-01-28 21:54:33 +00001255 // Note: we perform a linear search of the fields here, despite
1256 // the fact that we have a faster lookup method, because we always
1257 // need to compute the field's index.
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001258 FieldDecl *KnownField = D->getField();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001259 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregorf603b472009-01-28 21:54:33 +00001260 unsigned FieldIndex = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001261 RecordDecl::field_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001262 Field = RT->getDecl()->field_begin(),
1263 FieldEnd = RT->getDecl()->field_end();
Douglas Gregorf603b472009-01-28 21:54:33 +00001264 for (; Field != FieldEnd; ++Field) {
1265 if (Field->isUnnamedBitfield())
1266 continue;
1267
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001268 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregorf603b472009-01-28 21:54:33 +00001269 break;
1270
1271 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001272 }
1273
Douglas Gregorf603b472009-01-28 21:54:33 +00001274 if (Field == FieldEnd) {
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001275 // There was no normal field in the struct with the designated
1276 // name. Perform another lookup for this name, which may find
1277 // something that we can't designate (e.g., a member function),
1278 // may find nothing, or may find a member of an anonymous
1279 // struct/union.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001280 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorf603b472009-01-28 21:54:33 +00001281 if (Lookup.first == Lookup.second) {
1282 // Name lookup didn't find anything.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001283 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregorf603b472009-01-28 21:54:33 +00001284 << FieldName << CurrentObjectType;
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001285 ++Index;
1286 return true;
1287 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1288 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1289 ->isAnonymousStructOrUnion()) {
1290 // Handle an field designator that refers to a member of an
1291 // anonymous struct or union.
1292 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1293 cast<FieldDecl>(*Lookup.first),
1294 Field, FieldIndex);
Eli Friedmanbd45b552009-04-16 17:49:48 +00001295 D = DIE->getDesignator(DesigIdx);
Douglas Gregorf603b472009-01-28 21:54:33 +00001296 } else {
1297 // Name lookup found something, but it wasn't a field.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001298 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregorf603b472009-01-28 21:54:33 +00001299 << FieldName;
Chris Lattner2e2766a2009-02-24 22:50:46 +00001300 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001301 diag::note_field_designator_found);
Eli Friedmanbd45b552009-04-16 17:49:48 +00001302 ++Index;
1303 return true;
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001304 }
1305 } else if (!KnownField &&
1306 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregorf603b472009-01-28 21:54:33 +00001307 ->isAnonymousStructOrUnion()) {
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001308 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1309 Field, FieldIndex);
1310 D = DIE->getDesignator(DesigIdx);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001311 }
Douglas Gregorf603b472009-01-28 21:54:33 +00001312
1313 // All of the fields of a union are located at the same place in
1314 // the initializer list.
Douglas Gregor82462762009-01-29 16:53:55 +00001315 if (RT->getDecl()->isUnion()) {
Douglas Gregorf603b472009-01-28 21:54:33 +00001316 FieldIndex = 0;
Douglas Gregor82462762009-01-29 16:53:55 +00001317 StructuredList->setInitializedFieldInUnion(*Field);
1318 }
Douglas Gregorf603b472009-01-28 21:54:33 +00001319
Douglas Gregor710f6d42009-01-22 23:26:18 +00001320 // Update the designator with the field declaration.
Douglas Gregorf603b472009-01-28 21:54:33 +00001321 D->setField(*Field);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001322
Douglas Gregorf603b472009-01-28 21:54:33 +00001323 // Make sure that our non-designated initializer list has space
1324 // for a subobject corresponding to this field.
1325 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner2e2766a2009-02-24 22:50:46 +00001326 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +00001327
Douglas Gregorbe69b162009-02-04 22:46:25 +00001328 // This designator names a flexible array member.
1329 if (Field->getType()->isIncompleteArrayType()) {
1330 bool Invalid = false;
Douglas Gregoraa357272009-04-15 04:56:10 +00001331 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorbe69b162009-02-04 22:46:25 +00001332 // We can't designate an object within the flexible array
1333 // member (because GCC doesn't allow it).
Douglas Gregoraa357272009-04-15 04:56:10 +00001334 DesignatedInitExpr::Designator *NextD
1335 = DIE->getDesignator(DesigIdx + 1);
Chris Lattner2e2766a2009-02-24 22:50:46 +00001336 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001337 diag::err_designator_into_flexible_array_member)
1338 << SourceRange(NextD->getStartLocation(),
1339 DIE->getSourceRange().getEnd());
Chris Lattner2e2766a2009-02-24 22:50:46 +00001340 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001341 << *Field;
1342 Invalid = true;
1343 }
1344
1345 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1346 // The initializer is not an initializer list.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001347 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001348 diag::err_flexible_array_init_needs_braces)
1349 << DIE->getInit()->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001350 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001351 << *Field;
1352 Invalid = true;
1353 }
1354
1355 // Handle GNU flexible array initializers.
1356 if (!Invalid && !TopLevelObject &&
1357 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001358 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001359 diag::err_flexible_array_init_nonempty)
1360 << DIE->getSourceRange().getBegin();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001361 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001362 << *Field;
1363 Invalid = true;
1364 }
1365
1366 if (Invalid) {
1367 ++Index;
1368 return true;
1369 }
1370
1371 // Initialize the array.
1372 bool prevHadError = hadError;
1373 unsigned newStructuredIndex = FieldIndex;
1374 unsigned OldIndex = Index;
1375 IList->setInit(Index, DIE->getInit());
1376 CheckSubElementType(IList, Field->getType(), Index,
1377 StructuredList, newStructuredIndex);
1378 IList->setInit(OldIndex, DIE);
1379 if (hadError && !prevHadError) {
1380 ++Field;
1381 ++FieldIndex;
1382 if (NextField)
1383 *NextField = Field;
1384 StructuredIndex = FieldIndex;
1385 return true;
1386 }
1387 } else {
1388 // Recurse to check later designated subobjects.
1389 QualType FieldType = (*Field)->getType();
1390 unsigned newStructuredIndex = FieldIndex;
Douglas Gregoraa357272009-04-15 04:56:10 +00001391 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1392 Index, StructuredList, newStructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001393 true, false))
1394 return true;
1395 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001396
1397 // Find the position of the next field to be initialized in this
1398 // subobject.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001399 ++Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001400 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001401
1402 // If this the first designator, our caller will continue checking
1403 // the rest of this struct/class/union subobject.
1404 if (IsFirstDesignator) {
1405 if (NextField)
1406 *NextField = Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001407 StructuredIndex = FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001408 return false;
1409 }
1410
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001411 if (!FinishSubobjectInit)
1412 return false;
1413
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001414 // We've already initialized something in the union; we're done.
1415 if (RT->getDecl()->isUnion())
1416 return hadError;
1417
Douglas Gregor710f6d42009-01-22 23:26:18 +00001418 // Check the remaining fields within this class/struct/union subobject.
1419 bool prevHadError = hadError;
Douglas Gregorf603b472009-01-28 21:54:33 +00001420 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1421 StructuredList, FieldIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001422 return hadError && !prevHadError;
1423 }
1424
1425 // C99 6.7.8p6:
1426 //
1427 // If a designator has the form
1428 //
1429 // [ constant-expression ]
1430 //
1431 // then the current object (defined below) shall have array
1432 // type and the expression shall be an integer constant
1433 // expression. If the array is of unknown size, any
1434 // nonnegative value is valid.
1435 //
1436 // Additionally, cope with the GNU extension that permits
1437 // designators of the form
1438 //
1439 // [ constant-expression ... constant-expression ]
Chris Lattner2e2766a2009-02-24 22:50:46 +00001440 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001441 if (!AT) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001442 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor710f6d42009-01-22 23:26:18 +00001443 << CurrentObjectType;
1444 ++Index;
1445 return true;
1446 }
1447
1448 Expr *IndexExpr = 0;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001449 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1450 if (D->isArrayDesignator()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001451 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnereec8ae22009-04-25 21:59:05 +00001452 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001453 DesignatedEndIndex = DesignatedStartIndex;
1454 } else {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001455 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001456
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001457
Chris Lattnereec8ae22009-04-25 21:59:05 +00001458 DesignatedStartIndex =
1459 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
1460 DesignatedEndIndex =
1461 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001462 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001463
Chris Lattnereec8ae22009-04-25 21:59:05 +00001464 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregor9fddded2009-01-29 19:42:23 +00001465 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001466 }
1467
Douglas Gregor710f6d42009-01-22 23:26:18 +00001468 if (isa<ConstantArrayType>(AT)) {
1469 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001470 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1471 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1472 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1473 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1474 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001475 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor710f6d42009-01-22 23:26:18 +00001476 diag::err_array_designator_too_large)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001477 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor710f6d42009-01-22 23:26:18 +00001478 << IndexExpr->getSourceRange();
1479 ++Index;
1480 return true;
1481 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001482 } else {
1483 // Make sure the bit-widths and signedness match.
1484 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1485 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnereec8ae22009-04-25 21:59:05 +00001486 else if (DesignatedStartIndex.getBitWidth() <
1487 DesignatedEndIndex.getBitWidth())
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001488 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1489 DesignatedStartIndex.setIsUnsigned(true);
1490 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001491 }
1492
Douglas Gregorf603b472009-01-28 21:54:33 +00001493 // Make sure that our non-designated initializer list has space
1494 // for a subobject corresponding to this array element.
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001495 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Chris Lattner2e2766a2009-02-24 22:50:46 +00001496 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001497 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +00001498
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001499 // Repeatedly perform subobject initializations in the range
1500 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor710f6d42009-01-22 23:26:18 +00001501
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001502 // Move to the next designator
1503 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1504 unsigned OldIndex = Index;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001505 while (DesignatedStartIndex <= DesignatedEndIndex) {
1506 // Recurse to check later designated subobjects.
1507 QualType ElementType = AT->getElementType();
1508 Index = OldIndex;
Douglas Gregoraa357272009-04-15 04:56:10 +00001509 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1510 Index, StructuredList, ElementIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001511 (DesignatedStartIndex == DesignatedEndIndex),
1512 false))
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001513 return true;
1514
1515 // Move to the next index in the array that we'll be initializing.
1516 ++DesignatedStartIndex;
1517 ElementIndex = DesignatedStartIndex.getZExtValue();
1518 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001519
1520 // If this the first designator, our caller will continue checking
1521 // the rest of this array subobject.
1522 if (IsFirstDesignator) {
1523 if (NextElementIndex)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001524 *NextElementIndex = DesignatedStartIndex;
Douglas Gregorf603b472009-01-28 21:54:33 +00001525 StructuredIndex = ElementIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001526 return false;
1527 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001528
1529 if (!FinishSubobjectInit)
1530 return false;
1531
Douglas Gregor710f6d42009-01-22 23:26:18 +00001532 // Check the remaining elements within this array subobject.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001533 bool prevHadError = hadError;
Douglas Gregord7e76c52009-02-09 19:45:19 +00001534 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001535 StructuredList, ElementIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001536 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001537}
1538
Douglas Gregorf603b472009-01-28 21:54:33 +00001539// Get the structured initializer list for a subobject of type
1540// @p CurrentObjectType.
1541InitListExpr *
1542InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1543 QualType CurrentObjectType,
1544 InitListExpr *StructuredList,
1545 unsigned StructuredIndex,
1546 SourceRange InitRange) {
1547 Expr *ExistingInit = 0;
1548 if (!StructuredList)
1549 ExistingInit = SyntacticToSemantic[IList];
1550 else if (StructuredIndex < StructuredList->getNumInits())
1551 ExistingInit = StructuredList->getInit(StructuredIndex);
1552
1553 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1554 return Result;
1555
1556 if (ExistingInit) {
1557 // We are creating an initializer list that initializes the
1558 // subobjects of the current object, but there was already an
1559 // initialization that completely initialized the current
1560 // subobject, e.g., by a compound literal:
1561 //
1562 // struct X { int a, b; };
1563 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1564 //
1565 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1566 // designated initializer re-initializes the whole
1567 // subobject [0], overwriting previous initializers.
Douglas Gregorea765e12009-03-01 17:12:46 +00001568 SemaRef.Diag(InitRange.getBegin(),
1569 diag::warn_subobject_initializer_overrides)
Douglas Gregorf603b472009-01-28 21:54:33 +00001570 << InitRange;
Chris Lattner2e2766a2009-02-24 22:50:46 +00001571 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001572 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001573 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001574 << ExistingInit->getSourceRange();
1575 }
1576
1577 InitListExpr *Result
Douglas Gregorea765e12009-03-01 17:12:46 +00001578 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
1579 InitRange.getEnd());
1580
Douglas Gregorf603b472009-01-28 21:54:33 +00001581 Result->setType(CurrentObjectType);
1582
Douglas Gregoree0792c2009-03-20 23:58:33 +00001583 // Pre-allocate storage for the structured initializer list.
1584 unsigned NumElements = 0;
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001585 unsigned NumInits = 0;
1586 if (!StructuredList)
1587 NumInits = IList->getNumInits();
1588 else if (Index < IList->getNumInits()) {
1589 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1590 NumInits = SubList->getNumInits();
1591 }
1592
Douglas Gregoree0792c2009-03-20 23:58:33 +00001593 if (const ArrayType *AType
1594 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1595 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1596 NumElements = CAType->getSize().getZExtValue();
1597 // Simple heuristic so that we don't allocate a very large
1598 // initializer with many empty entries at the end.
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001599 if (NumInits && NumElements > NumInits)
Douglas Gregoree0792c2009-03-20 23:58:33 +00001600 NumElements = 0;
1601 }
1602 } else if (const VectorType *VType = CurrentObjectType->getAsVectorType())
1603 NumElements = VType->getNumElements();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001604 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregoree0792c2009-03-20 23:58:33 +00001605 RecordDecl *RDecl = RType->getDecl();
1606 if (RDecl->isUnion())
1607 NumElements = 1;
1608 else
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001609 NumElements = std::distance(RDecl->field_begin(),
1610 RDecl->field_end());
Douglas Gregoree0792c2009-03-20 23:58:33 +00001611 }
1612
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001613 if (NumElements < NumInits)
Douglas Gregoree0792c2009-03-20 23:58:33 +00001614 NumElements = IList->getNumInits();
1615
1616 Result->reserveInits(NumElements);
1617
Douglas Gregorf603b472009-01-28 21:54:33 +00001618 // Link this new initializer list into the structured initializer
1619 // lists.
1620 if (StructuredList)
1621 StructuredList->updateInit(StructuredIndex, Result);
1622 else {
1623 Result->setSyntacticForm(IList);
1624 SyntacticToSemantic[IList] = Result;
1625 }
1626
1627 return Result;
1628}
1629
1630/// Update the initializer at index @p StructuredIndex within the
1631/// structured initializer list to the value @p expr.
1632void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1633 unsigned &StructuredIndex,
1634 Expr *expr) {
1635 // No structured initializer list to update
1636 if (!StructuredList)
1637 return;
1638
1639 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1640 // This initializer overwrites a previous initializer. Warn.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001641 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001642 diag::warn_initializer_overrides)
1643 << expr->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001644 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001645 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001646 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001647 << PrevInit->getSourceRange();
1648 }
1649
1650 ++StructuredIndex;
1651}
1652
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001653/// Check that the given Index expression is a valid array designator
1654/// value. This is essentailly just a wrapper around
Chris Lattnereec8ae22009-04-25 21:59:05 +00001655/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001656/// and produces a reasonable diagnostic if there is a
1657/// failure. Returns true if there was an error, false otherwise. If
1658/// everything went okay, Value will receive the value of the constant
1659/// expression.
1660static bool
Chris Lattnereec8ae22009-04-25 21:59:05 +00001661CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001662 SourceLocation Loc = Index->getSourceRange().getBegin();
1663
1664 // Make sure this is an integer constant expression.
Chris Lattnereec8ae22009-04-25 21:59:05 +00001665 if (S.VerifyIntegerConstantExpression(Index, &Value))
1666 return true;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001667
Chris Lattnereec8ae22009-04-25 21:59:05 +00001668 if (Value.isSigned() && Value.isNegative())
1669 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001670 << Value.toString(10) << Index->getSourceRange();
1671
Douglas Gregore498e372009-01-23 21:04:18 +00001672 Value.setIsUnsigned(true);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001673 return false;
1674}
1675
1676Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1677 SourceLocation Loc,
Douglas Gregor5f34f0e2009-03-28 00:41:23 +00001678 bool GNUSyntax,
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001679 OwningExprResult Init) {
1680 typedef DesignatedInitExpr::Designator ASTDesignator;
1681
1682 bool Invalid = false;
1683 llvm::SmallVector<ASTDesignator, 32> Designators;
1684 llvm::SmallVector<Expr *, 32> InitExpressions;
1685
1686 // Build designators and check array designator expressions.
1687 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1688 const Designator &D = Desig.getDesignator(Idx);
1689 switch (D.getKind()) {
1690 case Designator::FieldDesignator:
1691 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1692 D.getFieldLoc()));
1693 break;
1694
1695 case Designator::ArrayDesignator: {
1696 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1697 llvm::APSInt IndexValue;
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001698 if (!Index->isTypeDependent() &&
1699 !Index->isValueDependent() &&
1700 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001701 Invalid = true;
1702 else {
1703 Designators.push_back(ASTDesignator(InitExpressions.size(),
1704 D.getLBracketLoc(),
1705 D.getRBracketLoc()));
1706 InitExpressions.push_back(Index);
1707 }
1708 break;
1709 }
1710
1711 case Designator::ArrayRangeDesignator: {
1712 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1713 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1714 llvm::APSInt StartValue;
1715 llvm::APSInt EndValue;
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001716 bool StartDependent = StartIndex->isTypeDependent() ||
1717 StartIndex->isValueDependent();
1718 bool EndDependent = EndIndex->isTypeDependent() ||
1719 EndIndex->isValueDependent();
1720 if ((!StartDependent &&
1721 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1722 (!EndDependent &&
1723 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001724 Invalid = true;
Douglas Gregorea0528d2009-01-23 22:22:29 +00001725 else {
1726 // Make sure we're comparing values with the same bit width.
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001727 if (StartDependent || EndDependent) {
1728 // Nothing to compute.
1729 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregorea0528d2009-01-23 22:22:29 +00001730 EndValue.extend(StartValue.getBitWidth());
1731 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1732 StartValue.extend(EndValue.getBitWidth());
1733
Douglas Gregor1401c062009-05-21 23:30:39 +00001734 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregorea0528d2009-01-23 22:22:29 +00001735 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1736 << StartValue.toString(10) << EndValue.toString(10)
1737 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1738 Invalid = true;
1739 } else {
1740 Designators.push_back(ASTDesignator(InitExpressions.size(),
1741 D.getLBracketLoc(),
1742 D.getEllipsisLoc(),
1743 D.getRBracketLoc()));
1744 InitExpressions.push_back(StartIndex);
1745 InitExpressions.push_back(EndIndex);
1746 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001747 }
1748 break;
1749 }
1750 }
1751 }
1752
1753 if (Invalid || Init.isInvalid())
1754 return ExprError();
1755
1756 // Clear out the expressions within the designation.
1757 Desig.ClearExprs(*this);
1758
1759 DesignatedInitExpr *DIE
Jay Foad9e6bef42009-05-21 09:52:38 +00001760 = DesignatedInitExpr::Create(Context,
1761 Designators.data(), Designators.size(),
1762 InitExpressions.data(), InitExpressions.size(),
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001763 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001764 return Owned(DIE);
1765}
Douglas Gregor849afc32009-01-29 00:45:39 +00001766
1767bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001768 InitListChecker CheckInitList(*this, InitList, DeclType);
Douglas Gregor849afc32009-01-29 00:45:39 +00001769 if (!CheckInitList.HadError())
1770 InitList = CheckInitList.getFullyStructuredList();
1771
1772 return CheckInitList.HadError();
1773}
Douglas Gregor538a4c22009-02-02 17:43:21 +00001774
1775/// \brief Diagnose any semantic errors with value-initialization of
1776/// the given type.
1777///
1778/// Value-initialization effectively zero-initializes any types
1779/// without user-declared constructors, and calls the default
1780/// constructor for a for any type that has a user-declared
1781/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1782/// a type with a user-declared constructor does not have an
1783/// accessible, non-deleted default constructor. In C, everything can
1784/// be value-initialized, which corresponds to C's notion of
1785/// initializing objects with static storage duration when no
1786/// initializer is provided for that object.
1787///
1788/// \returns true if there was an error, false otherwise.
1789bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1790 // C++ [dcl.init]p5:
1791 //
1792 // To value-initialize an object of type T means:
1793
1794 // -- if T is an array type, then each element is value-initialized;
1795 if (const ArrayType *AT = Context.getAsArrayType(Type))
1796 return CheckValueInitialization(AT->getElementType(), Loc);
1797
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001798 if (const RecordType *RT = Type->getAs<RecordType>()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001799 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Douglas Gregor538a4c22009-02-02 17:43:21 +00001800 // -- if T is a class type (clause 9) with a user-declared
1801 // constructor (12.1), then the default constructor for T is
1802 // called (and the initialization is ill-formed if T has no
1803 // accessible default constructor);
Douglas Gregor2e047592009-02-28 01:32:25 +00001804 if (ClassDecl->hasUserDeclaredConstructor())
Mike Stumpe127ae32009-05-16 07:39:55 +00001805 // FIXME: Eventually, we'll need to put the constructor decl into the
1806 // AST.
Douglas Gregor538a4c22009-02-02 17:43:21 +00001807 return PerformInitializationByConstructor(Type, 0, 0, Loc,
1808 SourceRange(Loc),
1809 DeclarationName(),
1810 IK_Direct);
1811 }
1812 }
1813
1814 if (Type->isReferenceType()) {
1815 // C++ [dcl.init]p5:
1816 // [...] A program that calls for default-initialization or
1817 // value-initialization of an entity of reference type is
1818 // ill-formed. [...]
Mike Stumpe127ae32009-05-16 07:39:55 +00001819 // FIXME: Once we have code that goes through this path, add an actual
1820 // diagnostic :)
Douglas Gregor538a4c22009-02-02 17:43:21 +00001821 }
1822
1823 return false;
1824}