blob: 5dc40a4593445996bf47976c6d23520e402afeec [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
34 // See if this is a string literal or @encode.
35 Init = Init->IgnoreParens();
36
37 // Handle @encode, which is a narrow string.
38 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
39 return Init;
40
41 // Otherwise we can only handle string literals.
42 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattnerff065f72009-02-26 23:42:47 +000043 if (SL == 0) return 0;
Chris Lattner7a7c1452009-02-26 23:26:43 +000044
45 // char array can be initialized with a narrow string.
46 // Only allow char x[] = "foo"; not char x[] = L"foo";
47 if (!SL->isWide())
48 return AT->getElementType()->isCharType() ? Init : 0;
49
50 // wchar_t array can be initialized with a wide string: C99 6.7.8p15:
51 // "An array with element type compatible with wchar_t may be initialized by a
52 // wide string literal, optionally enclosed in braces."
Chris Lattnerb1fe0472009-02-26 23:36:02 +000053 if (Context.typesAreCompatible(Context.getWCharType(), AT->getElementType()))
Chris Lattner7a7c1452009-02-26 23:26:43 +000054 // Only allow wchar_t x[] = L"foo"; not wchar_t x[] = "foo";
55 return Init;
56
Chris Lattnerd3a00502009-02-24 22:27:37 +000057 return 0;
58}
59
Chris Lattner160da072009-02-24 22:46:58 +000060static bool CheckSingleInitializer(Expr *&Init, QualType DeclType,
61 bool DirectInit, Sema &S) {
Chris Lattnerd3a00502009-02-24 22:27:37 +000062 // Get the type before calling CheckSingleAssignmentConstraints(), since
63 // it can promote the expression.
64 QualType InitType = Init->getType();
65
Chris Lattner160da072009-02-24 22:46:58 +000066 if (S.getLangOptions().CPlusPlus) {
Chris Lattnerd3a00502009-02-24 22:27:37 +000067 // FIXME: I dislike this error message. A lot.
Chris Lattner160da072009-02-24 22:46:58 +000068 if (S.PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
69 return S.Diag(Init->getSourceRange().getBegin(),
70 diag::err_typecheck_convert_incompatible)
71 << DeclType << Init->getType() << "initializing"
72 << Init->getSourceRange();
Chris Lattnerd3a00502009-02-24 22:27:37 +000073 return false;
74 }
75
Chris Lattner160da072009-02-24 22:46:58 +000076 Sema::AssignConvertType ConvTy =
77 S.CheckSingleAssignmentConstraints(DeclType, Init);
78 return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
Chris Lattnerd3a00502009-02-24 22:27:37 +000079 InitType, Init, "initializing");
80}
81
Chris Lattner19ae2fc2009-02-24 23:10:27 +000082static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
83 // Get the length of the string as parsed.
84 uint64_t StrLength =
85 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
86
Chris Lattnerd3a00502009-02-24 22:27:37 +000087
Chris Lattner19ae2fc2009-02-24 23:10:27 +000088 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerd3a00502009-02-24 22:27:37 +000089 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
90 // C99 6.7.8p14. We have an array of character type with unknown size
91 // being initialized to a string literal.
92 llvm::APSInt ConstVal(32);
Chris Lattnerd20fac42009-02-24 23:01:39 +000093 ConstVal = StrLength;
Chris Lattnerd3a00502009-02-24 22:27:37 +000094 // Return a new array type (C99 6.7.8p22).
Chris Lattner45d6fd62009-02-24 22:41:04 +000095 DeclT = S.Context.getConstantArrayType(IAT->getElementType(), ConstVal,
96 ArrayType::Normal, 0);
Chris Lattnerd20fac42009-02-24 23:01:39 +000097 return;
Chris Lattnerd3a00502009-02-24 22:27:37 +000098 }
Chris Lattnerd20fac42009-02-24 23:01:39 +000099
100 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
101
102 // C99 6.7.8p14. We have an array of character type with known size. However,
103 // the size may be smaller or larger than the string we are initializing.
104 // FIXME: Avoid truncation for 64-bit length strings.
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000105 if (StrLength-1 > CAT->getSize().getZExtValue())
Chris Lattnerd20fac42009-02-24 23:01:39 +0000106 S.Diag(Str->getSourceRange().getBegin(),
107 diag::warn_initializer_string_for_char_array_too_long)
108 << Str->getSourceRange();
109
110 // Set the type to the actual size that we are initializing. If we have
111 // something like:
112 // char x[1] = "foo";
113 // then this will set the string literal's type to char[1].
Chris Lattner45d6fd62009-02-24 22:41:04 +0000114 Str->setType(DeclT);
Chris Lattnerd3a00502009-02-24 22:27:37 +0000115}
116
117bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
118 SourceLocation InitLoc,
119 DeclarationName InitEntity,
Anders Carlsson73bb5e62009-05-27 16:10:08 +0000120 bool DirectInit, VarDecl *VD) {
Douglas Gregor3a7a06e2009-05-21 23:17:49 +0000121 if (DeclType->isDependentType() ||
122 Init->isTypeDependent() || Init->isValueDependent())
Chris Lattnerd3a00502009-02-24 22:27:37 +0000123 return false;
124
125 // C++ [dcl.init.ref]p1:
Sebastian Redlce6fff02009-03-16 23:22:08 +0000126 // A variable declared to be a T& or T&&, that is "reference to type T"
Chris Lattnerd3a00502009-02-24 22:27:37 +0000127 // (8.3.2), shall be initialized by an object, or function, of
128 // type T or by an object that can be converted into a T.
129 if (DeclType->isReferenceType())
130 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
131
132 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
133 // of unknown size ("[]") or an object type that is not a variable array type.
134 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
135 return Diag(InitLoc, diag::err_variable_object_no_init)
136 << VAT->getSizeExpr()->getSourceRange();
137
138 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
139 if (!InitList) {
140 // FIXME: Handle wide strings
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000141 if (Expr *Str = IsStringInit(Init, DeclType, Context)) {
142 CheckStringInit(Str, DeclType, *this);
Chris Lattnerd20fac42009-02-24 23:01:39 +0000143 return false;
144 }
Chris Lattnerd3a00502009-02-24 22:27:37 +0000145
146 // C++ [dcl.init]p14:
147 // -- If the destination type is a (possibly cv-qualified) class
148 // type:
149 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
150 QualType DeclTypeC = Context.getCanonicalType(DeclType);
151 QualType InitTypeC = Context.getCanonicalType(Init->getType());
152
153 // -- If the initialization is direct-initialization, or if it is
154 // copy-initialization where the cv-unqualified version of the
155 // source type is the same class as, or a derived class of, the
156 // class of the destination, constructors are considered.
157 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
158 IsDerivedFrom(InitTypeC, DeclTypeC)) {
Anders Carlsson5868dfc2009-05-27 16:38:58 +0000159 const CXXRecordDecl *RD =
160 cast<CXXRecordDecl>(DeclType->getAsRecordType()->getDecl());
161
162 // No need to make a CXXConstructExpr if both the ctor and dtor are
163 // trivial.
164 if (RD->hasTrivialConstructor() && RD->hasTrivialDestructor())
165 return false;
166
Chris Lattnerd3a00502009-02-24 22:27:37 +0000167 CXXConstructorDecl *Constructor
168 = PerformInitializationByConstructor(DeclType, &Init, 1,
169 InitLoc, Init->getSourceRange(),
170 InitEntity,
171 DirectInit? IK_Direct : IK_Copy);
Anders Carlsson73bb5e62009-05-27 16:10:08 +0000172 if (!Constructor)
173 return true;
174
175 // FIXME: What do do if VD is null here?
Anders Carlsson6b0e7972009-05-27 16:28:34 +0000176 if (VD)
177 Init = CXXConstructExpr::Create(Context, VD, DeclType, Constructor,
178 false, &Init, 1);
Anders Carlsson73bb5e62009-05-27 16:10:08 +0000179 return false;
Chris Lattnerd3a00502009-02-24 22:27:37 +0000180 }
181
182 // -- Otherwise (i.e., for the remaining copy-initialization
183 // cases), user-defined conversion sequences that can
184 // convert from the source type to the destination type or
185 // (when a conversion function is used) to a derived class
186 // thereof are enumerated as described in 13.3.1.4, and the
187 // best one is chosen through overload resolution
188 // (13.3). If the conversion cannot be done or is
189 // ambiguous, the initialization is ill-formed. The
190 // function selected is called with the initializer
191 // expression as its argument; if the function is a
192 // constructor, the call initializes a temporary of the
193 // destination type.
Mike Stumpe127ae32009-05-16 07:39:55 +0000194 // FIXME: We're pretending to do copy elision here; return to this when we
195 // have ASTs for such things.
Chris Lattnerd3a00502009-02-24 22:27:37 +0000196 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
197 return false;
198
199 if (InitEntity)
200 return Diag(InitLoc, diag::err_cannot_initialize_decl)
201 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
202 << Init->getType() << Init->getSourceRange();
203 else
204 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
205 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
206 << Init->getType() << Init->getSourceRange();
207 }
208
209 // C99 6.7.8p16.
210 if (DeclType->isArrayType())
211 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
212 << Init->getSourceRange();
213
Chris Lattner160da072009-02-24 22:46:58 +0000214 return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
Chris Lattnerd3a00502009-02-24 22:27:37 +0000215 }
216
217 bool hadError = CheckInitList(InitList, DeclType);
218 Init = InitList;
219 return hadError;
220}
221
222//===----------------------------------------------------------------------===//
223// Semantic checking for initializer lists.
224//===----------------------------------------------------------------------===//
225
Douglas Gregoraaa20962009-01-29 01:05:33 +0000226/// @brief Semantic checking for initializer lists.
227///
228/// The InitListChecker class contains a set of routines that each
229/// handle the initialization of a certain kind of entity, e.g.,
230/// arrays, vectors, struct/union types, scalars, etc. The
231/// InitListChecker itself performs a recursive walk of the subobject
232/// structure of the type to be initialized, while stepping through
233/// the initializer list one element at a time. The IList and Index
234/// parameters to each of the Check* routines contain the active
235/// (syntactic) initializer list and the index into that initializer
236/// list that represents the current initializer. Each routine is
237/// responsible for moving that Index forward as it consumes elements.
238///
239/// Each Check* routine also has a StructuredList/StructuredIndex
240/// arguments, which contains the current the "structured" (semantic)
241/// initializer list and the index into that initializer list where we
242/// are copying initializers as we map them over to the semantic
243/// list. Once we have completed our recursive walk of the subobject
244/// structure, we will have constructed a full semantic initializer
245/// list.
246///
247/// C99 designators cause changes in the initializer list traversal,
248/// because they make the initialization "jump" into a specific
249/// subobject and then continue the initialization from that
250/// point. CheckDesignatedInitializer() recursively steps into the
251/// designated subobject and manages backing out the recursion to
252/// initialize the subobjects after the one designated.
Chris Lattnere76e9bf2009-02-24 22:48:58 +0000253namespace {
Douglas Gregor849afc32009-01-29 00:45:39 +0000254class InitListChecker {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000255 Sema &SemaRef;
Douglas Gregor849afc32009-01-29 00:45:39 +0000256 bool hadError;
257 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
258 InitListExpr *FullyStructuredList;
259
260 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000261 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000262 unsigned &StructuredIndex,
263 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000264 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000265 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000266 unsigned &StructuredIndex,
267 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000268 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
269 bool SubobjectIsDesignatorContext,
270 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000271 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 CheckSubElementType(InitListExpr *IList, QualType ElemType,
275 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000276 InitListExpr *StructuredList,
277 unsigned &StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000278 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor849afc32009-01-29 00:45:39 +0000279 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000280 InitListExpr *StructuredList,
281 unsigned &StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000282 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
283 unsigned &Index,
284 InitListExpr *StructuredList,
285 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000286 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000287 InitListExpr *StructuredList,
288 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000289 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
290 RecordDecl::field_iterator Field,
291 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000292 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000293 unsigned &StructuredIndex,
294 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000295 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
296 llvm::APSInt elementIndex,
297 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000298 InitListExpr *StructuredList,
299 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000300 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregoraa357272009-04-15 04:56:10 +0000301 unsigned DesigIdx,
Douglas Gregor849afc32009-01-29 00:45:39 +0000302 QualType &CurrentObjectType,
303 RecordDecl::field_iterator *NextField,
304 llvm::APSInt *NextElementIndex,
305 unsigned &Index,
306 InitListExpr *StructuredList,
307 unsigned &StructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000308 bool FinishSubobjectInit,
309 bool TopLevelObject);
Douglas Gregor849afc32009-01-29 00:45:39 +0000310 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
311 QualType CurrentObjectType,
312 InitListExpr *StructuredList,
313 unsigned StructuredIndex,
314 SourceRange InitRange);
Douglas Gregoraaa20962009-01-29 01:05:33 +0000315 void UpdateStructuredListElement(InitListExpr *StructuredList,
316 unsigned &StructuredIndex,
Douglas Gregor849afc32009-01-29 00:45:39 +0000317 Expr *expr);
318 int numArrayElements(QualType DeclType);
319 int numStructUnionElements(QualType DeclType);
Douglas Gregord45210d2009-01-30 22:09:00 +0000320
321 void FillInValueInitializations(InitListExpr *ILE);
Douglas Gregor849afc32009-01-29 00:45:39 +0000322public:
Chris Lattner2e2766a2009-02-24 22:50:46 +0000323 InitListChecker(Sema &S, InitListExpr *IL, QualType &T);
Douglas Gregor849afc32009-01-29 00:45:39 +0000324 bool HadError() { return hadError; }
325
326 // @brief Retrieves the fully-structured initializer list used for
327 // semantic analysis and code generation.
328 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
329};
Chris Lattnere76e9bf2009-02-24 22:48:58 +0000330} // end anonymous namespace
Chris Lattner1aa25a72009-01-29 05:10:57 +0000331
Douglas Gregorf603b472009-01-28 21:54:33 +0000332/// Recursively replaces NULL values within the given initializer list
333/// with expressions that perform value-initialization of the
334/// appropriate type.
Douglas Gregord45210d2009-01-30 22:09:00 +0000335void InitListChecker::FillInValueInitializations(InitListExpr *ILE) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000336 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord45210d2009-01-30 22:09:00 +0000337 "Should not have void type");
Douglas Gregor538a4c22009-02-02 17:43:21 +0000338 SourceLocation Loc = ILE->getSourceRange().getBegin();
339 if (ILE->getSyntacticForm())
340 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
341
Douglas Gregorf603b472009-01-28 21:54:33 +0000342 if (const RecordType *RType = ILE->getType()->getAsRecordType()) {
343 unsigned Init = 0, NumInits = ILE->getNumInits();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000344 for (RecordDecl::field_iterator
345 Field = RType->getDecl()->field_begin(SemaRef.Context),
346 FieldEnd = RType->getDecl()->field_end(SemaRef.Context);
Douglas Gregorf603b472009-01-28 21:54:33 +0000347 Field != FieldEnd; ++Field) {
348 if (Field->isUnnamedBitfield())
349 continue;
350
Douglas Gregor538a4c22009-02-02 17:43:21 +0000351 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000352 if (Field->getType()->isReferenceType()) {
353 // C++ [dcl.init.aggr]p9:
354 // If an incomplete or empty initializer-list leaves a
355 // member of reference type uninitialized, the program is
356 // ill-formed.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000357 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregord45210d2009-01-30 22:09:00 +0000358 << Field->getType()
359 << ILE->getSyntacticForm()->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +0000360 SemaRef.Diag(Field->getLocation(),
Douglas Gregord45210d2009-01-30 22:09:00 +0000361 diag::note_uninit_reference_member);
362 hadError = true;
Douglas Gregor538a4c22009-02-02 17:43:21 +0000363 return;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000364 } else if (SemaRef.CheckValueInitialization(Field->getType(), Loc)) {
Douglas Gregor538a4c22009-02-02 17:43:21 +0000365 hadError = true;
366 return;
Douglas Gregord45210d2009-01-30 22:09:00 +0000367 }
Douglas Gregor538a4c22009-02-02 17:43:21 +0000368
Mike Stumpe127ae32009-05-16 07:39:55 +0000369 // FIXME: If value-initialization involves calling a constructor, should
370 // we make that call explicit in the representation (even when it means
371 // extending the initializer list)?
Douglas Gregor538a4c22009-02-02 17:43:21 +0000372 if (Init < NumInits && !hadError)
373 ILE->setInit(Init,
Chris Lattner2e2766a2009-02-24 22:50:46 +0000374 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()));
Douglas Gregor538a4c22009-02-02 17:43:21 +0000375 } else if (InitListExpr *InnerILE
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000376 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregord45210d2009-01-30 22:09:00 +0000377 FillInValueInitializations(InnerILE);
Douglas Gregorf603b472009-01-28 21:54:33 +0000378 ++Init;
Douglas Gregord45210d2009-01-30 22:09:00 +0000379
380 // Only look at the first initialization of a union.
381 if (RType->getDecl()->isUnion())
382 break;
Douglas Gregorf603b472009-01-28 21:54:33 +0000383 }
384
385 return;
386 }
387
388 QualType ElementType;
389
Douglas Gregor538a4c22009-02-02 17:43:21 +0000390 unsigned NumInits = ILE->getNumInits();
391 unsigned NumElements = NumInits;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000392 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000393 ElementType = AType->getElementType();
Douglas Gregor538a4c22009-02-02 17:43:21 +0000394 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
395 NumElements = CAType->getSize().getZExtValue();
396 } else if (const VectorType *VType = ILE->getType()->getAsVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000397 ElementType = VType->getElementType();
Douglas Gregor538a4c22009-02-02 17:43:21 +0000398 NumElements = VType->getNumElements();
399 } else
Douglas Gregorf603b472009-01-28 21:54:33 +0000400 ElementType = ILE->getType();
401
Douglas Gregor538a4c22009-02-02 17:43:21 +0000402 for (unsigned Init = 0; Init != NumElements; ++Init) {
403 if (Init >= NumInits || !ILE->getInit(Init)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000404 if (SemaRef.CheckValueInitialization(ElementType, Loc)) {
Douglas Gregor538a4c22009-02-02 17:43:21 +0000405 hadError = true;
406 return;
407 }
408
Mike Stumpe127ae32009-05-16 07:39:55 +0000409 // FIXME: If value-initialization involves calling a constructor, should
410 // we make that call explicit in the representation (even when it means
411 // extending the initializer list)?
Douglas Gregor538a4c22009-02-02 17:43:21 +0000412 if (Init < NumInits && !hadError)
413 ILE->setInit(Init,
Chris Lattner2e2766a2009-02-24 22:50:46 +0000414 new (SemaRef.Context) ImplicitValueInitExpr(ElementType));
Douglas Gregor538a4c22009-02-02 17:43:21 +0000415 }
Chris Lattner1aa25a72009-01-29 05:10:57 +0000416 else if (InitListExpr *InnerILE =dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregord45210d2009-01-30 22:09:00 +0000417 FillInValueInitializations(InnerILE);
Douglas Gregorf603b472009-01-28 21:54:33 +0000418 }
419}
420
Chris Lattner1aa25a72009-01-29 05:10:57 +0000421
Chris Lattner2e2766a2009-02-24 22:50:46 +0000422InitListChecker::InitListChecker(Sema &S, InitListExpr *IL, QualType &T)
423 : SemaRef(S) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000424 hadError = false;
Eli Friedmand8535af2008-05-19 20:00:43 +0000425
Eli Friedman683cedf2008-05-19 19:16:24 +0000426 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000427 unsigned newStructuredIndex = 0;
428 FullyStructuredList
Douglas Gregorea765e12009-03-01 17:12:46 +0000429 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregorbe69b162009-02-04 22:46:25 +0000430 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
431 /*TopLevelObject=*/true);
Eli Friedmand8535af2008-05-19 20:00:43 +0000432
Douglas Gregord45210d2009-01-30 22:09:00 +0000433 if (!hadError)
434 FillInValueInitializations(FullyStructuredList);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000435}
436
437int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman46f81662008-05-25 13:22:35 +0000438 // FIXME: use a proper constant
439 int maxElements = 0x7FFFFFFF;
Chris Lattnera1923f62008-08-04 07:31:14 +0000440 if (const ConstantArrayType *CAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000441 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000442 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
443 }
444 return maxElements;
445}
446
447int InitListChecker::numStructUnionElements(QualType DeclType) {
448 RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl();
Douglas Gregorf603b472009-01-28 21:54:33 +0000449 int InitializableMembers = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000450 for (RecordDecl::field_iterator
451 Field = structDecl->field_begin(SemaRef.Context),
452 FieldEnd = structDecl->field_end(SemaRef.Context);
Douglas Gregorf603b472009-01-28 21:54:33 +0000453 Field != FieldEnd; ++Field) {
454 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
455 ++InitializableMembers;
456 }
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000457 if (structDecl->isUnion())
Eli Friedman9f5250b2008-05-25 14:03:31 +0000458 return std::min(InitializableMembers, 1);
459 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000460}
461
462void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregorf603b472009-01-28 21:54:33 +0000463 QualType T, unsigned &Index,
464 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000465 unsigned &StructuredIndex,
466 bool TopLevelObject) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000467 int maxElements = 0;
468
469 if (T->isArrayType())
470 maxElements = numArrayElements(T);
471 else if (T->isStructureType() || T->isUnionType())
472 maxElements = numStructUnionElements(T);
Eli Friedman683cedf2008-05-19 19:16:24 +0000473 else if (T->isVectorType())
474 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000475 else
476 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman683cedf2008-05-19 19:16:24 +0000477
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000478 if (maxElements == 0) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000479 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000480 diag::err_implicit_empty_initializer);
Douglas Gregorf603b472009-01-28 21:54:33 +0000481 ++Index;
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000482 hadError = true;
483 return;
484 }
485
Douglas Gregorf603b472009-01-28 21:54:33 +0000486 // Build a structured initializer list corresponding to this subobject.
487 InitListExpr *StructuredSubobjectInitList
488 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
489 StructuredIndex,
Douglas Gregorea765e12009-03-01 17:12:46 +0000490 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
491 ParentIList->getSourceRange().getEnd()));
Douglas Gregorf603b472009-01-28 21:54:33 +0000492 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman683cedf2008-05-19 19:16:24 +0000493
Douglas Gregorf603b472009-01-28 21:54:33 +0000494 // Check the element types and build the structural subobject.
Douglas Gregor538a4c22009-02-02 17:43:21 +0000495 unsigned StartIndex = Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000496 CheckListElementTypes(ParentIList, T, false, Index,
497 StructuredSubobjectInitList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000498 StructuredSubobjectInitIndex,
499 TopLevelObject);
Douglas Gregor538a4c22009-02-02 17:43:21 +0000500 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregorcd2c5272009-03-20 00:32:56 +0000501 StructuredSubobjectInitList->setType(T);
502
Douglas Gregorea765e12009-03-01 17:12:46 +0000503 // Update the structured sub-object initializer so that it's ending
Douglas Gregor538a4c22009-02-02 17:43:21 +0000504 // range corresponds with the end of the last initializer it used.
505 if (EndIndex < ParentIList->getNumInits()) {
506 SourceLocation EndLoc
507 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
508 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
509 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000510}
511
Steve Naroff56099522008-05-06 00:23:44 +0000512void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregorf603b472009-01-28 21:54:33 +0000513 unsigned &Index,
514 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000515 unsigned &StructuredIndex,
516 bool TopLevelObject) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000517 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregorf603b472009-01-28 21:54:33 +0000518 SyntacticToSemantic[IList] = StructuredList;
519 StructuredList->setSyntacticForm(IList);
520 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000521 StructuredIndex, TopLevelObject);
Steve Naroff56099522008-05-06 00:23:44 +0000522 IList->setType(T);
Douglas Gregorf603b472009-01-28 21:54:33 +0000523 StructuredList->setType(T);
Eli Friedman46f81662008-05-25 13:22:35 +0000524 if (hadError)
525 return;
Eli Friedmand8535af2008-05-19 20:00:43 +0000526
Eli Friedman46f81662008-05-25 13:22:35 +0000527 if (Index < IList->getNumInits()) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000528 // We have leftover initializers
529 if (IList->getNumInits() > 0 &&
Chris Lattner2e2766a2009-02-24 22:50:46 +0000530 IsStringInit(IList->getInit(Index), T, SemaRef.Context)) {
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000531 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000532 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000533 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000534 // Special-case
Chris Lattner2e2766a2009-02-24 22:50:46 +0000535 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattner9d2cf082008-11-19 05:27:50 +0000536 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000537 hadError = true;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000538 } else if (!T->isIncompleteType()) {
Douglas Gregor09f078c2009-01-30 22:26:29 +0000539 // Don't complain for incomplete types, since we'll get an error
540 // elsewhere
Douglas Gregorbe69b162009-02-04 22:46:25 +0000541 QualType CurrentObjectType = StructuredList->getType();
542 int initKind =
543 CurrentObjectType->isArrayType()? 0 :
544 CurrentObjectType->isVectorType()? 1 :
545 CurrentObjectType->isScalarType()? 2 :
546 CurrentObjectType->isUnionType()? 3 :
547 4;
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000548
549 unsigned DK = diag::warn_excess_initializers;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000550 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000551 DK = diag::err_excess_initializers;
552
Chris Lattner2e2766a2009-02-24 22:50:46 +0000553 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorbe69b162009-02-04 22:46:25 +0000554 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000555 }
556 }
Eli Friedman455f7622008-05-19 20:20:43 +0000557
Eli Friedman90bcb892009-05-16 11:45:48 +0000558 if (T->isScalarType() && !TopLevelObject)
Chris Lattner2e2766a2009-02-24 22:50:46 +0000559 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor3faaa812009-04-01 23:51:29 +0000560 << IList->getSourceRange()
561 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocStart()))
562 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocEnd()));
Steve Naroffc4d4a482008-05-01 22:18:59 +0000563}
564
Eli Friedman683cedf2008-05-19 19:16:24 +0000565void InitListChecker::CheckListElementTypes(InitListExpr *IList,
566 QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000567 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000568 unsigned &Index,
569 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000570 unsigned &StructuredIndex,
571 bool TopLevelObject) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000572 if (DeclType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000573 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000574 } else if (DeclType->isVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000575 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregore7ef5002009-01-30 17:31:00 +0000576 } else if (DeclType->isAggregateType()) {
577 if (DeclType->isRecordType()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000578 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000579 CheckStructUnionTypes(IList, DeclType, RD->field_begin(SemaRef.Context),
Douglas Gregorf603b472009-01-28 21:54:33 +0000580 SubobjectIsDesignatorContext, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000581 StructuredList, StructuredIndex,
582 TopLevelObject);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000583 } else if (DeclType->isArrayType()) {
Douglas Gregor5a203a62009-01-23 16:54:12 +0000584 llvm::APSInt Zero(
Chris Lattner2e2766a2009-02-24 22:50:46 +0000585 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor5a203a62009-01-23 16:54:12 +0000586 false);
Douglas Gregorf603b472009-01-28 21:54:33 +0000587 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
588 StructuredList, StructuredIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000589 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000590 else
Douglas Gregorf603b472009-01-28 21:54:33 +0000591 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffff5b3a82008-08-10 16:05:48 +0000592 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
593 // This type is invalid, issue a diagnostic.
Douglas Gregorf603b472009-01-28 21:54:33 +0000594 ++Index;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000595 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000596 << DeclType;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000597 hadError = true;
Douglas Gregord45210d2009-01-30 22:09:00 +0000598 } else if (DeclType->isRecordType()) {
599 // C++ [dcl.init]p14:
600 // [...] If the class is an aggregate (8.5.1), and the initializer
601 // is a brace-enclosed list, see 8.5.1.
602 //
603 // Note: 8.5.1 is handled below; here, we diagnose the case where
604 // we have an initializer list and a destination type that is not
605 // an aggregate.
606 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000607 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord45210d2009-01-30 22:09:00 +0000608 << DeclType << IList->getSourceRange();
609 hadError = true;
610 } else if (DeclType->isReferenceType()) {
611 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000612 } else {
613 // In C, all types are either scalars or aggregates, but
614 // additional handling is needed here for C++ (and possibly others?).
615 assert(0 && "Unsupported initializer type");
616 }
617}
618
Eli Friedman683cedf2008-05-19 19:16:24 +0000619void InitListChecker::CheckSubElementType(InitListExpr *IList,
620 QualType ElemType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000621 unsigned &Index,
622 InitListExpr *StructuredList,
623 unsigned &StructuredIndex) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000624 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000625 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
626 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000627 unsigned newStructuredIndex = 0;
628 InitListExpr *newStructuredList
629 = getStructuredSubobjectInit(IList, Index, ElemType,
630 StructuredList, StructuredIndex,
631 SubInitList->getSourceRange());
632 CheckExplicitInitList(SubInitList, ElemType, newIndex,
633 newStructuredList, newStructuredIndex);
634 ++StructuredIndex;
635 ++Index;
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000636 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
637 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattner45d6fd62009-02-24 22:41:04 +0000638 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregorf603b472009-01-28 21:54:33 +0000639 ++Index;
Eli Friedmand8535af2008-05-19 20:00:43 +0000640 } else if (ElemType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000641 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000642 } else if (ElemType->isReferenceType()) {
643 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedman683cedf2008-05-19 19:16:24 +0000644 } else {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000645 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000646 // C++ [dcl.init.aggr]p12:
647 // All implicit type conversions (clause 4) are considered when
648 // initializing the aggregate member with an ini- tializer from
649 // an initializer-list. If the initializer can initialize a
650 // member, the member is initialized. [...]
651 ImplicitConversionSequence ICS
Chris Lattner2e2766a2009-02-24 22:50:46 +0000652 = SemaRef.TryCopyInitialization(expr, ElemType);
Douglas Gregord45210d2009-01-30 22:09:00 +0000653 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000654 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregord45210d2009-01-30 22:09:00 +0000655 "initializing"))
656 hadError = true;
657 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
658 ++Index;
659 return;
660 }
661
662 // Fall through for subaggregate initialization
663 } else {
664 // C99 6.7.8p13:
665 //
666 // The initializer for a structure or union object that has
667 // automatic storage duration shall be either an initializer
668 // list as described below, or a single expression that has
669 // compatible structure or union type. In the latter case, the
670 // initial value of the object, including unnamed members, is
671 // that of the expression.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000672 QualType ExprType = SemaRef.Context.getCanonicalType(expr->getType());
673 QualType ElemTypeCanon = SemaRef.Context.getCanonicalType(ElemType);
674 if (SemaRef.Context.typesAreCompatible(ExprType.getUnqualifiedType(),
Douglas Gregord45210d2009-01-30 22:09:00 +0000675 ElemTypeCanon.getUnqualifiedType())) {
676 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
677 ++Index;
678 return;
679 }
680
681 // Fall through for subaggregate initialization
682 }
683
684 // C++ [dcl.init.aggr]p12:
685 //
686 // [...] Otherwise, if the member is itself a non-empty
687 // subaggregate, brace elision is assumed and the initializer is
688 // considered for the initialization of the first member of
689 // the subaggregate.
690 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
691 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
692 StructuredIndex);
693 ++StructuredIndex;
694 } else {
695 // We cannot initialize this element, so let
696 // PerformCopyInitialization produce the appropriate diagnostic.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000697 SemaRef.PerformCopyInitialization(expr, ElemType, "initializing");
Douglas Gregord45210d2009-01-30 22:09:00 +0000698 hadError = true;
699 ++Index;
700 ++StructuredIndex;
701 }
702 }
Eli Friedman683cedf2008-05-19 19:16:24 +0000703}
704
Douglas Gregord45210d2009-01-30 22:09:00 +0000705void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor36859eb2009-01-29 00:39:20 +0000706 unsigned &Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000707 InitListExpr *StructuredList,
708 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000709 if (Index < IList->getNumInits()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000710 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000711 if (isa<InitListExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000712 SemaRef.Diag(IList->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000713 diag::err_many_braces_around_scalar_init)
714 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000715 hadError = true;
716 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000717 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000718 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000719 } else if (isa<DesignatedInitExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000720 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000721 diag::err_designator_for_scalar_init)
722 << DeclType << expr->getSourceRange();
723 hadError = true;
724 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000725 ++StructuredIndex;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000726 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000727 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000728
Eli Friedmand8535af2008-05-19 20:00:43 +0000729 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000730 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedman71de9eb2008-05-19 20:12:18 +0000731 hadError = true; // types weren't compatible.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000732 else if (savExpr != expr) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000733 // The type was promoted, update initializer list.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000734 IList->setInit(Index, expr);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000735 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000736 if (hadError)
737 ++StructuredIndex;
738 else
739 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000740 ++Index;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000741 } else {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000742 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattner9d2cf082008-11-19 05:27:50 +0000743 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000744 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000745 ++Index;
746 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000747 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000748 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000749}
750
Douglas Gregord45210d2009-01-30 22:09:00 +0000751void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
752 unsigned &Index,
753 InitListExpr *StructuredList,
754 unsigned &StructuredIndex) {
755 if (Index < IList->getNumInits()) {
756 Expr *expr = IList->getInit(Index);
757 if (isa<InitListExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000758 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord45210d2009-01-30 22:09:00 +0000759 << DeclType << IList->getSourceRange();
760 hadError = true;
761 ++Index;
762 ++StructuredIndex;
763 return;
764 }
765
766 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000767 if (SemaRef.CheckReferenceInit(expr, DeclType))
Douglas Gregord45210d2009-01-30 22:09:00 +0000768 hadError = true;
769 else if (savExpr != expr) {
770 // The type was promoted, update initializer list.
771 IList->setInit(Index, expr);
772 }
773 if (hadError)
774 ++StructuredIndex;
775 else
776 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
777 ++Index;
778 } else {
Mike Stumpe127ae32009-05-16 07:39:55 +0000779 // FIXME: It would be wonderful if we could point at the actual member. In
780 // general, it would be useful to pass location information down the stack,
781 // so that we know the location (or decl) of the "current object" being
782 // initialized.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000783 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord45210d2009-01-30 22:09:00 +0000784 diag::err_init_reference_member_uninitialized)
785 << DeclType
786 << IList->getSourceRange();
787 hadError = true;
788 ++Index;
789 ++StructuredIndex;
790 return;
791 }
792}
793
Steve Naroffc4d4a482008-05-01 22:18:59 +0000794void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000795 unsigned &Index,
796 InitListExpr *StructuredList,
797 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000798 if (Index < IList->getNumInits()) {
799 const VectorType *VT = DeclType->getAsVectorType();
800 int maxElements = VT->getNumElements();
801 QualType elementType = VT->getElementType();
802
803 for (int i = 0; i < maxElements; ++i) {
804 // Don't attempt to go past the end of the init list
805 if (Index >= IList->getNumInits())
806 break;
Douglas Gregor36859eb2009-01-29 00:39:20 +0000807 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000808 StructuredList, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000809 }
810 }
811}
812
813void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000814 llvm::APSInt elementIndex,
815 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000816 unsigned &Index,
817 InitListExpr *StructuredList,
818 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000819 // Check for the special-case of initializing an array with a string.
820 if (Index < IList->getNumInits()) {
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000821 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
822 SemaRef.Context)) {
823 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregorf603b472009-01-28 21:54:33 +0000824 // We place the string literal directly into the resulting
825 // initializer list. This is the only place where the structure
826 // of the structured initializer list doesn't match exactly,
827 // because doing so would involve allocating one character
828 // constant for each string.
Chris Lattner45d6fd62009-02-24 22:41:04 +0000829 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner2e2766a2009-02-24 22:50:46 +0000830 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000831 ++Index;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000832 return;
833 }
834 }
Chris Lattnera1923f62008-08-04 07:31:14 +0000835 if (const VariableArrayType *VAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000836 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman46f81662008-05-25 13:22:35 +0000837 // Check for VLAs; in standard C it would be possible to check this
838 // earlier, but I don't know where clang accepts VLAs (gcc accepts
839 // them in all sorts of strange places).
Chris Lattner2e2766a2009-02-24 22:50:46 +0000840 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000841 diag::err_variable_object_no_init)
842 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman46f81662008-05-25 13:22:35 +0000843 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000844 ++Index;
845 ++StructuredIndex;
Eli Friedman46f81662008-05-25 13:22:35 +0000846 return;
847 }
848
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000849 // We might know the maximum number of elements in advance.
Douglas Gregorf603b472009-01-28 21:54:33 +0000850 llvm::APSInt maxElements(elementIndex.getBitWidth(),
851 elementIndex.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000852 bool maxElementsKnown = false;
853 if (const ConstantArrayType *CAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000854 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000855 maxElements = CAT->getSize();
Douglas Gregor5a203a62009-01-23 16:54:12 +0000856 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000857 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000858 maxElementsKnown = true;
859 }
860
Chris Lattner2e2766a2009-02-24 22:50:46 +0000861 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnera1923f62008-08-04 07:31:14 +0000862 ->getElementType();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000863 while (Index < IList->getNumInits()) {
864 Expr *Init = IList->getInit(Index);
865 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000866 // If we're not the subobject that matches up with the '{' for
867 // the designator, we shouldn't be handling the
868 // designator. Return immediately.
869 if (!SubobjectIsDesignatorContext)
870 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000871
Douglas Gregor710f6d42009-01-22 23:26:18 +0000872 // Handle this designated initializer. elementIndex will be
873 // updated to be the next array element we'll initialize.
Douglas Gregoraa357272009-04-15 04:56:10 +0000874 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregorf603b472009-01-28 21:54:33 +0000875 DeclType, 0, &elementIndex, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000876 StructuredList, StructuredIndex, true,
877 false)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000878 hadError = true;
879 continue;
880 }
881
Douglas Gregor5a203a62009-01-23 16:54:12 +0000882 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
883 maxElements.extend(elementIndex.getBitWidth());
884 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
885 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000886 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor5a203a62009-01-23 16:54:12 +0000887
Douglas Gregor710f6d42009-01-22 23:26:18 +0000888 // If the array is of incomplete type, keep track of the number of
889 // elements in the initializer.
890 if (!maxElementsKnown && elementIndex > maxElements)
891 maxElements = elementIndex;
892
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000893 continue;
894 }
895
896 // If we know the maximum number of elements, and we've already
897 // hit it, stop consuming elements in the initializer list.
898 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000899 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000900
901 // Check this element.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000902 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000903 StructuredList, StructuredIndex);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000904 ++elementIndex;
905
906 // If the array is of incomplete type, keep track of the number of
907 // elements in the initializer.
908 if (!maxElementsKnown && elementIndex > maxElements)
909 maxElements = elementIndex;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000910 }
911 if (DeclType->isIncompleteArrayType()) {
912 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000913 // be calculated here.
Douglas Gregor69722702009-01-23 18:58:42 +0000914 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000915 if (maxElements == Zero) {
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000916 // Sizing an array implicitly to zero is not allowed by ISO C,
917 // but is supported by GNU.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000918 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000919 diag::ext_typecheck_zero_array_size);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000920 }
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000921
Chris Lattner2e2766a2009-02-24 22:50:46 +0000922 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000923 ArrayType::Normal, 0);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000924 }
925}
926
927void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
928 QualType DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000929 RecordDecl::field_iterator Field,
930 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000931 unsigned &Index,
932 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000933 unsigned &StructuredIndex,
934 bool TopLevelObject) {
Eli Friedman683cedf2008-05-19 19:16:24 +0000935 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000936
Eli Friedman683cedf2008-05-19 19:16:24 +0000937 // If the record is invalid, some of it's members are invalid. To avoid
938 // confusion, we forgo checking the intializer for the entire record.
939 if (structDecl->isInvalidDecl()) {
940 hadError = true;
941 return;
942 }
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000943
944 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
945 // Value-initialize the first named member of the union.
946 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000947 for (RecordDecl::field_iterator FieldEnd = RD->field_end(SemaRef.Context);
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000948 Field != FieldEnd; ++Field) {
949 if (Field->getDeclName()) {
950 StructuredList->setInitializedFieldInUnion(*Field);
951 break;
952 }
953 }
954 return;
955 }
956
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000957 // If structDecl is a forward declaration, this loop won't do
958 // anything except look at designated initializers; That's okay,
959 // because an error should get printed out elsewhere. It might be
960 // worthwhile to skip over the rest of the initializer, though.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000961 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000962 RecordDecl::field_iterator FieldEnd = RD->field_end(SemaRef.Context);
Douglas Gregor0ecc9e92009-02-12 19:00:39 +0000963 bool InitializedSomething = false;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000964 while (Index < IList->getNumInits()) {
965 Expr *Init = IList->getInit(Index);
966
967 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000968 // If we're not the subobject that matches up with the '{' for
969 // the designator, we shouldn't be handling the
970 // designator. Return immediately.
971 if (!SubobjectIsDesignatorContext)
972 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000973
Douglas Gregor710f6d42009-01-22 23:26:18 +0000974 // Handle this designated initializer. Field will be updated to
975 // the next field that we'll be initializing.
Douglas Gregoraa357272009-04-15 04:56:10 +0000976 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregorf603b472009-01-28 21:54:33 +0000977 DeclType, &Field, 0, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000978 StructuredList, StructuredIndex,
979 true, TopLevelObject))
Douglas Gregor710f6d42009-01-22 23:26:18 +0000980 hadError = true;
981
Douglas Gregor0ecc9e92009-02-12 19:00:39 +0000982 InitializedSomething = true;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000983 continue;
984 }
985
986 if (Field == FieldEnd) {
987 // We've run out of fields. We're done.
988 break;
989 }
990
Douglas Gregor0ecc9e92009-02-12 19:00:39 +0000991 // We've already initialized a member of a union. We're done.
992 if (InitializedSomething && DeclType->isUnionType())
993 break;
994
Douglas Gregor8acb7272008-12-11 16:49:14 +0000995 // If we've hit the flexible array member at the end, we're done.
996 if (Field->getType()->isIncompleteArrayType())
997 break;
998
Douglas Gregor82462762009-01-29 16:53:55 +0000999 if (Field->isUnnamedBitfield()) {
Douglas Gregorf603b472009-01-28 21:54:33 +00001000 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001001 ++Field;
Eli Friedman683cedf2008-05-19 19:16:24 +00001002 continue;
Steve Naroffc4d4a482008-05-01 22:18:59 +00001003 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001004
Douglas Gregor36859eb2009-01-29 00:39:20 +00001005 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001006 StructuredList, StructuredIndex);
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001007 InitializedSomething = true;
Douglas Gregor82462762009-01-29 16:53:55 +00001008
1009 if (DeclType->isUnionType()) {
1010 // Initialize the first field within the union.
1011 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor82462762009-01-29 16:53:55 +00001012 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001013
1014 ++Field;
Steve Naroffc4d4a482008-05-01 22:18:59 +00001015 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001016
Douglas Gregorbe69b162009-02-04 22:46:25 +00001017 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001018 Index >= IList->getNumInits())
Douglas Gregorbe69b162009-02-04 22:46:25 +00001019 return;
1020
1021 // Handle GNU flexible array initializers.
1022 if (!TopLevelObject &&
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001023 (!isa<InitListExpr>(IList->getInit(Index)) ||
1024 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001025 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001026 diag::err_flexible_array_init_nonempty)
1027 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001028 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001029 << *Field;
1030 hadError = true;
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001031 ++Index;
1032 return;
1033 } else {
1034 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
1035 diag::ext_flexible_array_init)
1036 << IList->getInit(Index)->getSourceRange().getBegin();
1037 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1038 << *Field;
Douglas Gregorbe69b162009-02-04 22:46:25 +00001039 }
1040
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001041 if (isa<InitListExpr>(IList->getInit(Index)))
1042 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1043 StructuredIndex);
1044 else
1045 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1046 StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +00001047}
Steve Naroffc4d4a482008-05-01 22:18:59 +00001048
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001049/// \brief Expand a field designator that refers to a member of an
1050/// anonymous struct or union into a series of field designators that
1051/// refers to the field within the appropriate subobject.
1052///
1053/// Field/FieldIndex will be updated to point to the (new)
1054/// currently-designated field.
1055static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1056 DesignatedInitExpr *DIE,
1057 unsigned DesigIdx,
1058 FieldDecl *Field,
1059 RecordDecl::field_iterator &FieldIter,
1060 unsigned &FieldIndex) {
1061 typedef DesignatedInitExpr::Designator Designator;
1062
1063 // Build the path from the current object to the member of the
1064 // anonymous struct/union (backwards).
1065 llvm::SmallVector<FieldDecl *, 4> Path;
1066 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
1067
1068 // Build the replacement designators.
1069 llvm::SmallVector<Designator, 4> Replacements;
1070 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1071 FI = Path.rbegin(), FIEnd = Path.rend();
1072 FI != FIEnd; ++FI) {
1073 if (FI + 1 == FIEnd)
1074 Replacements.push_back(Designator((IdentifierInfo *)0,
1075 DIE->getDesignator(DesigIdx)->getDotLoc(),
1076 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1077 else
1078 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1079 SourceLocation()));
1080 Replacements.back().setField(*FI);
1081 }
1082
1083 // Expand the current designator into the set of replacement
1084 // designators, so we have a full subobject path down to where the
1085 // member of the anonymous struct/union is actually stored.
1086 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
1087 &Replacements[0] + Replacements.size());
1088
1089 // Update FieldIter/FieldIndex;
1090 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
1091 FieldIter = Record->field_begin(SemaRef.Context);
1092 FieldIndex = 0;
1093 for (RecordDecl::field_iterator FEnd = Record->field_end(SemaRef.Context);
1094 FieldIter != FEnd; ++FieldIter) {
1095 if (FieldIter->isUnnamedBitfield())
1096 continue;
1097
1098 if (*FieldIter == Path.back())
1099 return;
1100
1101 ++FieldIndex;
1102 }
1103
1104 assert(false && "Unable to find anonymous struct/union field");
1105}
1106
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001107/// @brief Check the well-formedness of a C99 designated initializer.
1108///
1109/// Determines whether the designated initializer @p DIE, which
1110/// resides at the given @p Index within the initializer list @p
1111/// IList, is well-formed for a current object of type @p DeclType
1112/// (C99 6.7.8). The actual subobject that this designator refers to
1113/// within the current subobject is returned in either
Douglas Gregorf603b472009-01-28 21:54:33 +00001114/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001115///
1116/// @param IList The initializer list in which this designated
1117/// initializer occurs.
1118///
Douglas Gregoraa357272009-04-15 04:56:10 +00001119/// @param DIE The designated initializer expression.
1120///
1121/// @param DesigIdx The index of the current designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001122///
1123/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1124/// into which the designation in @p DIE should refer.
1125///
Douglas Gregor710f6d42009-01-22 23:26:18 +00001126/// @param NextField If non-NULL and the first designator in @p DIE is
1127/// a field, this will be set to the field declaration corresponding
1128/// to the field named by the designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001129///
Douglas Gregor710f6d42009-01-22 23:26:18 +00001130/// @param NextElementIndex If non-NULL and the first designator in @p
1131/// DIE is an array designator or GNU array-range designator, this
1132/// will be set to the last index initialized by this designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001133///
1134/// @param Index Index into @p IList where the designated initializer
1135/// @p DIE occurs.
1136///
Douglas Gregorf603b472009-01-28 21:54:33 +00001137/// @param StructuredList The initializer list expression that
1138/// describes all of the subobject initializers in the order they'll
1139/// actually be initialized.
1140///
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001141/// @returns true if there was an error, false otherwise.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001142bool
1143InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
1144 DesignatedInitExpr *DIE,
Douglas Gregoraa357272009-04-15 04:56:10 +00001145 unsigned DesigIdx,
Douglas Gregor710f6d42009-01-22 23:26:18 +00001146 QualType &CurrentObjectType,
1147 RecordDecl::field_iterator *NextField,
1148 llvm::APSInt *NextElementIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +00001149 unsigned &Index,
1150 InitListExpr *StructuredList,
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001151 unsigned &StructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001152 bool FinishSubobjectInit,
1153 bool TopLevelObject) {
Douglas Gregoraa357272009-04-15 04:56:10 +00001154 if (DesigIdx == DIE->size()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001155 // Check the actual initialization for the designated object type.
1156 bool prevHadError = hadError;
Douglas Gregor36859eb2009-01-29 00:39:20 +00001157
1158 // Temporarily remove the designator expression from the
1159 // initializer list that the child calls see, so that we don't try
1160 // to re-process the designator.
1161 unsigned OldIndex = Index;
1162 IList->setInit(OldIndex, DIE->getInit());
1163
1164 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001165 StructuredList, StructuredIndex);
Douglas Gregor36859eb2009-01-29 00:39:20 +00001166
1167 // Restore the designated initializer expression in the syntactic
1168 // form of the initializer list.
1169 if (IList->getInit(OldIndex) != DIE->getInit())
1170 DIE->setInit(IList->getInit(OldIndex));
1171 IList->setInit(OldIndex, DIE);
1172
Douglas Gregor710f6d42009-01-22 23:26:18 +00001173 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001174 }
1175
Douglas Gregoraa357272009-04-15 04:56:10 +00001176 bool IsFirstDesignator = (DesigIdx == 0);
Douglas Gregorf603b472009-01-28 21:54:33 +00001177 assert((IsFirstDesignator || StructuredList) &&
1178 "Need a non-designated initializer list to start from");
1179
Douglas Gregoraa357272009-04-15 04:56:10 +00001180 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregorf603b472009-01-28 21:54:33 +00001181 // Determine the structural initializer list that corresponds to the
1182 // current subobject.
1183 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Douglas Gregorea765e12009-03-01 17:12:46 +00001184 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1185 StructuredList, StructuredIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +00001186 SourceRange(D->getStartLocation(),
1187 DIE->getSourceRange().getEnd()));
1188 assert(StructuredList && "Expected a structured initializer list");
1189
Douglas Gregor710f6d42009-01-22 23:26:18 +00001190 if (D->isFieldDesignator()) {
1191 // C99 6.7.8p7:
1192 //
1193 // If a designator has the form
1194 //
1195 // . identifier
1196 //
1197 // then the current object (defined below) shall have
1198 // structure or union type and the identifier shall be the
1199 // name of a member of that type.
1200 const RecordType *RT = CurrentObjectType->getAsRecordType();
1201 if (!RT) {
1202 SourceLocation Loc = D->getDotLoc();
1203 if (Loc.isInvalid())
1204 Loc = D->getFieldLoc();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001205 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1206 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001207 ++Index;
1208 return true;
1209 }
1210
Douglas Gregorf603b472009-01-28 21:54:33 +00001211 // Note: we perform a linear search of the fields here, despite
1212 // the fact that we have a faster lookup method, because we always
1213 // need to compute the field's index.
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001214 FieldDecl *KnownField = D->getField();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001215 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregorf603b472009-01-28 21:54:33 +00001216 unsigned FieldIndex = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001217 RecordDecl::field_iterator
1218 Field = RT->getDecl()->field_begin(SemaRef.Context),
1219 FieldEnd = RT->getDecl()->field_end(SemaRef.Context);
Douglas Gregorf603b472009-01-28 21:54:33 +00001220 for (; Field != FieldEnd; ++Field) {
1221 if (Field->isUnnamedBitfield())
1222 continue;
1223
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001224 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregorf603b472009-01-28 21:54:33 +00001225 break;
1226
1227 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001228 }
1229
Douglas Gregorf603b472009-01-28 21:54:33 +00001230 if (Field == FieldEnd) {
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001231 // There was no normal field in the struct with the designated
1232 // name. Perform another lookup for this name, which may find
1233 // something that we can't designate (e.g., a member function),
1234 // may find nothing, or may find a member of an anonymous
1235 // struct/union.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001236 DeclContext::lookup_result Lookup
1237 = RT->getDecl()->lookup(SemaRef.Context, FieldName);
Douglas Gregorf603b472009-01-28 21:54:33 +00001238 if (Lookup.first == Lookup.second) {
1239 // Name lookup didn't find anything.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001240 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregorf603b472009-01-28 21:54:33 +00001241 << FieldName << CurrentObjectType;
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001242 ++Index;
1243 return true;
1244 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1245 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1246 ->isAnonymousStructOrUnion()) {
1247 // Handle an field designator that refers to a member of an
1248 // anonymous struct or union.
1249 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1250 cast<FieldDecl>(*Lookup.first),
1251 Field, FieldIndex);
Eli Friedmanbd45b552009-04-16 17:49:48 +00001252 D = DIE->getDesignator(DesigIdx);
Douglas Gregorf603b472009-01-28 21:54:33 +00001253 } else {
1254 // Name lookup found something, but it wasn't a field.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001255 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregorf603b472009-01-28 21:54:33 +00001256 << FieldName;
Chris Lattner2e2766a2009-02-24 22:50:46 +00001257 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001258 diag::note_field_designator_found);
Eli Friedmanbd45b552009-04-16 17:49:48 +00001259 ++Index;
1260 return true;
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001261 }
1262 } else if (!KnownField &&
1263 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregorf603b472009-01-28 21:54:33 +00001264 ->isAnonymousStructOrUnion()) {
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001265 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1266 Field, FieldIndex);
1267 D = DIE->getDesignator(DesigIdx);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001268 }
Douglas Gregorf603b472009-01-28 21:54:33 +00001269
1270 // All of the fields of a union are located at the same place in
1271 // the initializer list.
Douglas Gregor82462762009-01-29 16:53:55 +00001272 if (RT->getDecl()->isUnion()) {
Douglas Gregorf603b472009-01-28 21:54:33 +00001273 FieldIndex = 0;
Douglas Gregor82462762009-01-29 16:53:55 +00001274 StructuredList->setInitializedFieldInUnion(*Field);
1275 }
Douglas Gregorf603b472009-01-28 21:54:33 +00001276
Douglas Gregor710f6d42009-01-22 23:26:18 +00001277 // Update the designator with the field declaration.
Douglas Gregorf603b472009-01-28 21:54:33 +00001278 D->setField(*Field);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001279
Douglas Gregorf603b472009-01-28 21:54:33 +00001280 // Make sure that our non-designated initializer list has space
1281 // for a subobject corresponding to this field.
1282 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner2e2766a2009-02-24 22:50:46 +00001283 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +00001284
Douglas Gregorbe69b162009-02-04 22:46:25 +00001285 // This designator names a flexible array member.
1286 if (Field->getType()->isIncompleteArrayType()) {
1287 bool Invalid = false;
Douglas Gregoraa357272009-04-15 04:56:10 +00001288 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorbe69b162009-02-04 22:46:25 +00001289 // We can't designate an object within the flexible array
1290 // member (because GCC doesn't allow it).
Douglas Gregoraa357272009-04-15 04:56:10 +00001291 DesignatedInitExpr::Designator *NextD
1292 = DIE->getDesignator(DesigIdx + 1);
Chris Lattner2e2766a2009-02-24 22:50:46 +00001293 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001294 diag::err_designator_into_flexible_array_member)
1295 << SourceRange(NextD->getStartLocation(),
1296 DIE->getSourceRange().getEnd());
Chris Lattner2e2766a2009-02-24 22:50:46 +00001297 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001298 << *Field;
1299 Invalid = true;
1300 }
1301
1302 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1303 // The initializer is not an initializer list.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001304 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001305 diag::err_flexible_array_init_needs_braces)
1306 << DIE->getInit()->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001307 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001308 << *Field;
1309 Invalid = true;
1310 }
1311
1312 // Handle GNU flexible array initializers.
1313 if (!Invalid && !TopLevelObject &&
1314 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001315 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001316 diag::err_flexible_array_init_nonempty)
1317 << DIE->getSourceRange().getBegin();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001318 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001319 << *Field;
1320 Invalid = true;
1321 }
1322
1323 if (Invalid) {
1324 ++Index;
1325 return true;
1326 }
1327
1328 // Initialize the array.
1329 bool prevHadError = hadError;
1330 unsigned newStructuredIndex = FieldIndex;
1331 unsigned OldIndex = Index;
1332 IList->setInit(Index, DIE->getInit());
1333 CheckSubElementType(IList, Field->getType(), Index,
1334 StructuredList, newStructuredIndex);
1335 IList->setInit(OldIndex, DIE);
1336 if (hadError && !prevHadError) {
1337 ++Field;
1338 ++FieldIndex;
1339 if (NextField)
1340 *NextField = Field;
1341 StructuredIndex = FieldIndex;
1342 return true;
1343 }
1344 } else {
1345 // Recurse to check later designated subobjects.
1346 QualType FieldType = (*Field)->getType();
1347 unsigned newStructuredIndex = FieldIndex;
Douglas Gregoraa357272009-04-15 04:56:10 +00001348 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1349 Index, StructuredList, newStructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001350 true, false))
1351 return true;
1352 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001353
1354 // Find the position of the next field to be initialized in this
1355 // subobject.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001356 ++Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001357 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001358
1359 // If this the first designator, our caller will continue checking
1360 // the rest of this struct/class/union subobject.
1361 if (IsFirstDesignator) {
1362 if (NextField)
1363 *NextField = Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001364 StructuredIndex = FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001365 return false;
1366 }
1367
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001368 if (!FinishSubobjectInit)
1369 return false;
1370
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001371 // We've already initialized something in the union; we're done.
1372 if (RT->getDecl()->isUnion())
1373 return hadError;
1374
Douglas Gregor710f6d42009-01-22 23:26:18 +00001375 // Check the remaining fields within this class/struct/union subobject.
1376 bool prevHadError = hadError;
Douglas Gregorf603b472009-01-28 21:54:33 +00001377 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1378 StructuredList, FieldIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001379 return hadError && !prevHadError;
1380 }
1381
1382 // C99 6.7.8p6:
1383 //
1384 // If a designator has the form
1385 //
1386 // [ constant-expression ]
1387 //
1388 // then the current object (defined below) shall have array
1389 // type and the expression shall be an integer constant
1390 // expression. If the array is of unknown size, any
1391 // nonnegative value is valid.
1392 //
1393 // Additionally, cope with the GNU extension that permits
1394 // designators of the form
1395 //
1396 // [ constant-expression ... constant-expression ]
Chris Lattner2e2766a2009-02-24 22:50:46 +00001397 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001398 if (!AT) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001399 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor710f6d42009-01-22 23:26:18 +00001400 << CurrentObjectType;
1401 ++Index;
1402 return true;
1403 }
1404
1405 Expr *IndexExpr = 0;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001406 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1407 if (D->isArrayDesignator()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001408 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnereec8ae22009-04-25 21:59:05 +00001409 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001410 DesignatedEndIndex = DesignatedStartIndex;
1411 } else {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001412 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001413
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001414
Chris Lattnereec8ae22009-04-25 21:59:05 +00001415 DesignatedStartIndex =
1416 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
1417 DesignatedEndIndex =
1418 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001419 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001420
Chris Lattnereec8ae22009-04-25 21:59:05 +00001421 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregor9fddded2009-01-29 19:42:23 +00001422 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001423 }
1424
Douglas Gregor710f6d42009-01-22 23:26:18 +00001425 if (isa<ConstantArrayType>(AT)) {
1426 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001427 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1428 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1429 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1430 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1431 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001432 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor710f6d42009-01-22 23:26:18 +00001433 diag::err_array_designator_too_large)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001434 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor710f6d42009-01-22 23:26:18 +00001435 << IndexExpr->getSourceRange();
1436 ++Index;
1437 return true;
1438 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001439 } else {
1440 // Make sure the bit-widths and signedness match.
1441 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1442 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnereec8ae22009-04-25 21:59:05 +00001443 else if (DesignatedStartIndex.getBitWidth() <
1444 DesignatedEndIndex.getBitWidth())
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001445 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1446 DesignatedStartIndex.setIsUnsigned(true);
1447 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001448 }
1449
Douglas Gregorf603b472009-01-28 21:54:33 +00001450 // Make sure that our non-designated initializer list has space
1451 // for a subobject corresponding to this array element.
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001452 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Chris Lattner2e2766a2009-02-24 22:50:46 +00001453 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001454 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +00001455
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001456 // Repeatedly perform subobject initializations in the range
1457 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor710f6d42009-01-22 23:26:18 +00001458
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001459 // Move to the next designator
1460 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1461 unsigned OldIndex = Index;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001462 while (DesignatedStartIndex <= DesignatedEndIndex) {
1463 // Recurse to check later designated subobjects.
1464 QualType ElementType = AT->getElementType();
1465 Index = OldIndex;
Douglas Gregoraa357272009-04-15 04:56:10 +00001466 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1467 Index, StructuredList, ElementIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001468 (DesignatedStartIndex == DesignatedEndIndex),
1469 false))
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001470 return true;
1471
1472 // Move to the next index in the array that we'll be initializing.
1473 ++DesignatedStartIndex;
1474 ElementIndex = DesignatedStartIndex.getZExtValue();
1475 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001476
1477 // If this the first designator, our caller will continue checking
1478 // the rest of this array subobject.
1479 if (IsFirstDesignator) {
1480 if (NextElementIndex)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001481 *NextElementIndex = DesignatedStartIndex;
Douglas Gregorf603b472009-01-28 21:54:33 +00001482 StructuredIndex = ElementIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001483 return false;
1484 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001485
1486 if (!FinishSubobjectInit)
1487 return false;
1488
Douglas Gregor710f6d42009-01-22 23:26:18 +00001489 // Check the remaining elements within this array subobject.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001490 bool prevHadError = hadError;
Douglas Gregord7e76c52009-02-09 19:45:19 +00001491 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001492 StructuredList, ElementIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001493 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001494}
1495
Douglas Gregorf603b472009-01-28 21:54:33 +00001496// Get the structured initializer list for a subobject of type
1497// @p CurrentObjectType.
1498InitListExpr *
1499InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1500 QualType CurrentObjectType,
1501 InitListExpr *StructuredList,
1502 unsigned StructuredIndex,
1503 SourceRange InitRange) {
1504 Expr *ExistingInit = 0;
1505 if (!StructuredList)
1506 ExistingInit = SyntacticToSemantic[IList];
1507 else if (StructuredIndex < StructuredList->getNumInits())
1508 ExistingInit = StructuredList->getInit(StructuredIndex);
1509
1510 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1511 return Result;
1512
1513 if (ExistingInit) {
1514 // We are creating an initializer list that initializes the
1515 // subobjects of the current object, but there was already an
1516 // initialization that completely initialized the current
1517 // subobject, e.g., by a compound literal:
1518 //
1519 // struct X { int a, b; };
1520 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1521 //
1522 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1523 // designated initializer re-initializes the whole
1524 // subobject [0], overwriting previous initializers.
Douglas Gregorea765e12009-03-01 17:12:46 +00001525 SemaRef.Diag(InitRange.getBegin(),
1526 diag::warn_subobject_initializer_overrides)
Douglas Gregorf603b472009-01-28 21:54:33 +00001527 << InitRange;
Chris Lattner2e2766a2009-02-24 22:50:46 +00001528 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001529 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001530 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001531 << ExistingInit->getSourceRange();
1532 }
1533
1534 InitListExpr *Result
Douglas Gregorea765e12009-03-01 17:12:46 +00001535 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
1536 InitRange.getEnd());
1537
Douglas Gregorf603b472009-01-28 21:54:33 +00001538 Result->setType(CurrentObjectType);
1539
Douglas Gregoree0792c2009-03-20 23:58:33 +00001540 // Pre-allocate storage for the structured initializer list.
1541 unsigned NumElements = 0;
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001542 unsigned NumInits = 0;
1543 if (!StructuredList)
1544 NumInits = IList->getNumInits();
1545 else if (Index < IList->getNumInits()) {
1546 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1547 NumInits = SubList->getNumInits();
1548 }
1549
Douglas Gregoree0792c2009-03-20 23:58:33 +00001550 if (const ArrayType *AType
1551 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1552 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1553 NumElements = CAType->getSize().getZExtValue();
1554 // Simple heuristic so that we don't allocate a very large
1555 // initializer with many empty entries at the end.
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001556 if (NumInits && NumElements > NumInits)
Douglas Gregoree0792c2009-03-20 23:58:33 +00001557 NumElements = 0;
1558 }
1559 } else if (const VectorType *VType = CurrentObjectType->getAsVectorType())
1560 NumElements = VType->getNumElements();
1561 else if (const RecordType *RType = CurrentObjectType->getAsRecordType()) {
1562 RecordDecl *RDecl = RType->getDecl();
1563 if (RDecl->isUnion())
1564 NumElements = 1;
1565 else
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001566 NumElements = std::distance(RDecl->field_begin(SemaRef.Context),
1567 RDecl->field_end(SemaRef.Context));
Douglas Gregoree0792c2009-03-20 23:58:33 +00001568 }
1569
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001570 if (NumElements < NumInits)
Douglas Gregoree0792c2009-03-20 23:58:33 +00001571 NumElements = IList->getNumInits();
1572
1573 Result->reserveInits(NumElements);
1574
Douglas Gregorf603b472009-01-28 21:54:33 +00001575 // Link this new initializer list into the structured initializer
1576 // lists.
1577 if (StructuredList)
1578 StructuredList->updateInit(StructuredIndex, Result);
1579 else {
1580 Result->setSyntacticForm(IList);
1581 SyntacticToSemantic[IList] = Result;
1582 }
1583
1584 return Result;
1585}
1586
1587/// Update the initializer at index @p StructuredIndex within the
1588/// structured initializer list to the value @p expr.
1589void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1590 unsigned &StructuredIndex,
1591 Expr *expr) {
1592 // No structured initializer list to update
1593 if (!StructuredList)
1594 return;
1595
1596 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1597 // This initializer overwrites a previous initializer. Warn.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001598 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001599 diag::warn_initializer_overrides)
1600 << expr->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001601 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001602 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001603 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001604 << PrevInit->getSourceRange();
1605 }
1606
1607 ++StructuredIndex;
1608}
1609
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001610/// Check that the given Index expression is a valid array designator
1611/// value. This is essentailly just a wrapper around
Chris Lattnereec8ae22009-04-25 21:59:05 +00001612/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001613/// and produces a reasonable diagnostic if there is a
1614/// failure. Returns true if there was an error, false otherwise. If
1615/// everything went okay, Value will receive the value of the constant
1616/// expression.
1617static bool
Chris Lattnereec8ae22009-04-25 21:59:05 +00001618CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001619 SourceLocation Loc = Index->getSourceRange().getBegin();
1620
1621 // Make sure this is an integer constant expression.
Chris Lattnereec8ae22009-04-25 21:59:05 +00001622 if (S.VerifyIntegerConstantExpression(Index, &Value))
1623 return true;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001624
Chris Lattnereec8ae22009-04-25 21:59:05 +00001625 if (Value.isSigned() && Value.isNegative())
1626 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001627 << Value.toString(10) << Index->getSourceRange();
1628
Douglas Gregore498e372009-01-23 21:04:18 +00001629 Value.setIsUnsigned(true);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001630 return false;
1631}
1632
1633Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1634 SourceLocation Loc,
Douglas Gregor5f34f0e2009-03-28 00:41:23 +00001635 bool GNUSyntax,
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001636 OwningExprResult Init) {
1637 typedef DesignatedInitExpr::Designator ASTDesignator;
1638
1639 bool Invalid = false;
1640 llvm::SmallVector<ASTDesignator, 32> Designators;
1641 llvm::SmallVector<Expr *, 32> InitExpressions;
1642
1643 // Build designators and check array designator expressions.
1644 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1645 const Designator &D = Desig.getDesignator(Idx);
1646 switch (D.getKind()) {
1647 case Designator::FieldDesignator:
1648 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1649 D.getFieldLoc()));
1650 break;
1651
1652 case Designator::ArrayDesignator: {
1653 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1654 llvm::APSInt IndexValue;
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001655 if (!Index->isTypeDependent() &&
1656 !Index->isValueDependent() &&
1657 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001658 Invalid = true;
1659 else {
1660 Designators.push_back(ASTDesignator(InitExpressions.size(),
1661 D.getLBracketLoc(),
1662 D.getRBracketLoc()));
1663 InitExpressions.push_back(Index);
1664 }
1665 break;
1666 }
1667
1668 case Designator::ArrayRangeDesignator: {
1669 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1670 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1671 llvm::APSInt StartValue;
1672 llvm::APSInt EndValue;
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001673 bool StartDependent = StartIndex->isTypeDependent() ||
1674 StartIndex->isValueDependent();
1675 bool EndDependent = EndIndex->isTypeDependent() ||
1676 EndIndex->isValueDependent();
1677 if ((!StartDependent &&
1678 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1679 (!EndDependent &&
1680 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001681 Invalid = true;
Douglas Gregorea0528d2009-01-23 22:22:29 +00001682 else {
1683 // Make sure we're comparing values with the same bit width.
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001684 if (StartDependent || EndDependent) {
1685 // Nothing to compute.
1686 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregorea0528d2009-01-23 22:22:29 +00001687 EndValue.extend(StartValue.getBitWidth());
1688 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1689 StartValue.extend(EndValue.getBitWidth());
1690
Douglas Gregor1401c062009-05-21 23:30:39 +00001691 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregorea0528d2009-01-23 22:22:29 +00001692 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1693 << StartValue.toString(10) << EndValue.toString(10)
1694 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1695 Invalid = true;
1696 } else {
1697 Designators.push_back(ASTDesignator(InitExpressions.size(),
1698 D.getLBracketLoc(),
1699 D.getEllipsisLoc(),
1700 D.getRBracketLoc()));
1701 InitExpressions.push_back(StartIndex);
1702 InitExpressions.push_back(EndIndex);
1703 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001704 }
1705 break;
1706 }
1707 }
1708 }
1709
1710 if (Invalid || Init.isInvalid())
1711 return ExprError();
1712
1713 // Clear out the expressions within the designation.
1714 Desig.ClearExprs(*this);
1715
1716 DesignatedInitExpr *DIE
Jay Foad9e6bef42009-05-21 09:52:38 +00001717 = DesignatedInitExpr::Create(Context,
1718 Designators.data(), Designators.size(),
1719 InitExpressions.data(), InitExpressions.size(),
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001720 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001721 return Owned(DIE);
1722}
Douglas Gregor849afc32009-01-29 00:45:39 +00001723
1724bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001725 InitListChecker CheckInitList(*this, InitList, DeclType);
Douglas Gregor849afc32009-01-29 00:45:39 +00001726 if (!CheckInitList.HadError())
1727 InitList = CheckInitList.getFullyStructuredList();
1728
1729 return CheckInitList.HadError();
1730}
Douglas Gregor538a4c22009-02-02 17:43:21 +00001731
1732/// \brief Diagnose any semantic errors with value-initialization of
1733/// the given type.
1734///
1735/// Value-initialization effectively zero-initializes any types
1736/// without user-declared constructors, and calls the default
1737/// constructor for a for any type that has a user-declared
1738/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1739/// a type with a user-declared constructor does not have an
1740/// accessible, non-deleted default constructor. In C, everything can
1741/// be value-initialized, which corresponds to C's notion of
1742/// initializing objects with static storage duration when no
1743/// initializer is provided for that object.
1744///
1745/// \returns true if there was an error, false otherwise.
1746bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1747 // C++ [dcl.init]p5:
1748 //
1749 // To value-initialize an object of type T means:
1750
1751 // -- if T is an array type, then each element is value-initialized;
1752 if (const ArrayType *AT = Context.getAsArrayType(Type))
1753 return CheckValueInitialization(AT->getElementType(), Loc);
1754
1755 if (const RecordType *RT = Type->getAsRecordType()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001756 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Douglas Gregor538a4c22009-02-02 17:43:21 +00001757 // -- if T is a class type (clause 9) with a user-declared
1758 // constructor (12.1), then the default constructor for T is
1759 // called (and the initialization is ill-formed if T has no
1760 // accessible default constructor);
Douglas Gregor2e047592009-02-28 01:32:25 +00001761 if (ClassDecl->hasUserDeclaredConstructor())
Mike Stumpe127ae32009-05-16 07:39:55 +00001762 // FIXME: Eventually, we'll need to put the constructor decl into the
1763 // AST.
Douglas Gregor538a4c22009-02-02 17:43:21 +00001764 return PerformInitializationByConstructor(Type, 0, 0, Loc,
1765 SourceRange(Loc),
1766 DeclarationName(),
1767 IK_Direct);
1768 }
1769 }
1770
1771 if (Type->isReferenceType()) {
1772 // C++ [dcl.init]p5:
1773 // [...] A program that calls for default-initialization or
1774 // value-initialization of an entity of reference type is
1775 // ill-formed. [...]
Mike Stumpe127ae32009-05-16 07:39:55 +00001776 // FIXME: Once we have code that goes through this path, add an actual
1777 // diagnostic :)
Douglas Gregor538a4c22009-02-02 17:43:21 +00001778 }
1779
1780 return false;
1781}