blob: 785e40b16526d4b34af36705b861e496c98159ca [file] [log] [blame]
Steve Naroff0cca7492008-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 Lattnerdd8e0062009-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 Lattner8b419b92009-02-24 22:48:58 +000014// This file also implements Sema::CheckInitializerTypes.
Steve Naroff0cca7492008-05-01 22:18:59 +000015//
16//===----------------------------------------------------------------------===//
17
Douglas Gregor20093b42009-12-09 23:02:17 +000018#include "SemaInit.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000019#include "Sema.h"
Douglas Gregor05c13a32009-01-22 00:58:24 +000020#include "clang/Parse/Designator.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000021#include "clang/AST/ASTContext.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000022#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000023#include "clang/AST/ExprObjC.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000024#include "llvm/Support/ErrorHandling.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000025#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000026using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000027
Chris Lattnerdd8e0062009-02-24 22:27:37 +000028//===----------------------------------------------------------------------===//
29// Sema Initialization Checking
30//===----------------------------------------------------------------------===//
31
Chris Lattner79e079d2009-02-24 23:10:27 +000032static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattner8879e3b2009-02-26 23:26:43 +000033 const ArrayType *AT = Context.getAsArrayType(DeclType);
34 if (!AT) return 0;
35
Eli Friedman8718a6a2009-05-29 18:22:49 +000036 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
37 return 0;
38
Chris Lattner8879e3b2009-02-26 23:26:43 +000039 // See if this is a string literal or @encode.
40 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000041
Chris Lattner8879e3b2009-02-26 23:26:43 +000042 // Handle @encode, which is a narrow string.
43 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
44 return Init;
45
46 // Otherwise we can only handle string literals.
47 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000048 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000049
50 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattner8879e3b2009-02-26 23:26:43 +000051 // char array can be initialized with a narrow string.
52 // Only allow char x[] = "foo"; not char x[] = L"foo";
53 if (!SL->isWide())
Eli Friedmanbb6415c2009-05-31 10:54:53 +000054 return ElemTy->isCharType() ? Init : 0;
Chris Lattner8879e3b2009-02-26 23:26:43 +000055
Eli Friedmanbb6415c2009-05-31 10:54:53 +000056 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
57 // correction from DR343): "An array with element type compatible with a
58 // qualified or unqualified version of wchar_t may be initialized by a wide
59 // string literal, optionally enclosed in braces."
60 if (Context.typesAreCompatible(Context.getWCharType(),
61 ElemTy.getUnqualifiedType()))
Chris Lattner8879e3b2009-02-26 23:26:43 +000062 return Init;
Mike Stump1eb44332009-09-09 15:08:12 +000063
Chris Lattnerdd8e0062009-02-24 22:27:37 +000064 return 0;
65}
66
Mike Stump1eb44332009-09-09 15:08:12 +000067static bool CheckSingleInitializer(Expr *&Init, QualType DeclType,
Chris Lattner95e8d652009-02-24 22:46:58 +000068 bool DirectInit, Sema &S) {
Chris Lattnerdd8e0062009-02-24 22:27:37 +000069 // Get the type before calling CheckSingleAssignmentConstraints(), since
70 // it can promote the expression.
Mike Stump1eb44332009-09-09 15:08:12 +000071 QualType InitType = Init->getType();
72
Chris Lattner95e8d652009-02-24 22:46:58 +000073 if (S.getLangOptions().CPlusPlus) {
Chris Lattnerdd8e0062009-02-24 22:27:37 +000074 // FIXME: I dislike this error message. A lot.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +000075 if (S.PerformImplicitConversion(Init, DeclType,
76 "initializing", DirectInit)) {
77 ImplicitConversionSequence ICS;
78 OverloadCandidateSet CandidateSet;
79 if (S.IsUserDefinedConversion(Init, DeclType, ICS.UserDefined,
80 CandidateSet,
Douglas Gregor20093b42009-12-09 23:02:17 +000081 true, false, false) != OR_Ambiguous)
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +000082 return S.Diag(Init->getSourceRange().getBegin(),
83 diag::err_typecheck_convert_incompatible)
84 << DeclType << Init->getType() << "initializing"
85 << Init->getSourceRange();
86 S.Diag(Init->getSourceRange().getBegin(),
87 diag::err_typecheck_convert_ambiguous)
88 << DeclType << Init->getType() << Init->getSourceRange();
89 S.PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
90 return true;
91 }
Chris Lattnerdd8e0062009-02-24 22:27:37 +000092 return false;
93 }
Mike Stump1eb44332009-09-09 15:08:12 +000094
Chris Lattner95e8d652009-02-24 22:46:58 +000095 Sema::AssignConvertType ConvTy =
96 S.CheckSingleAssignmentConstraints(DeclType, Init);
97 return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
Chris Lattnerdd8e0062009-02-24 22:27:37 +000098 InitType, Init, "initializing");
99}
100
Chris Lattner79e079d2009-02-24 23:10:27 +0000101static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
102 // Get the length of the string as parsed.
103 uint64_t StrLength =
104 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
105
Mike Stump1eb44332009-09-09 15:08:12 +0000106
Chris Lattner79e079d2009-02-24 23:10:27 +0000107 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000108 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000109 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000110 // being initialized to a string literal.
111 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000112 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000113 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +0000114 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
115 ConstVal,
116 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000117 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000118 }
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Eli Friedman8718a6a2009-05-29 18:22:49 +0000120 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000121
Eli Friedman8718a6a2009-05-29 18:22:49 +0000122 // C99 6.7.8p14. We have an array of character type with known size. However,
123 // the size may be smaller or larger than the string we are initializing.
124 // FIXME: Avoid truncation for 64-bit length strings.
125 if (StrLength-1 > CAT->getSize().getZExtValue())
126 S.Diag(Str->getSourceRange().getBegin(),
127 diag::warn_initializer_string_for_char_array_too_long)
128 << Str->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Eli Friedman8718a6a2009-05-29 18:22:49 +0000130 // Set the type to the actual size that we are initializing. If we have
131 // something like:
132 // char x[1] = "foo";
133 // then this will set the string literal's type to char[1].
134 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000135}
136
137bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
138 SourceLocation InitLoc,
Anders Carlsson0f5f2c62009-05-30 20:41:30 +0000139 DeclarationName InitEntity, bool DirectInit) {
Mike Stump1eb44332009-09-09 15:08:12 +0000140 if (DeclType->isDependentType() ||
Douglas Gregorcb78d882009-11-19 18:03:26 +0000141 Init->isTypeDependent() || Init->isValueDependent()) {
142 // We have either a dependent type or a type- or value-dependent
143 // initializer, so we don't perform any additional checking at
144 // this point.
145
146 // If the declaration is a non-dependent, incomplete array type
147 // that has an initializer, then its type will be completed once
Douglas Gregor73460a32009-11-19 23:25:22 +0000148 // the initializer is instantiated.
Douglas Gregorcb78d882009-11-19 18:03:26 +0000149 if (!DeclType->isDependentType()) {
150 if (const IncompleteArrayType *ArrayT
151 = Context.getAsIncompleteArrayType(DeclType)) {
Douglas Gregor73460a32009-11-19 23:25:22 +0000152 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
153 if (!ILE->isTypeDependent()) {
154 // Compute the constant array type from the length of the
155 // initializer list.
156 // FIXME: This will be wrong if there are designated
157 // initializations. Good thing they don't exist in C++!
158 llvm::APInt NumElements(Context.getTypeSize(Context.getSizeType()),
159 ILE->getNumInits());
160 llvm::APInt Zero(Context.getTypeSize(Context.getSizeType()), 0);
161 if (NumElements == Zero) {
162 // Sizing an array implicitly to zero is not allowed by ISO C,
163 // but is supported by GNU.
164 Diag(ILE->getLocStart(), diag::ext_typecheck_zero_array_size);
165 }
166
167 DeclType = Context.getConstantArrayType(ArrayT->getElementType(),
168 NumElements,
169 ArrayT->getSizeModifier(),
170 ArrayT->getIndexTypeCVRQualifiers());
171 return false;
172 }
173 }
174
175 // Make the array type-dependent by making it dependently-sized.
Douglas Gregorcb78d882009-11-19 18:03:26 +0000176 DeclType = Context.getDependentSizedArrayType(ArrayT->getElementType(),
177 /*NumElts=*/0,
178 ArrayT->getSizeModifier(),
179 ArrayT->getIndexTypeCVRQualifiers(),
180 SourceRange());
181 }
182 }
183
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000184 return false;
Douglas Gregorcb78d882009-11-19 18:03:26 +0000185 }
Mike Stump1eb44332009-09-09 15:08:12 +0000186
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000187 // C++ [dcl.init.ref]p1:
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000188 // A variable declared to be a T& or T&&, that is "reference to type T"
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000189 // (8.3.2), shall be initialized by an object, or function, of
190 // type T or by an object that can be converted into a T.
191 if (DeclType->isReferenceType())
Douglas Gregor739d8282009-09-23 23:04:10 +0000192 return CheckReferenceInit(Init, DeclType, InitLoc,
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000193 /*SuppressUserConversions=*/false,
194 /*AllowExplicit=*/DirectInit,
195 /*ForceRValue=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000197 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
198 // of unknown size ("[]") or an object type that is not a variable array type.
199 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
200 return Diag(InitLoc, diag::err_variable_object_no_init)
201 << VAT->getSizeExpr()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000202
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000203 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
204 if (!InitList) {
205 // FIXME: Handle wide strings
Chris Lattner79e079d2009-02-24 23:10:27 +0000206 if (Expr *Str = IsStringInit(Init, DeclType, Context)) {
207 CheckStringInit(Str, DeclType, *this);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000208 return false;
209 }
Mike Stump1eb44332009-09-09 15:08:12 +0000210
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000211 // C++ [dcl.init]p14:
212 // -- If the destination type is a (possibly cv-qualified) class
213 // type:
214 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
215 QualType DeclTypeC = Context.getCanonicalType(DeclType);
216 QualType InitTypeC = Context.getCanonicalType(Init->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000217
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000218 // -- If the initialization is direct-initialization, or if it is
219 // copy-initialization where the cv-unqualified version of the
220 // source type is the same class as, or a derived class of, the
221 // class of the destination, constructors are considered.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000222 if ((DeclTypeC.getLocalUnqualifiedType()
223 == InitTypeC.getLocalUnqualifiedType()) ||
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000224 IsDerivedFrom(InitTypeC, DeclTypeC)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000225 const CXXRecordDecl *RD =
Ted Kremenek6217b802009-07-29 21:53:49 +0000226 cast<CXXRecordDecl>(DeclType->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000227
Anders Carlssonbffed8a2009-05-27 16:38:58 +0000228 // No need to make a CXXConstructExpr if both the ctor and dtor are
229 // trivial.
230 if (RD->hasTrivialConstructor() && RD->hasTrivialDestructor())
231 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000232
Douglas Gregor39da0b82009-09-09 23:08:42 +0000233 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
234
Douglas Gregor20093b42009-12-09 23:02:17 +0000235 // FIXME: Poor location information
236 InitializationKind InitKind
237 = InitializationKind::CreateCopy(Init->getLocStart(),
238 SourceLocation());
239 if (DirectInit)
240 InitKind = InitializationKind::CreateDirect(Init->getLocStart(),
241 SourceLocation(),
242 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000243 CXXConstructorDecl *Constructor
Douglas Gregor39da0b82009-09-09 23:08:42 +0000244 = PerformInitializationByConstructor(DeclType,
245 MultiExprArg(*this,
246 (void **)&Init, 1),
247 InitLoc, Init->getSourceRange(),
Douglas Gregor20093b42009-12-09 23:02:17 +0000248 InitEntity, InitKind,
Douglas Gregor39da0b82009-09-09 23:08:42 +0000249 ConstructorArgs);
Anders Carlsson2078bb92009-05-27 16:10:08 +0000250 if (!Constructor)
251 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000252
253 OwningExprResult InitResult =
Anders Carlssonec8e5ea2009-09-05 07:40:38 +0000254 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000255 DeclType, Constructor,
Douglas Gregor39da0b82009-09-09 23:08:42 +0000256 move_arg(ConstructorArgs));
Anders Carlssonda3f4e22009-08-25 05:12:04 +0000257 if (InitResult.isInvalid())
258 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000259
Anders Carlssonda3f4e22009-08-25 05:12:04 +0000260 Init = InitResult.takeAs<Expr>();
Anders Carlsson2078bb92009-05-27 16:10:08 +0000261 return false;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000262 }
Mike Stump1eb44332009-09-09 15:08:12 +0000263
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000264 // -- Otherwise (i.e., for the remaining copy-initialization
265 // cases), user-defined conversion sequences that can
266 // convert from the source type to the destination type or
267 // (when a conversion function is used) to a derived class
268 // thereof are enumerated as described in 13.3.1.4, and the
269 // best one is chosen through overload resolution
270 // (13.3). If the conversion cannot be done or is
271 // ambiguous, the initialization is ill-formed. The
272 // function selected is called with the initializer
273 // expression as its argument; if the function is a
274 // constructor, the call initializes a temporary of the
275 // destination type.
Mike Stump390b4cc2009-05-16 07:39:55 +0000276 // FIXME: We're pretending to do copy elision here; return to this when we
277 // have ASTs for such things.
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000278 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
279 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000281 if (InitEntity)
282 return Diag(InitLoc, diag::err_cannot_initialize_decl)
Chris Lattnerb78d8332009-06-26 04:45:06 +0000283 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
284 << Init->getType() << Init->getSourceRange();
285 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000286 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
287 << Init->getType() << Init->getSourceRange();
288 }
Mike Stump1eb44332009-09-09 15:08:12 +0000289
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000290 // C99 6.7.8p16.
291 if (DeclType->isArrayType())
292 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
Chris Lattnerb78d8332009-06-26 04:45:06 +0000293 << Init->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Chris Lattner95e8d652009-02-24 22:46:58 +0000295 return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
Mike Stump1eb44332009-09-09 15:08:12 +0000296 }
297
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000298 bool hadError = CheckInitList(InitList, DeclType);
299 Init = InitList;
300 return hadError;
301}
302
303//===----------------------------------------------------------------------===//
304// Semantic checking for initializer lists.
305//===----------------------------------------------------------------------===//
306
Douglas Gregor9e80f722009-01-29 01:05:33 +0000307/// @brief Semantic checking for initializer lists.
308///
309/// The InitListChecker class contains a set of routines that each
310/// handle the initialization of a certain kind of entity, e.g.,
311/// arrays, vectors, struct/union types, scalars, etc. The
312/// InitListChecker itself performs a recursive walk of the subobject
313/// structure of the type to be initialized, while stepping through
314/// the initializer list one element at a time. The IList and Index
315/// parameters to each of the Check* routines contain the active
316/// (syntactic) initializer list and the index into that initializer
317/// list that represents the current initializer. Each routine is
318/// responsible for moving that Index forward as it consumes elements.
319///
320/// Each Check* routine also has a StructuredList/StructuredIndex
321/// arguments, which contains the current the "structured" (semantic)
322/// initializer list and the index into that initializer list where we
323/// are copying initializers as we map them over to the semantic
324/// list. Once we have completed our recursive walk of the subobject
325/// structure, we will have constructed a full semantic initializer
326/// list.
327///
328/// C99 designators cause changes in the initializer list traversal,
329/// because they make the initialization "jump" into a specific
330/// subobject and then continue the initialization from that
331/// point. CheckDesignatedInitializer() recursively steps into the
332/// designated subobject and manages backing out the recursion to
333/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000334namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000335class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000336 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000337 bool hadError;
338 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
339 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000340
341 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000342 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000343 unsigned &StructuredIndex,
344 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000345 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000346 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000347 unsigned &StructuredIndex,
348 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000349 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
350 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000351 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000352 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000353 unsigned &StructuredIndex,
354 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000355 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000356 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000357 InitListExpr *StructuredList,
358 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000359 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000360 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000361 InitListExpr *StructuredList,
362 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000363 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000364 unsigned &Index,
365 InitListExpr *StructuredList,
366 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000367 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000368 InitListExpr *StructuredList,
369 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000370 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
371 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000372 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000373 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000374 unsigned &StructuredIndex,
375 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000376 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
377 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000378 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000379 InitListExpr *StructuredList,
380 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000381 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000382 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000383 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000384 RecordDecl::field_iterator *NextField,
385 llvm::APSInt *NextElementIndex,
386 unsigned &Index,
387 InitListExpr *StructuredList,
388 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000389 bool FinishSubobjectInit,
390 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000391 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
392 QualType CurrentObjectType,
393 InitListExpr *StructuredList,
394 unsigned StructuredIndex,
395 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000396 void UpdateStructuredListElement(InitListExpr *StructuredList,
397 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000398 Expr *expr);
399 int numArrayElements(QualType DeclType);
400 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000401
402 void FillInValueInitializations(InitListExpr *ILE);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000403public:
Chris Lattner08202542009-02-24 22:50:46 +0000404 InitListChecker(Sema &S, InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000405 bool HadError() { return hadError; }
406
407 // @brief Retrieves the fully-structured initializer list used for
408 // semantic analysis and code generation.
409 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
410};
Chris Lattner8b419b92009-02-24 22:48:58 +0000411} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000412
Douglas Gregor4c678342009-01-28 21:54:33 +0000413/// Recursively replaces NULL values within the given initializer list
414/// with expressions that perform value-initialization of the
415/// appropriate type.
Douglas Gregor930d8b52009-01-30 22:09:00 +0000416void InitListChecker::FillInValueInitializations(InitListExpr *ILE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000417 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000418 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000419 SourceLocation Loc = ILE->getSourceRange().getBegin();
420 if (ILE->getSyntacticForm())
421 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000422
Ted Kremenek6217b802009-07-29 21:53:49 +0000423 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000424 unsigned Init = 0, NumInits = ILE->getNumInits();
Mike Stump1eb44332009-09-09 15:08:12 +0000425 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000426 Field = RType->getDecl()->field_begin(),
427 FieldEnd = RType->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000428 Field != FieldEnd; ++Field) {
429 if (Field->isUnnamedBitfield())
430 continue;
431
Douglas Gregor87fd7032009-02-02 17:43:21 +0000432 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000433 if (Field->getType()->isReferenceType()) {
434 // C++ [dcl.init.aggr]p9:
435 // If an incomplete or empty initializer-list leaves a
436 // member of reference type uninitialized, the program is
Mike Stump1eb44332009-09-09 15:08:12 +0000437 // ill-formed.
Chris Lattner08202542009-02-24 22:50:46 +0000438 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000439 << Field->getType()
440 << ILE->getSyntacticForm()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000441 SemaRef.Diag(Field->getLocation(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000442 diag::note_uninit_reference_member);
443 hadError = true;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000444 return;
Chris Lattner08202542009-02-24 22:50:46 +0000445 } else if (SemaRef.CheckValueInitialization(Field->getType(), Loc)) {
Douglas Gregor87fd7032009-02-02 17:43:21 +0000446 hadError = true;
447 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000448 }
Douglas Gregor87fd7032009-02-02 17:43:21 +0000449
Mike Stump390b4cc2009-05-16 07:39:55 +0000450 // FIXME: If value-initialization involves calling a constructor, should
451 // we make that call explicit in the representation (even when it means
452 // extending the initializer list)?
Douglas Gregor87fd7032009-02-02 17:43:21 +0000453 if (Init < NumInits && !hadError)
Mike Stump1eb44332009-09-09 15:08:12 +0000454 ILE->setInit(Init,
Chris Lattner08202542009-02-24 22:50:46 +0000455 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +0000456 } else if (InitListExpr *InnerILE
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000457 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000458 FillInValueInitializations(InnerILE);
Douglas Gregor4c678342009-01-28 21:54:33 +0000459 ++Init;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000460
461 // Only look at the first initialization of a union.
462 if (RType->getDecl()->isUnion())
463 break;
Douglas Gregor4c678342009-01-28 21:54:33 +0000464 }
465
466 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000467 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000468
469 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000470
Douglas Gregor87fd7032009-02-02 17:43:21 +0000471 unsigned NumInits = ILE->getNumInits();
472 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000473 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000474 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000475 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
476 NumElements = CAType->getSize().getZExtValue();
John McCall183700f2009-09-21 23:43:11 +0000477 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000478 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000479 NumElements = VType->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +0000480 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000481 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000482
Douglas Gregor87fd7032009-02-02 17:43:21 +0000483 for (unsigned Init = 0; Init != NumElements; ++Init) {
484 if (Init >= NumInits || !ILE->getInit(Init)) {
Chris Lattner08202542009-02-24 22:50:46 +0000485 if (SemaRef.CheckValueInitialization(ElementType, Loc)) {
Douglas Gregor87fd7032009-02-02 17:43:21 +0000486 hadError = true;
487 return;
488 }
489
Mike Stump390b4cc2009-05-16 07:39:55 +0000490 // FIXME: If value-initialization involves calling a constructor, should
491 // we make that call explicit in the representation (even when it means
492 // extending the initializer list)?
Douglas Gregor87fd7032009-02-02 17:43:21 +0000493 if (Init < NumInits && !hadError)
Mike Stump1eb44332009-09-09 15:08:12 +0000494 ILE->setInit(Init,
Chris Lattner08202542009-02-24 22:50:46 +0000495 new (SemaRef.Context) ImplicitValueInitExpr(ElementType));
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000496 } else if (InitListExpr *InnerILE
497 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000498 FillInValueInitializations(InnerILE);
Douglas Gregor4c678342009-01-28 21:54:33 +0000499 }
500}
501
Chris Lattner68355a52009-01-29 05:10:57 +0000502
Chris Lattner08202542009-02-24 22:50:46 +0000503InitListChecker::InitListChecker(Sema &S, InitListExpr *IL, QualType &T)
504 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000505 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000506
Eli Friedmanb85f7072008-05-19 19:16:24 +0000507 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000508 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000509 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000510 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000511 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
512 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000513
Douglas Gregor930d8b52009-01-30 22:09:00 +0000514 if (!hadError)
515 FillInValueInitializations(FullyStructuredList);
Steve Naroff0cca7492008-05-01 22:18:59 +0000516}
517
518int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000519 // FIXME: use a proper constant
520 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000521 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000522 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000523 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
524 }
525 return maxElements;
526}
527
528int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000529 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000530 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000531 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000532 Field = structDecl->field_begin(),
533 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000534 Field != FieldEnd; ++Field) {
535 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
536 ++InitializableMembers;
537 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000538 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000539 return std::min(InitializableMembers, 1);
540 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000541}
542
Mike Stump1eb44332009-09-09 15:08:12 +0000543void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000544 QualType T, unsigned &Index,
545 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000546 unsigned &StructuredIndex,
547 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000548 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000549
Steve Naroff0cca7492008-05-01 22:18:59 +0000550 if (T->isArrayType())
551 maxElements = numArrayElements(T);
552 else if (T->isStructureType() || T->isUnionType())
553 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000554 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000555 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000556 else
557 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000558
Eli Friedman402256f2008-05-25 13:49:22 +0000559 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000560 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000561 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000562 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000563 hadError = true;
564 return;
565 }
566
Douglas Gregor4c678342009-01-28 21:54:33 +0000567 // Build a structured initializer list corresponding to this subobject.
568 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000569 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
570 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000571 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
572 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000573 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000574
Douglas Gregor4c678342009-01-28 21:54:33 +0000575 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000576 unsigned StartIndex = Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000577 CheckListElementTypes(ParentIList, T, false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000578 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000579 StructuredSubobjectInitIndex,
580 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000581 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000582 StructuredSubobjectInitList->setType(T);
583
Douglas Gregored8a93d2009-03-01 17:12:46 +0000584 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000585 // range corresponds with the end of the last initializer it used.
586 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000587 SourceLocation EndLoc
Douglas Gregor87fd7032009-02-02 17:43:21 +0000588 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
589 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
590 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000591}
592
Steve Naroffa647caa2008-05-06 00:23:44 +0000593void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000594 unsigned &Index,
595 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000596 unsigned &StructuredIndex,
597 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000598 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000599 SyntacticToSemantic[IList] = StructuredList;
600 StructuredList->setSyntacticForm(IList);
Mike Stump1eb44332009-09-09 15:08:12 +0000601 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000602 StructuredIndex, TopLevelObject);
Steve Naroffa647caa2008-05-06 00:23:44 +0000603 IList->setType(T);
Douglas Gregor4c678342009-01-28 21:54:33 +0000604 StructuredList->setType(T);
Eli Friedman638e1442008-05-25 13:22:35 +0000605 if (hadError)
606 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000607
Eli Friedman638e1442008-05-25 13:22:35 +0000608 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000609 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000610 if (StructuredIndex == 1 &&
611 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000612 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000613 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000614 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000615 hadError = true;
616 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000617 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000618 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000619 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000620 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000621 // Don't complain for incomplete types, since we'll get an error
622 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000623 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000624 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000625 CurrentObjectType->isArrayType()? 0 :
626 CurrentObjectType->isVectorType()? 1 :
627 CurrentObjectType->isScalarType()? 2 :
628 CurrentObjectType->isUnionType()? 3 :
629 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000630
631 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000632 if (SemaRef.getLangOptions().CPlusPlus) {
633 DK = diag::err_excess_initializers;
634 hadError = true;
635 }
Nate Begeman08634522009-07-07 21:53:06 +0000636 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
637 DK = diag::err_excess_initializers;
638 hadError = true;
639 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000640
Chris Lattner08202542009-02-24 22:50:46 +0000641 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000642 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000643 }
644 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000645
Eli Friedman759f2522009-05-16 11:45:48 +0000646 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000647 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000648 << IList->getSourceRange()
Chris Lattner29d9c1a2009-12-06 17:36:05 +0000649 << CodeModificationHint::CreateRemoval(IList->getLocStart())
650 << CodeModificationHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000651}
652
Eli Friedmanb85f7072008-05-19 19:16:24 +0000653void InitListChecker::CheckListElementTypes(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000654 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000655 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000656 unsigned &Index,
657 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000658 unsigned &StructuredIndex,
659 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000660 if (DeclType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000661 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000662 } else if (DeclType->isVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000663 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000664 } else if (DeclType->isAggregateType()) {
665 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000666 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000667 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000668 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000669 StructuredList, StructuredIndex,
670 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000671 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000672 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000673 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000674 false);
Douglas Gregor4c678342009-01-28 21:54:33 +0000675 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
676 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000677 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000678 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000679 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
680 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000681 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000682 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000683 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000684 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000685 } else if (DeclType->isRecordType()) {
686 // C++ [dcl.init]p14:
687 // [...] If the class is an aggregate (8.5.1), and the initializer
688 // is a brace-enclosed list, see 8.5.1.
689 //
690 // Note: 8.5.1 is handled below; here, we diagnose the case where
691 // we have an initializer list and a destination type that is not
692 // an aggregate.
693 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000694 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000695 << DeclType << IList->getSourceRange();
696 hadError = true;
697 } else if (DeclType->isReferenceType()) {
698 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000699 } else {
700 // In C, all types are either scalars or aggregates, but
Mike Stump1eb44332009-09-09 15:08:12 +0000701 // additional handling is needed here for C++ (and possibly others?).
Steve Naroff0cca7492008-05-01 22:18:59 +0000702 assert(0 && "Unsupported initializer type");
703 }
704}
705
Eli Friedmanb85f7072008-05-19 19:16:24 +0000706void InitListChecker::CheckSubElementType(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000707 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000708 unsigned &Index,
709 InitListExpr *StructuredList,
710 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000711 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000712 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
713 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000714 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000715 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000716 = getStructuredSubobjectInit(IList, Index, ElemType,
717 StructuredList, StructuredIndex,
718 SubInitList->getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +0000719 CheckExplicitInitList(SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000720 newStructuredList, newStructuredIndex);
721 ++StructuredIndex;
722 ++Index;
Chris Lattner79e079d2009-02-24 23:10:27 +0000723 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
724 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000725 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000726 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000727 } else if (ElemType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000728 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000729 } else if (ElemType->isReferenceType()) {
730 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000731 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000732 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000733 // C++ [dcl.init.aggr]p12:
734 // All implicit type conversions (clause 4) are considered when
735 // initializing the aggregate member with an ini- tializer from
736 // an initializer-list. If the initializer can initialize a
737 // member, the member is initialized. [...]
Mike Stump1eb44332009-09-09 15:08:12 +0000738 ImplicitConversionSequence ICS
Anders Carlssond28b4282009-08-27 17:18:13 +0000739 = SemaRef.TryCopyInitialization(expr, ElemType,
740 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +0000741 /*ForceRValue=*/false,
742 /*InOverloadResolution=*/false);
Anders Carlssond28b4282009-08-27 17:18:13 +0000743
Douglas Gregor930d8b52009-01-30 22:09:00 +0000744 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Mike Stump1eb44332009-09-09 15:08:12 +0000745 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000746 "initializing"))
747 hadError = true;
748 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
749 ++Index;
750 return;
751 }
752
753 // Fall through for subaggregate initialization
754 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000755 // C99 6.7.8p13:
Douglas Gregor930d8b52009-01-30 22:09:00 +0000756 //
757 // The initializer for a structure or union object that has
758 // automatic storage duration shall be either an initializer
759 // list as described below, or a single expression that has
760 // compatible structure or union type. In the latter case, the
761 // initial value of the object, including unnamed members, is
762 // that of the expression.
Eli Friedman6b5374f2009-06-13 10:38:46 +0000763 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman8718a6a2009-05-29 18:22:49 +0000764 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000765 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
766 ++Index;
767 return;
768 }
769
770 // Fall through for subaggregate initialization
771 }
772
773 // C++ [dcl.init.aggr]p12:
Mike Stump1eb44332009-09-09 15:08:12 +0000774 //
Douglas Gregor930d8b52009-01-30 22:09:00 +0000775 // [...] Otherwise, if the member is itself a non-empty
776 // subaggregate, brace elision is assumed and the initializer is
777 // considered for the initialization of the first member of
778 // the subaggregate.
779 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000780 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000781 StructuredIndex);
782 ++StructuredIndex;
783 } else {
784 // We cannot initialize this element, so let
785 // PerformCopyInitialization produce the appropriate diagnostic.
Chris Lattner08202542009-02-24 22:50:46 +0000786 SemaRef.PerformCopyInitialization(expr, ElemType, "initializing");
Douglas Gregor930d8b52009-01-30 22:09:00 +0000787 hadError = true;
788 ++Index;
789 ++StructuredIndex;
790 }
791 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000792}
793
Douglas Gregor930d8b52009-01-30 22:09:00 +0000794void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000795 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000796 InitListExpr *StructuredList,
797 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000798 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000799 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000800 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000801 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000802 diag::err_many_braces_around_scalar_init)
803 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000804 hadError = true;
805 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000806 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000807 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000808 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000809 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor05c13a32009-01-22 00:58:24 +0000810 diag::err_designator_for_scalar_init)
811 << DeclType << expr->getSourceRange();
812 hadError = true;
813 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000814 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000815 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000816 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000817
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000818 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner08202542009-02-24 22:50:46 +0000819 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedmanbb504d32008-05-19 20:12:18 +0000820 hadError = true; // types weren't compatible.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000821 else if (savExpr != expr) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000822 // The type was promoted, update initializer list.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000823 IList->setInit(Index, expr);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000824 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000825 if (hadError)
826 ++StructuredIndex;
827 else
828 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000829 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000830 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000831 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000832 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000833 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000834 ++Index;
835 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000836 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000837 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000838}
839
Douglas Gregor930d8b52009-01-30 22:09:00 +0000840void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
841 unsigned &Index,
842 InitListExpr *StructuredList,
843 unsigned &StructuredIndex) {
844 if (Index < IList->getNumInits()) {
845 Expr *expr = IList->getInit(Index);
846 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000847 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000848 << DeclType << IList->getSourceRange();
849 hadError = true;
850 ++Index;
851 ++StructuredIndex;
852 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000853 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000854
855 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000856 if (SemaRef.CheckReferenceInit(expr, DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +0000857 /*FIXME:*/expr->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000858 /*SuppressUserConversions=*/false,
859 /*AllowExplicit=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +0000860 /*ForceRValue=*/false))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000861 hadError = true;
862 else if (savExpr != expr) {
863 // The type was promoted, update initializer list.
864 IList->setInit(Index, expr);
865 }
866 if (hadError)
867 ++StructuredIndex;
868 else
869 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
870 ++Index;
871 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000872 // FIXME: It would be wonderful if we could point at the actual member. In
873 // general, it would be useful to pass location information down the stack,
874 // so that we know the location (or decl) of the "current object" being
875 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000876 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000877 diag::err_init_reference_member_uninitialized)
878 << DeclType
879 << IList->getSourceRange();
880 hadError = true;
881 ++Index;
882 ++StructuredIndex;
883 return;
884 }
885}
886
Mike Stump1eb44332009-09-09 15:08:12 +0000887void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000888 unsigned &Index,
889 InitListExpr *StructuredList,
890 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000891 if (Index < IList->getNumInits()) {
John McCall183700f2009-09-21 23:43:11 +0000892 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000893 unsigned maxElements = VT->getNumElements();
894 unsigned numEltsInit = 0;
Steve Naroff0cca7492008-05-01 22:18:59 +0000895 QualType elementType = VT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +0000896
Nate Begeman2ef13e52009-08-10 23:49:36 +0000897 if (!SemaRef.getLangOptions().OpenCL) {
898 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
899 // Don't attempt to go past the end of the init list
900 if (Index >= IList->getNumInits())
901 break;
902 CheckSubElementType(IList, elementType, Index,
903 StructuredList, StructuredIndex);
904 }
905 } else {
906 // OpenCL initializers allows vectors to be constructed from vectors.
907 for (unsigned i = 0; i < maxElements; ++i) {
908 // Don't attempt to go past the end of the init list
909 if (Index >= IList->getNumInits())
910 break;
911 QualType IType = IList->getInit(Index)->getType();
912 if (!IType->isVectorType()) {
913 CheckSubElementType(IList, elementType, Index,
914 StructuredList, StructuredIndex);
915 ++numEltsInit;
916 } else {
John McCall183700f2009-09-21 23:43:11 +0000917 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000918 unsigned numIElts = IVT->getNumElements();
919 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
920 numIElts);
921 CheckSubElementType(IList, VecType, Index,
922 StructuredList, StructuredIndex);
923 numEltsInit += numIElts;
924 }
925 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000926 }
Mike Stump1eb44332009-09-09 15:08:12 +0000927
Nate Begeman2ef13e52009-08-10 23:49:36 +0000928 // OpenCL & AltiVec require all elements to be initialized.
929 if (numEltsInit != maxElements)
930 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
931 SemaRef.Diag(IList->getSourceRange().getBegin(),
932 diag::err_vector_incorrect_num_initializers)
933 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +0000934 }
935}
936
Mike Stump1eb44332009-09-09 15:08:12 +0000937void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000938 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +0000939 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000940 unsigned &Index,
941 InitListExpr *StructuredList,
942 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000943 // Check for the special-case of initializing an array with a string.
944 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000945 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
946 SemaRef.Context)) {
947 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +0000948 // We place the string literal directly into the resulting
949 // initializer list. This is the only place where the structure
950 // of the structured initializer list doesn't match exactly,
951 // because doing so would involve allocating one character
952 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000953 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +0000954 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000955 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000956 return;
957 }
958 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000959 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +0000960 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000961 // Check for VLAs; in standard C it would be possible to check this
962 // earlier, but I don't know where clang accepts VLAs (gcc accepts
963 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +0000964 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000965 diag::err_variable_object_no_init)
966 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000967 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000968 ++Index;
969 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000970 return;
971 }
972
Douglas Gregor05c13a32009-01-22 00:58:24 +0000973 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000974 llvm::APSInt maxElements(elementIndex.getBitWidth(),
975 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000976 bool maxElementsKnown = false;
977 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000978 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000979 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000980 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000981 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000982 maxElementsKnown = true;
983 }
984
Chris Lattner08202542009-02-24 22:50:46 +0000985 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000986 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000987 while (Index < IList->getNumInits()) {
988 Expr *Init = IList->getInit(Index);
989 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000990 // If we're not the subobject that matches up with the '{' for
991 // the designator, we shouldn't be handling the
992 // designator. Return immediately.
993 if (!SubobjectIsDesignatorContext)
994 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000995
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000996 // Handle this designated initializer. elementIndex will be
997 // updated to be the next array element we'll initialize.
Mike Stump1eb44332009-09-09 15:08:12 +0000998 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +0000999 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001000 StructuredList, StructuredIndex, true,
1001 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001002 hadError = true;
1003 continue;
1004 }
1005
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001006 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1007 maxElements.extend(elementIndex.getBitWidth());
1008 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1009 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001010 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001011
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001012 // If the array is of incomplete type, keep track of the number of
1013 // elements in the initializer.
1014 if (!maxElementsKnown && elementIndex > maxElements)
1015 maxElements = elementIndex;
1016
Douglas Gregor05c13a32009-01-22 00:58:24 +00001017 continue;
1018 }
1019
1020 // If we know the maximum number of elements, and we've already
1021 // hit it, stop consuming elements in the initializer list.
1022 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001023 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001024
1025 // Check this element.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001026 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001027 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001028 ++elementIndex;
1029
1030 // If the array is of incomplete type, keep track of the number of
1031 // elements in the initializer.
1032 if (!maxElementsKnown && elementIndex > maxElements)
1033 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001034 }
Eli Friedman587cbdf2009-05-29 20:17:55 +00001035 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001036 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001037 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001038 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001039 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001040 // Sizing an array implicitly to zero is not allowed by ISO C,
1041 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001042 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001043 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001044 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001045
Mike Stump1eb44332009-09-09 15:08:12 +00001046 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001047 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001048 }
1049}
1050
Mike Stump1eb44332009-09-09 15:08:12 +00001051void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
1052 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001053 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001054 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001055 unsigned &Index,
1056 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001057 unsigned &StructuredIndex,
1058 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001059 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001060
Eli Friedmanb85f7072008-05-19 19:16:24 +00001061 // If the record is invalid, some of it's members are invalid. To avoid
1062 // confusion, we forgo checking the intializer for the entire record.
1063 if (structDecl->isInvalidDecl()) {
1064 hadError = true;
1065 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001066 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001067
1068 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1069 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001070 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001071 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001072 Field != FieldEnd; ++Field) {
1073 if (Field->getDeclName()) {
1074 StructuredList->setInitializedFieldInUnion(*Field);
1075 break;
1076 }
1077 }
1078 return;
1079 }
1080
Douglas Gregor05c13a32009-01-22 00:58:24 +00001081 // If structDecl is a forward declaration, this loop won't do
1082 // anything except look at designated initializers; That's okay,
1083 // because an error should get printed out elsewhere. It might be
1084 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001085 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001086 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001087 bool InitializedSomething = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001088 while (Index < IList->getNumInits()) {
1089 Expr *Init = IList->getInit(Index);
1090
1091 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001092 // If we're not the subobject that matches up with the '{' for
1093 // the designator, we shouldn't be handling the
1094 // designator. Return immediately.
1095 if (!SubobjectIsDesignatorContext)
1096 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001097
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001098 // Handle this designated initializer. Field will be updated to
1099 // the next field that we'll be initializing.
Mike Stump1eb44332009-09-09 15:08:12 +00001100 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001101 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001102 StructuredList, StructuredIndex,
1103 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001104 hadError = true;
1105
Douglas Gregordfb5e592009-02-12 19:00:39 +00001106 InitializedSomething = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001107 continue;
1108 }
1109
1110 if (Field == FieldEnd) {
1111 // We've run out of fields. We're done.
1112 break;
1113 }
1114
Douglas Gregordfb5e592009-02-12 19:00:39 +00001115 // We've already initialized a member of a union. We're done.
1116 if (InitializedSomething && DeclType->isUnionType())
1117 break;
1118
Douglas Gregor44b43212008-12-11 16:49:14 +00001119 // If we've hit the flexible array member at the end, we're done.
1120 if (Field->getType()->isIncompleteArrayType())
1121 break;
1122
Douglas Gregor0bb76892009-01-29 16:53:55 +00001123 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001124 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001125 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001126 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001127 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001128
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001129 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001130 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001131 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001132
1133 if (DeclType->isUnionType()) {
1134 // Initialize the first field within the union.
1135 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001136 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001137
1138 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001139 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001140
Mike Stump1eb44332009-09-09 15:08:12 +00001141 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001142 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001143 return;
1144
1145 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001146 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001147 (!isa<InitListExpr>(IList->getInit(Index)) ||
1148 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001149 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001150 diag::err_flexible_array_init_nonempty)
1151 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001152 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001153 << *Field;
1154 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001155 ++Index;
1156 return;
1157 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001158 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001159 diag::ext_flexible_array_init)
1160 << IList->getInit(Index)->getSourceRange().getBegin();
1161 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1162 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001163 }
1164
Douglas Gregora6457962009-03-20 00:32:56 +00001165 if (isa<InitListExpr>(IList->getInit(Index)))
1166 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1167 StructuredIndex);
1168 else
1169 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1170 StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001171}
Steve Naroff0cca7492008-05-01 22:18:59 +00001172
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001173/// \brief Expand a field designator that refers to a member of an
1174/// anonymous struct or union into a series of field designators that
1175/// refers to the field within the appropriate subobject.
1176///
1177/// Field/FieldIndex will be updated to point to the (new)
1178/// currently-designated field.
1179static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001180 DesignatedInitExpr *DIE,
1181 unsigned DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001182 FieldDecl *Field,
1183 RecordDecl::field_iterator &FieldIter,
1184 unsigned &FieldIndex) {
1185 typedef DesignatedInitExpr::Designator Designator;
1186
1187 // Build the path from the current object to the member of the
1188 // anonymous struct/union (backwards).
1189 llvm::SmallVector<FieldDecl *, 4> Path;
1190 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump1eb44332009-09-09 15:08:12 +00001191
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001192 // Build the replacement designators.
1193 llvm::SmallVector<Designator, 4> Replacements;
1194 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1195 FI = Path.rbegin(), FIEnd = Path.rend();
1196 FI != FIEnd; ++FI) {
1197 if (FI + 1 == FIEnd)
Mike Stump1eb44332009-09-09 15:08:12 +00001198 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001199 DIE->getDesignator(DesigIdx)->getDotLoc(),
1200 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1201 else
1202 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1203 SourceLocation()));
1204 Replacements.back().setField(*FI);
1205 }
1206
1207 // Expand the current designator into the set of replacement
1208 // designators, so we have a full subobject path down to where the
1209 // member of the anonymous struct/union is actually stored.
Mike Stump1eb44332009-09-09 15:08:12 +00001210 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001211 &Replacements[0] + Replacements.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001212
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001213 // Update FieldIter/FieldIndex;
1214 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001215 FieldIter = Record->field_begin();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001216 FieldIndex = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001217 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001218 FieldIter != FEnd; ++FieldIter) {
1219 if (FieldIter->isUnnamedBitfield())
1220 continue;
1221
1222 if (*FieldIter == Path.back())
1223 return;
1224
1225 ++FieldIndex;
1226 }
1227
1228 assert(false && "Unable to find anonymous struct/union field");
1229}
1230
Douglas Gregor05c13a32009-01-22 00:58:24 +00001231/// @brief Check the well-formedness of a C99 designated initializer.
1232///
1233/// Determines whether the designated initializer @p DIE, which
1234/// resides at the given @p Index within the initializer list @p
1235/// IList, is well-formed for a current object of type @p DeclType
1236/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001237/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001238/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001239///
1240/// @param IList The initializer list in which this designated
1241/// initializer occurs.
1242///
Douglas Gregor71199712009-04-15 04:56:10 +00001243/// @param DIE The designated initializer expression.
1244///
1245/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001246///
1247/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1248/// into which the designation in @p DIE should refer.
1249///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001250/// @param NextField If non-NULL and the first designator in @p DIE is
1251/// a field, this will be set to the field declaration corresponding
1252/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001253///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001254/// @param NextElementIndex If non-NULL and the first designator in @p
1255/// DIE is an array designator or GNU array-range designator, this
1256/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001257///
1258/// @param Index Index into @p IList where the designated initializer
1259/// @p DIE occurs.
1260///
Douglas Gregor4c678342009-01-28 21:54:33 +00001261/// @param StructuredList The initializer list expression that
1262/// describes all of the subobject initializers in the order they'll
1263/// actually be initialized.
1264///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001265/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001266bool
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001267InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001268 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001269 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001270 QualType &CurrentObjectType,
1271 RecordDecl::field_iterator *NextField,
1272 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001273 unsigned &Index,
1274 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001275 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001276 bool FinishSubobjectInit,
1277 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001278 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001279 // Check the actual initialization for the designated object type.
1280 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001281
1282 // Temporarily remove the designator expression from the
1283 // initializer list that the child calls see, so that we don't try
1284 // to re-process the designator.
1285 unsigned OldIndex = Index;
1286 IList->setInit(OldIndex, DIE->getInit());
1287
1288 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001289 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001290
1291 // Restore the designated initializer expression in the syntactic
1292 // form of the initializer list.
1293 if (IList->getInit(OldIndex) != DIE->getInit())
1294 DIE->setInit(IList->getInit(OldIndex));
1295 IList->setInit(OldIndex, DIE);
1296
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001297 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001298 }
1299
Douglas Gregor71199712009-04-15 04:56:10 +00001300 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001301 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001302 "Need a non-designated initializer list to start from");
1303
Douglas Gregor71199712009-04-15 04:56:10 +00001304 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001305 // Determine the structural initializer list that corresponds to the
1306 // current subobject.
1307 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001308 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001309 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001310 SourceRange(D->getStartLocation(),
1311 DIE->getSourceRange().getEnd()));
1312 assert(StructuredList && "Expected a structured initializer list");
1313
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001314 if (D->isFieldDesignator()) {
1315 // C99 6.7.8p7:
1316 //
1317 // If a designator has the form
1318 //
1319 // . identifier
1320 //
1321 // then the current object (defined below) shall have
1322 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001323 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001324 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001325 if (!RT) {
1326 SourceLocation Loc = D->getDotLoc();
1327 if (Loc.isInvalid())
1328 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001329 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1330 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001331 ++Index;
1332 return true;
1333 }
1334
Douglas Gregor4c678342009-01-28 21:54:33 +00001335 // Note: we perform a linear search of the fields here, despite
1336 // the fact that we have a faster lookup method, because we always
1337 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001338 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001339 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001340 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001341 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001342 Field = RT->getDecl()->field_begin(),
1343 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001344 for (; Field != FieldEnd; ++Field) {
1345 if (Field->isUnnamedBitfield())
1346 continue;
1347
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001348 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor4c678342009-01-28 21:54:33 +00001349 break;
1350
1351 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001352 }
1353
Douglas Gregor4c678342009-01-28 21:54:33 +00001354 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001355 // There was no normal field in the struct with the designated
1356 // name. Perform another lookup for this name, which may find
1357 // something that we can't designate (e.g., a member function),
1358 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001359 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001360 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4c678342009-01-28 21:54:33 +00001361 if (Lookup.first == Lookup.second) {
1362 // Name lookup didn't find anything.
Chris Lattner08202542009-02-24 22:50:46 +00001363 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregor4c678342009-01-28 21:54:33 +00001364 << FieldName << CurrentObjectType;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001365 ++Index;
1366 return true;
1367 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1368 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1369 ->isAnonymousStructOrUnion()) {
1370 // Handle an field designator that refers to a member of an
1371 // anonymous struct or union.
Mike Stump1eb44332009-09-09 15:08:12 +00001372 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001373 cast<FieldDecl>(*Lookup.first),
1374 Field, FieldIndex);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001375 D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001376 } else {
1377 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001378 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001379 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001380 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001381 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001382 ++Index;
1383 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001384 }
1385 } else if (!KnownField &&
1386 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor4c678342009-01-28 21:54:33 +00001387 ->isAnonymousStructOrUnion()) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001388 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1389 Field, FieldIndex);
1390 D = DIE->getDesignator(DesigIdx);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001391 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001392
1393 // All of the fields of a union are located at the same place in
1394 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001395 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001396 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001397 StructuredList->setInitializedFieldInUnion(*Field);
1398 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001399
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001400 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001401 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001402
Douglas Gregor4c678342009-01-28 21:54:33 +00001403 // Make sure that our non-designated initializer list has space
1404 // for a subobject corresponding to this field.
1405 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001406 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001407
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001408 // This designator names a flexible array member.
1409 if (Field->getType()->isIncompleteArrayType()) {
1410 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001411 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001412 // We can't designate an object within the flexible array
1413 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001414 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001415 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001416 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001417 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001418 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001419 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001420 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001421 << *Field;
1422 Invalid = true;
1423 }
1424
1425 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1426 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001427 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001428 diag::err_flexible_array_init_needs_braces)
1429 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001430 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001431 << *Field;
1432 Invalid = true;
1433 }
1434
1435 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001436 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001437 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001438 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001439 diag::err_flexible_array_init_nonempty)
1440 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001441 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001442 << *Field;
1443 Invalid = true;
1444 }
1445
1446 if (Invalid) {
1447 ++Index;
1448 return true;
1449 }
1450
1451 // Initialize the array.
1452 bool prevHadError = hadError;
1453 unsigned newStructuredIndex = FieldIndex;
1454 unsigned OldIndex = Index;
1455 IList->setInit(Index, DIE->getInit());
Mike Stump1eb44332009-09-09 15:08:12 +00001456 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001457 StructuredList, newStructuredIndex);
1458 IList->setInit(OldIndex, DIE);
1459 if (hadError && !prevHadError) {
1460 ++Field;
1461 ++FieldIndex;
1462 if (NextField)
1463 *NextField = Field;
1464 StructuredIndex = FieldIndex;
1465 return true;
1466 }
1467 } else {
1468 // Recurse to check later designated subobjects.
1469 QualType FieldType = (*Field)->getType();
1470 unsigned newStructuredIndex = FieldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001471 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1472 Index, StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001473 true, false))
1474 return true;
1475 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001476
1477 // Find the position of the next field to be initialized in this
1478 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001479 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001480 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001481
1482 // If this the first designator, our caller will continue checking
1483 // the rest of this struct/class/union subobject.
1484 if (IsFirstDesignator) {
1485 if (NextField)
1486 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001487 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001488 return false;
1489 }
1490
Douglas Gregor34e79462009-01-28 23:36:17 +00001491 if (!FinishSubobjectInit)
1492 return false;
1493
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001494 // We've already initialized something in the union; we're done.
1495 if (RT->getDecl()->isUnion())
1496 return hadError;
1497
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001498 // Check the remaining fields within this class/struct/union subobject.
1499 bool prevHadError = hadError;
Douglas Gregor4c678342009-01-28 21:54:33 +00001500 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1501 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001502 return hadError && !prevHadError;
1503 }
1504
1505 // C99 6.7.8p6:
1506 //
1507 // If a designator has the form
1508 //
1509 // [ constant-expression ]
1510 //
1511 // then the current object (defined below) shall have array
1512 // type and the expression shall be an integer constant
1513 // expression. If the array is of unknown size, any
1514 // nonnegative value is valid.
1515 //
1516 // Additionally, cope with the GNU extension that permits
1517 // designators of the form
1518 //
1519 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001520 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001521 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001522 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001523 << CurrentObjectType;
1524 ++Index;
1525 return true;
1526 }
1527
1528 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001529 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1530 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001531 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001532 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001533 DesignatedEndIndex = DesignatedStartIndex;
1534 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001535 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001536
Mike Stump1eb44332009-09-09 15:08:12 +00001537
1538 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001539 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001540 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001541 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001542 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001543
Chris Lattner3bf68932009-04-25 21:59:05 +00001544 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001545 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001546 }
1547
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001548 if (isa<ConstantArrayType>(AT)) {
1549 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001550 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1551 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1552 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1553 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1554 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001555 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001556 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001557 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001558 << IndexExpr->getSourceRange();
1559 ++Index;
1560 return true;
1561 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001562 } else {
1563 // Make sure the bit-widths and signedness match.
1564 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1565 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001566 else if (DesignatedStartIndex.getBitWidth() <
1567 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001568 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1569 DesignatedStartIndex.setIsUnsigned(true);
1570 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001571 }
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Douglas Gregor4c678342009-01-28 21:54:33 +00001573 // Make sure that our non-designated initializer list has space
1574 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001575 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001576 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001577 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001578
Douglas Gregor34e79462009-01-28 23:36:17 +00001579 // Repeatedly perform subobject initializations in the range
1580 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001581
Douglas Gregor34e79462009-01-28 23:36:17 +00001582 // Move to the next designator
1583 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1584 unsigned OldIndex = Index;
Douglas Gregor34e79462009-01-28 23:36:17 +00001585 while (DesignatedStartIndex <= DesignatedEndIndex) {
1586 // Recurse to check later designated subobjects.
1587 QualType ElementType = AT->getElementType();
1588 Index = OldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001589 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1590 Index, StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001591 (DesignatedStartIndex == DesignatedEndIndex),
1592 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001593 return true;
1594
1595 // Move to the next index in the array that we'll be initializing.
1596 ++DesignatedStartIndex;
1597 ElementIndex = DesignatedStartIndex.getZExtValue();
1598 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001599
1600 // If this the first designator, our caller will continue checking
1601 // the rest of this array subobject.
1602 if (IsFirstDesignator) {
1603 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001604 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001605 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001606 return false;
1607 }
Mike Stump1eb44332009-09-09 15:08:12 +00001608
Douglas Gregor34e79462009-01-28 23:36:17 +00001609 if (!FinishSubobjectInit)
1610 return false;
1611
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001612 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001613 bool prevHadError = hadError;
Douglas Gregorfdf55692009-02-09 19:45:19 +00001614 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001615 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001616 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001617}
1618
Douglas Gregor4c678342009-01-28 21:54:33 +00001619// Get the structured initializer list for a subobject of type
1620// @p CurrentObjectType.
1621InitListExpr *
1622InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1623 QualType CurrentObjectType,
1624 InitListExpr *StructuredList,
1625 unsigned StructuredIndex,
1626 SourceRange InitRange) {
1627 Expr *ExistingInit = 0;
1628 if (!StructuredList)
1629 ExistingInit = SyntacticToSemantic[IList];
1630 else if (StructuredIndex < StructuredList->getNumInits())
1631 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001632
Douglas Gregor4c678342009-01-28 21:54:33 +00001633 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1634 return Result;
1635
1636 if (ExistingInit) {
1637 // We are creating an initializer list that initializes the
1638 // subobjects of the current object, but there was already an
1639 // initialization that completely initialized the current
1640 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001641 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001642 // struct X { int a, b; };
1643 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001644 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001645 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1646 // designated initializer re-initializes the whole
1647 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001648 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001649 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001650 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001651 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001652 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001653 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001654 << ExistingInit->getSourceRange();
1655 }
1656
Mike Stump1eb44332009-09-09 15:08:12 +00001657 InitListExpr *Result
1658 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001659 InitRange.getEnd());
1660
Douglas Gregor4c678342009-01-28 21:54:33 +00001661 Result->setType(CurrentObjectType);
1662
Douglas Gregorfa219202009-03-20 23:58:33 +00001663 // Pre-allocate storage for the structured initializer list.
1664 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001665 unsigned NumInits = 0;
1666 if (!StructuredList)
1667 NumInits = IList->getNumInits();
1668 else if (Index < IList->getNumInits()) {
1669 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1670 NumInits = SubList->getNumInits();
1671 }
1672
Mike Stump1eb44332009-09-09 15:08:12 +00001673 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001674 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1675 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1676 NumElements = CAType->getSize().getZExtValue();
1677 // Simple heuristic so that we don't allocate a very large
1678 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001679 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001680 NumElements = 0;
1681 }
John McCall183700f2009-09-21 23:43:11 +00001682 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001683 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001684 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001685 RecordDecl *RDecl = RType->getDecl();
1686 if (RDecl->isUnion())
1687 NumElements = 1;
1688 else
Mike Stump1eb44332009-09-09 15:08:12 +00001689 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001690 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001691 }
1692
Douglas Gregor08457732009-03-21 18:13:52 +00001693 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001694 NumElements = IList->getNumInits();
1695
1696 Result->reserveInits(NumElements);
1697
Douglas Gregor4c678342009-01-28 21:54:33 +00001698 // Link this new initializer list into the structured initializer
1699 // lists.
1700 if (StructuredList)
1701 StructuredList->updateInit(StructuredIndex, Result);
1702 else {
1703 Result->setSyntacticForm(IList);
1704 SyntacticToSemantic[IList] = Result;
1705 }
1706
1707 return Result;
1708}
1709
1710/// Update the initializer at index @p StructuredIndex within the
1711/// structured initializer list to the value @p expr.
1712void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1713 unsigned &StructuredIndex,
1714 Expr *expr) {
1715 // No structured initializer list to update
1716 if (!StructuredList)
1717 return;
1718
1719 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1720 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001721 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001722 diag::warn_initializer_overrides)
1723 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001724 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001725 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001726 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001727 << PrevInit->getSourceRange();
1728 }
Mike Stump1eb44332009-09-09 15:08:12 +00001729
Douglas Gregor4c678342009-01-28 21:54:33 +00001730 ++StructuredIndex;
1731}
1732
Douglas Gregor05c13a32009-01-22 00:58:24 +00001733/// Check that the given Index expression is a valid array designator
1734/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001735/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001736/// and produces a reasonable diagnostic if there is a
1737/// failure. Returns true if there was an error, false otherwise. If
1738/// everything went okay, Value will receive the value of the constant
1739/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001740static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001741CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001742 SourceLocation Loc = Index->getSourceRange().getBegin();
1743
1744 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001745 if (S.VerifyIntegerConstantExpression(Index, &Value))
1746 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001747
Chris Lattner3bf68932009-04-25 21:59:05 +00001748 if (Value.isSigned() && Value.isNegative())
1749 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001750 << Value.toString(10) << Index->getSourceRange();
1751
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001752 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001753 return false;
1754}
1755
1756Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1757 SourceLocation Loc,
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001758 bool GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001759 OwningExprResult Init) {
1760 typedef DesignatedInitExpr::Designator ASTDesignator;
1761
1762 bool Invalid = false;
1763 llvm::SmallVector<ASTDesignator, 32> Designators;
1764 llvm::SmallVector<Expr *, 32> InitExpressions;
1765
1766 // Build designators and check array designator expressions.
1767 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1768 const Designator &D = Desig.getDesignator(Idx);
1769 switch (D.getKind()) {
1770 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001771 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001772 D.getFieldLoc()));
1773 break;
1774
1775 case Designator::ArrayDesignator: {
1776 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1777 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001778 if (!Index->isTypeDependent() &&
1779 !Index->isValueDependent() &&
1780 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001781 Invalid = true;
1782 else {
1783 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001784 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001785 D.getRBracketLoc()));
1786 InitExpressions.push_back(Index);
1787 }
1788 break;
1789 }
1790
1791 case Designator::ArrayRangeDesignator: {
1792 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1793 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1794 llvm::APSInt StartValue;
1795 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001796 bool StartDependent = StartIndex->isTypeDependent() ||
1797 StartIndex->isValueDependent();
1798 bool EndDependent = EndIndex->isTypeDependent() ||
1799 EndIndex->isValueDependent();
1800 if ((!StartDependent &&
1801 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1802 (!EndDependent &&
1803 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001804 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001805 else {
1806 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001807 if (StartDependent || EndDependent) {
1808 // Nothing to compute.
1809 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregord6f584f2009-01-23 22:22:29 +00001810 EndValue.extend(StartValue.getBitWidth());
1811 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1812 StartValue.extend(EndValue.getBitWidth());
1813
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001814 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001815 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001816 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001817 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1818 Invalid = true;
1819 } else {
1820 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001821 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001822 D.getEllipsisLoc(),
1823 D.getRBracketLoc()));
1824 InitExpressions.push_back(StartIndex);
1825 InitExpressions.push_back(EndIndex);
1826 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001827 }
1828 break;
1829 }
1830 }
1831 }
1832
1833 if (Invalid || Init.isInvalid())
1834 return ExprError();
1835
1836 // Clear out the expressions within the designation.
1837 Desig.ClearExprs(*this);
1838
1839 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001840 = DesignatedInitExpr::Create(Context,
1841 Designators.data(), Designators.size(),
1842 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001843 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001844 return Owned(DIE);
1845}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001846
1847bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
Chris Lattner08202542009-02-24 22:50:46 +00001848 InitListChecker CheckInitList(*this, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001849 if (!CheckInitList.HadError())
1850 InitList = CheckInitList.getFullyStructuredList();
1851
1852 return CheckInitList.HadError();
1853}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001854
1855/// \brief Diagnose any semantic errors with value-initialization of
1856/// the given type.
1857///
1858/// Value-initialization effectively zero-initializes any types
1859/// without user-declared constructors, and calls the default
1860/// constructor for a for any type that has a user-declared
1861/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1862/// a type with a user-declared constructor does not have an
1863/// accessible, non-deleted default constructor. In C, everything can
1864/// be value-initialized, which corresponds to C's notion of
1865/// initializing objects with static storage duration when no
Mike Stump1eb44332009-09-09 15:08:12 +00001866/// initializer is provided for that object.
Douglas Gregor87fd7032009-02-02 17:43:21 +00001867///
1868/// \returns true if there was an error, false otherwise.
1869bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1870 // C++ [dcl.init]p5:
1871 //
1872 // To value-initialize an object of type T means:
1873
1874 // -- if T is an array type, then each element is value-initialized;
1875 if (const ArrayType *AT = Context.getAsArrayType(Type))
1876 return CheckValueInitialization(AT->getElementType(), Loc);
1877
Ted Kremenek6217b802009-07-29 21:53:49 +00001878 if (const RecordType *RT = Type->getAs<RecordType>()) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001879 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Douglas Gregor87fd7032009-02-02 17:43:21 +00001880 // -- if T is a class type (clause 9) with a user-declared
1881 // constructor (12.1), then the default constructor for T is
1882 // called (and the initialization is ill-formed if T has no
1883 // accessible default constructor);
Douglas Gregor39da0b82009-09-09 23:08:42 +00001884 if (ClassDecl->hasUserDeclaredConstructor()) {
1885 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1886
Douglas Gregor20093b42009-12-09 23:02:17 +00001887 // FIXME: Poor location information
Douglas Gregor39da0b82009-09-09 23:08:42 +00001888 CXXConstructorDecl *Constructor
1889 = PerformInitializationByConstructor(Type,
1890 MultiExprArg(*this, 0, 0),
1891 Loc, SourceRange(Loc),
1892 DeclarationName(),
Douglas Gregor20093b42009-12-09 23:02:17 +00001893 InitializationKind::CreateValue(Loc, Loc, Loc),
Douglas Gregor39da0b82009-09-09 23:08:42 +00001894 ConstructorArgs);
1895 if (!Constructor)
1896 return true;
1897
1898 OwningExprResult Init
1899 = BuildCXXConstructExpr(Loc, Type, Constructor,
1900 move_arg(ConstructorArgs));
1901 if (Init.isInvalid())
1902 return true;
1903
1904 // FIXME: Actually perform the value-initialization!
1905 return false;
1906 }
Douglas Gregor87fd7032009-02-02 17:43:21 +00001907 }
1908 }
1909
1910 if (Type->isReferenceType()) {
1911 // C++ [dcl.init]p5:
1912 // [...] A program that calls for default-initialization or
1913 // value-initialization of an entity of reference type is
1914 // ill-formed. [...]
Mike Stump390b4cc2009-05-16 07:39:55 +00001915 // FIXME: Once we have code that goes through this path, add an actual
1916 // diagnostic :)
Douglas Gregor87fd7032009-02-02 17:43:21 +00001917 }
1918
1919 return false;
1920}
Douglas Gregor20093b42009-12-09 23:02:17 +00001921
1922//===----------------------------------------------------------------------===//
1923// Initialization entity
1924//===----------------------------------------------------------------------===//
1925
1926void InitializedEntity::InitDeclLoc() {
1927 assert((Kind == EK_Variable || Kind == EK_Parameter || Kind == EK_Member) &&
1928 "InitDeclLoc cannot be used with non-declaration entities.");
1929
1930 if (TypeSourceInfo *DI = VariableOrMember->getTypeSourceInfo()) {
1931 TL = DI->getTypeLoc();
1932 return;
1933 }
1934
1935 // FIXME: Once we've gone through the effort to create the fake
1936 // TypeSourceInfo, should we cache it in the declaration?
1937 // (If not, we "leak" it).
1938 TypeSourceInfo *DI = VariableOrMember->getASTContext()
1939 .CreateTypeSourceInfo(VariableOrMember->getType());
1940 DI->getTypeLoc().initialize(VariableOrMember->getLocation());
1941 TL = DI->getTypeLoc();
1942}
1943
1944InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1945 CXXBaseSpecifier *Base)
1946{
1947 InitializedEntity Result;
1948 Result.Kind = EK_Base;
1949 Result.Base = Base;
1950 // FIXME: CXXBaseSpecifier should store a TypeLoc.
1951 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Base->getType());
1952 DI->getTypeLoc().initialize(Base->getSourceRange().getBegin());
1953 Result.TL = DI->getTypeLoc();
1954 return Result;
1955}
1956
1957//===----------------------------------------------------------------------===//
1958// Initialization sequence
1959//===----------------------------------------------------------------------===//
1960
1961void InitializationSequence::Step::Destroy() {
1962 switch (Kind) {
1963 case SK_ResolveAddressOfOverloadedFunction:
1964 case SK_CastDerivedToBaseRValue:
1965 case SK_CastDerivedToBaseLValue:
1966 case SK_BindReference:
1967 case SK_BindReferenceToTemporary:
1968 case SK_UserConversion:
1969 case SK_QualificationConversionRValue:
1970 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00001971 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00001972 case SK_ConstructorInitialization:
Douglas Gregor20093b42009-12-09 23:02:17 +00001973 break;
1974
1975 case SK_ConversionSequence:
1976 delete ICS;
1977 }
1978}
1979
1980void InitializationSequence::AddAddressOverloadResolutionStep(
1981 FunctionDecl *Function) {
1982 Step S;
1983 S.Kind = SK_ResolveAddressOfOverloadedFunction;
1984 S.Type = Function->getType();
1985 S.Function = Function;
1986 Steps.push_back(S);
1987}
1988
1989void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
1990 bool IsLValue) {
1991 Step S;
1992 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
1993 S.Type = BaseType;
1994 Steps.push_back(S);
1995}
1996
1997void InitializationSequence::AddReferenceBindingStep(QualType T,
1998 bool BindingTemporary) {
1999 Step S;
2000 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2001 S.Type = T;
2002 Steps.push_back(S);
2003}
2004
Eli Friedman03981012009-12-11 02:42:07 +00002005void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2006 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002007 Step S;
2008 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002009 S.Type = T;
Douglas Gregor20093b42009-12-09 23:02:17 +00002010 S.Function = Function;
2011 Steps.push_back(S);
2012}
2013
2014void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2015 bool IsLValue) {
2016 Step S;
2017 S.Kind = IsLValue? SK_QualificationConversionLValue
2018 : SK_QualificationConversionRValue;
2019 S.Type = Ty;
2020 Steps.push_back(S);
2021}
2022
2023void InitializationSequence::AddConversionSequenceStep(
2024 const ImplicitConversionSequence &ICS,
2025 QualType T) {
2026 Step S;
2027 S.Kind = SK_ConversionSequence;
2028 S.Type = T;
2029 S.ICS = new ImplicitConversionSequence(ICS);
2030 Steps.push_back(S);
2031}
2032
Douglas Gregord87b61f2009-12-10 17:56:55 +00002033void InitializationSequence::AddListInitializationStep(QualType T) {
2034 Step S;
2035 S.Kind = SK_ListInitialization;
2036 S.Type = T;
2037 Steps.push_back(S);
2038}
2039
Douglas Gregor51c56d62009-12-14 20:49:26 +00002040void
2041InitializationSequence::AddConstructorInitializationStep(
2042 CXXConstructorDecl *Constructor,
2043 QualType T) {
2044 Step S;
2045 S.Kind = SK_ConstructorInitialization;
2046 S.Type = T;
2047 S.Function = Constructor;
2048 Steps.push_back(S);
2049}
2050
Douglas Gregor20093b42009-12-09 23:02:17 +00002051void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2052 OverloadingResult Result) {
2053 SequenceKind = FailedSequence;
2054 this->Failure = Failure;
2055 this->FailedOverloadResult = Result;
2056}
2057
2058//===----------------------------------------------------------------------===//
2059// Attempt initialization
2060//===----------------------------------------------------------------------===//
2061
2062/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregord87b61f2009-12-10 17:56:55 +00002063static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002064 const InitializedEntity &Entity,
2065 const InitializationKind &Kind,
2066 InitListExpr *InitList,
2067 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002068 // FIXME: We only perform rudimentary checking of list
2069 // initializations at this point, then assume that any list
2070 // initialization of an array, aggregate, or scalar will be
2071 // well-formed. We we actually "perform" list initialization, we'll
2072 // do all of the necessary checking. C++0x initializer lists will
2073 // force us to perform more checking here.
2074 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2075
2076 QualType DestType = Entity.getType().getType();
2077
2078 // C++ [dcl.init]p13:
2079 // If T is a scalar type, then a declaration of the form
2080 //
2081 // T x = { a };
2082 //
2083 // is equivalent to
2084 //
2085 // T x = a;
2086 if (DestType->isScalarType()) {
2087 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2088 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2089 return;
2090 }
2091
2092 // Assume scalar initialization from a single value works.
2093 } else if (DestType->isAggregateType()) {
2094 // Assume aggregate initialization works.
2095 } else if (DestType->isVectorType()) {
2096 // Assume vector initialization works.
2097 } else if (DestType->isReferenceType()) {
2098 // FIXME: C++0x defines behavior for this.
2099 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2100 return;
2101 } else if (DestType->isRecordType()) {
2102 // FIXME: C++0x defines behavior for this
2103 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2104 }
2105
2106 // Add a general "list initialization" step.
2107 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002108}
2109
2110/// \brief Try a reference initialization that involves calling a conversion
2111/// function.
2112///
2113/// FIXME: look intos DRs 656, 896
2114static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2115 const InitializedEntity &Entity,
2116 const InitializationKind &Kind,
2117 Expr *Initializer,
2118 bool AllowRValues,
2119 InitializationSequence &Sequence) {
2120 QualType DestType = Entity.getType().getType();
2121 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2122 QualType T1 = cv1T1.getUnqualifiedType();
2123 QualType cv2T2 = Initializer->getType();
2124 QualType T2 = cv2T2.getUnqualifiedType();
2125
2126 bool DerivedToBase;
2127 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2128 T1, T2, DerivedToBase) &&
2129 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002130 (void)DerivedToBase;
Douglas Gregor20093b42009-12-09 23:02:17 +00002131
2132 // Build the candidate set directly in the initialization sequence
2133 // structure, so that it will persist if we fail.
2134 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2135 CandidateSet.clear();
2136
2137 // Determine whether we are allowed to call explicit constructors or
2138 // explicit conversion operators.
2139 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2140
2141 const RecordType *T1RecordType = 0;
2142 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2143 // The type we're converting to is a class type. Enumerate its constructors
2144 // to see if there is a suitable conversion.
2145 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2146
2147 DeclarationName ConstructorName
2148 = S.Context.DeclarationNames.getCXXConstructorName(
2149 S.Context.getCanonicalType(T1).getUnqualifiedType());
2150 DeclContext::lookup_iterator Con, ConEnd;
2151 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2152 Con != ConEnd; ++Con) {
2153 // Find the constructor (which may be a template).
2154 CXXConstructorDecl *Constructor = 0;
2155 FunctionTemplateDecl *ConstructorTmpl
2156 = dyn_cast<FunctionTemplateDecl>(*Con);
2157 if (ConstructorTmpl)
2158 Constructor = cast<CXXConstructorDecl>(
2159 ConstructorTmpl->getTemplatedDecl());
2160 else
2161 Constructor = cast<CXXConstructorDecl>(*Con);
2162
2163 if (!Constructor->isInvalidDecl() &&
2164 Constructor->isConvertingConstructor(AllowExplicit)) {
2165 if (ConstructorTmpl)
2166 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2167 &Initializer, 1, CandidateSet);
2168 else
2169 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2170 }
2171 }
2172 }
2173
2174 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2175 // The type we're converting from is a class type, enumerate its conversion
2176 // functions.
2177 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2178
2179 // Determine the type we are converting to. If we are allowed to
2180 // convert to an rvalue, take the type that the destination type
2181 // refers to.
2182 QualType ToType = AllowRValues? cv1T1 : DestType;
2183
2184 const UnresolvedSet *Conversions
2185 = T2RecordDecl->getVisibleConversionFunctions();
2186 for (UnresolvedSet::iterator I = Conversions->begin(),
2187 E = Conversions->end();
2188 I != E; ++I) {
2189 NamedDecl *D = *I;
2190 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2191 if (isa<UsingShadowDecl>(D))
2192 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2193
2194 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2195 CXXConversionDecl *Conv;
2196 if (ConvTemplate)
2197 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2198 else
2199 Conv = cast<CXXConversionDecl>(*I);
2200
2201 // If the conversion function doesn't return a reference type,
2202 // it can't be considered for this conversion unless we're allowed to
2203 // consider rvalues.
2204 // FIXME: Do we need to make sure that we only consider conversion
2205 // candidates with reference-compatible results? That might be needed to
2206 // break recursion.
2207 if ((AllowExplicit || !Conv->isExplicit()) &&
2208 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2209 if (ConvTemplate)
2210 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2211 ToType, CandidateSet);
2212 else
2213 S.AddConversionCandidate(Conv, ActingDC, Initializer, cv1T1,
2214 CandidateSet);
2215 }
2216 }
2217 }
2218
2219 SourceLocation DeclLoc = Initializer->getLocStart();
2220
2221 // Perform overload resolution. If it fails, return the failed result.
2222 OverloadCandidateSet::iterator Best;
2223 if (OverloadingResult Result
2224 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2225 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002226
Douglas Gregor20093b42009-12-09 23:02:17 +00002227 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002228
2229 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002230 if (isa<CXXConversionDecl>(Function))
2231 T2 = Function->getResultType();
2232 else
2233 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002234
2235 // Add the user-defined conversion step.
2236 Sequence.AddUserConversionStep(Function, T2.getNonReferenceType());
2237
2238 // Determine whether we need to perform derived-to-base or
2239 // cv-qualification adjustments.
Douglas Gregor20093b42009-12-09 23:02:17 +00002240 bool NewDerivedToBase = false;
2241 Sema::ReferenceCompareResult NewRefRelationship
2242 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2243 NewDerivedToBase);
2244 assert(NewRefRelationship != Sema::Ref_Incompatible &&
2245 "Overload resolution picked a bad conversion function");
2246 (void)NewRefRelationship;
2247 if (NewDerivedToBase)
2248 Sequence.AddDerivedToBaseCastStep(
2249 S.Context.getQualifiedType(T1,
2250 T2.getNonReferenceType().getQualifiers()),
2251 /*isLValue=*/true);
2252
2253 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2254 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2255
2256 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2257 return OR_Success;
2258}
2259
2260/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2261static void TryReferenceInitialization(Sema &S,
2262 const InitializedEntity &Entity,
2263 const InitializationKind &Kind,
2264 Expr *Initializer,
2265 InitializationSequence &Sequence) {
2266 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2267
2268 QualType DestType = Entity.getType().getType();
2269 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2270 QualType T1 = cv1T1.getUnqualifiedType();
2271 QualType cv2T2 = Initializer->getType();
2272 QualType T2 = cv2T2.getUnqualifiedType();
2273 SourceLocation DeclLoc = Initializer->getLocStart();
2274
2275 // If the initializer is the address of an overloaded function, try
2276 // to resolve the overloaded function. If all goes well, T2 is the
2277 // type of the resulting function.
2278 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2279 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2280 T1,
2281 false);
2282 if (!Fn) {
2283 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2284 return;
2285 }
2286
2287 Sequence.AddAddressOverloadResolutionStep(Fn);
2288 cv2T2 = Fn->getType();
2289 T2 = cv2T2.getUnqualifiedType();
2290 }
2291
2292 // FIXME: Rvalue references
2293 bool ForceRValue = false;
2294
2295 // Compute some basic properties of the types and the initializer.
2296 bool isLValueRef = DestType->isLValueReferenceType();
2297 bool isRValueRef = !isLValueRef;
2298 bool DerivedToBase = false;
2299 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2300 Initializer->isLvalue(S.Context);
2301 Sema::ReferenceCompareResult RefRelationship
2302 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2303
2304 // C++0x [dcl.init.ref]p5:
2305 // A reference to type "cv1 T1" is initialized by an expression of type
2306 // "cv2 T2" as follows:
2307 //
2308 // - If the reference is an lvalue reference and the initializer
2309 // expression
2310 OverloadingResult ConvOvlResult = OR_Success;
2311 if (isLValueRef) {
2312 if (InitLvalue == Expr::LV_Valid &&
2313 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2314 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2315 // reference-compatible with "cv2 T2," or
2316 //
2317 // Per C++ [over.best.ics]p2, we ignore whether the lvalue is a
2318 // bit-field when we're determining whether the reference initialization
2319 // can occur. This property will be checked by PerformInitialization.
2320 if (DerivedToBase)
2321 Sequence.AddDerivedToBaseCastStep(
2322 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()),
2323 /*isLValue=*/true);
2324 if (cv1T1.getQualifiers() != cv2T2.getQualifiers())
2325 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
2326 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/false);
2327 return;
2328 }
2329
2330 // - has a class type (i.e., T2 is a class type), where T1 is not
2331 // reference-related to T2, and can be implicitly converted to an
2332 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2333 // with "cv3 T3" (this conversion is selected by enumerating the
2334 // applicable conversion functions (13.3.1.6) and choosing the best
2335 // one through overload resolution (13.3)),
2336 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2337 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2338 Initializer,
2339 /*AllowRValues=*/false,
2340 Sequence);
2341 if (ConvOvlResult == OR_Success)
2342 return;
2343 }
2344 }
2345
2346 // - Otherwise, the reference shall be an lvalue reference to a
2347 // non-volatile const type (i.e., cv1 shall be const), or the reference
2348 // shall be an rvalue reference and the initializer expression shall
2349 // be an rvalue.
2350 if (!((isLValueRef && cv1T1.getCVRQualifiers() == Qualifiers::Const) ||
2351 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2352 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2353 Sequence.SetOverloadFailure(
2354 InitializationSequence::FK_ReferenceInitOverloadFailed,
2355 ConvOvlResult);
2356 else if (isLValueRef)
2357 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2358 ? (RefRelationship == Sema::Ref_Related
2359 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2360 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2361 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2362 else
2363 Sequence.SetFailed(
2364 InitializationSequence::FK_RValueReferenceBindingToLValue);
2365
2366 return;
2367 }
2368
2369 // - If T1 and T2 are class types and
2370 if (T1->isRecordType() && T2->isRecordType()) {
2371 // - the initializer expression is an rvalue and "cv1 T1" is
2372 // reference-compatible with "cv2 T2", or
2373 if (InitLvalue != Expr::LV_Valid &&
2374 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2375 if (DerivedToBase)
2376 Sequence.AddDerivedToBaseCastStep(
2377 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()),
2378 /*isLValue=*/false);
2379 if (cv1T1.getQualifiers() != cv2T2.getQualifiers())
2380 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2381 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2382 return;
2383 }
2384
2385 // - T1 is not reference-related to T2 and the initializer expression
2386 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2387 // conversion is selected by enumerating the applicable conversion
2388 // functions (13.3.1.6) and choosing the best one through overload
2389 // resolution (13.3)),
2390 if (RefRelationship == Sema::Ref_Incompatible) {
2391 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2392 Kind, Initializer,
2393 /*AllowRValues=*/true,
2394 Sequence);
2395 if (ConvOvlResult)
2396 Sequence.SetOverloadFailure(
2397 InitializationSequence::FK_ReferenceInitOverloadFailed,
2398 ConvOvlResult);
2399
2400 return;
2401 }
2402
2403 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2404 return;
2405 }
2406
2407 // - If the initializer expression is an rvalue, with T2 an array type,
2408 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2409 // is bound to the object represented by the rvalue (see 3.10).
2410 // FIXME: How can an array type be reference-compatible with anything?
2411 // Don't we mean the element types of T1 and T2?
2412
2413 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2414 // from the initializer expression using the rules for a non-reference
2415 // copy initialization (8.5). The reference is then bound to the
2416 // temporary. [...]
2417 // Determine whether we are allowed to call explicit constructors or
2418 // explicit conversion operators.
2419 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2420 ImplicitConversionSequence ICS
2421 = S.TryImplicitConversion(Initializer, cv1T1,
2422 /*SuppressUserConversions=*/false, AllowExplicit,
2423 /*ForceRValue=*/false,
2424 /*FIXME:InOverloadResolution=*/false,
2425 /*UserCast=*/Kind.isExplicitCast());
2426
2427 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
2428 // FIXME: Use the conversion function set stored in ICS to turn
2429 // this into an overloading ambiguity diagnostic. However, we need
2430 // to keep that set as an OverloadCandidateSet rather than as some
2431 // other kind of set.
2432 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
2433 return;
2434 }
2435
2436 // [...] If T1 is reference-related to T2, cv1 must be the
2437 // same cv-qualification as, or greater cv-qualification
2438 // than, cv2; otherwise, the program is ill-formed.
2439 if (RefRelationship == Sema::Ref_Related &&
2440 !cv1T1.isAtLeastAsQualifiedAs(cv2T2)) {
2441 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2442 return;
2443 }
2444
2445 // Perform the actual conversion.
2446 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2447 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2448 return;
2449}
2450
2451/// \brief Attempt character array initialization from a string literal
2452/// (C++ [dcl.init.string], C99 6.7.8).
2453static void TryStringLiteralInitialization(Sema &S,
2454 const InitializedEntity &Entity,
2455 const InitializationKind &Kind,
2456 Expr *Initializer,
2457 InitializationSequence &Sequence) {
2458 // FIXME: Implement!
2459}
2460
2461/// \brief Attempt value initialization (C++ [dcl.init]p7).
2462static void TryValueInitialization(Sema &S,
2463 const InitializedEntity &Entity,
2464 const InitializationKind &Kind,
2465 InitializationSequence &Sequence) {
2466 // FIXME: Implement!
2467}
2468
2469/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2470/// enumerates the constructors of the initialized entity and performs overload
2471/// resolution to select the best.
2472static void TryConstructorInitialization(Sema &S,
2473 const InitializedEntity &Entity,
2474 const InitializationKind &Kind,
2475 Expr **Args, unsigned NumArgs,
2476 InitializationSequence &Sequence) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002477 Sequence.setSequenceKind(InitializationSequence::ConstructorConversion);
2478
2479 // Build the candidate set directly in the initialization sequence
2480 // structure, so that it will persist if we fail.
2481 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2482 CandidateSet.clear();
2483
2484 // Determine whether we are allowed to call explicit constructors or
2485 // explicit conversion operators.
2486 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2487 Kind.getKind() == InitializationKind::IK_Value ||
2488 Kind.getKind() == InitializationKind::IK_Default);
2489
2490 // The type we're converting to is a class type. Enumerate its constructors
2491 // to see if one is suitable.
2492 QualType DestType = Entity.getType().getType();
2493 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2494 assert(DestRecordType && "Constructor initialization requires record type");
2495 CXXRecordDecl *DestRecordDecl
2496 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2497
2498 DeclarationName ConstructorName
2499 = S.Context.DeclarationNames.getCXXConstructorName(
2500 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2501 DeclContext::lookup_iterator Con, ConEnd;
2502 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2503 Con != ConEnd; ++Con) {
2504 // Find the constructor (which may be a template).
2505 CXXConstructorDecl *Constructor = 0;
2506 FunctionTemplateDecl *ConstructorTmpl
2507 = dyn_cast<FunctionTemplateDecl>(*Con);
2508 if (ConstructorTmpl)
2509 Constructor = cast<CXXConstructorDecl>(
2510 ConstructorTmpl->getTemplatedDecl());
2511 else
2512 Constructor = cast<CXXConstructorDecl>(*Con);
2513
2514 if (!Constructor->isInvalidDecl() &&
2515 Constructor->isConvertingConstructor(AllowExplicit)) {
2516 if (ConstructorTmpl)
2517 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2518 Args, NumArgs, CandidateSet);
2519 else
2520 S.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2521 }
2522 }
2523
2524 SourceLocation DeclLoc = Kind.getLocation();
2525
2526 // Perform overload resolution. If it fails, return the failed result.
2527 OverloadCandidateSet::iterator Best;
2528 if (OverloadingResult Result
2529 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2530 Sequence.SetOverloadFailure(
2531 InitializationSequence::FK_ConstructorOverloadFailed,
2532 Result);
2533 return;
2534 }
2535
2536 // Add the constructor initialization step. Any cv-qualification conversion is
2537 // subsumed by the initialization.
2538 Sequence.AddConstructorInitializationStep(
2539 cast<CXXConstructorDecl>(Best->Function),
2540 DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002541}
2542
2543/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2544/// which enumerates all conversion functions and performs overload resolution
2545/// to select the best.
2546static void TryUserDefinedConversion(Sema &S,
2547 const InitializedEntity &Entity,
2548 const InitializationKind &Kind,
2549 Expr *Initializer,
2550 InitializationSequence &Sequence) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002551 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2552
2553 QualType DestType = Entity.getType().getType();
2554 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2555 QualType SourceType = Initializer->getType();
2556 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2557 "Must have a class type to perform a user-defined conversion");
2558
2559 // Build the candidate set directly in the initialization sequence
2560 // structure, so that it will persist if we fail.
2561 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2562 CandidateSet.clear();
2563
2564 // Determine whether we are allowed to call explicit constructors or
2565 // explicit conversion operators.
2566 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2567
2568 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2569 // The type we're converting to is a class type. Enumerate its constructors
2570 // to see if there is a suitable conversion.
2571 CXXRecordDecl *DestRecordDecl
2572 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2573
2574 DeclarationName ConstructorName
2575 = S.Context.DeclarationNames.getCXXConstructorName(
2576 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2577 DeclContext::lookup_iterator Con, ConEnd;
2578 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2579 Con != ConEnd; ++Con) {
2580 // Find the constructor (which may be a template).
2581 CXXConstructorDecl *Constructor = 0;
2582 FunctionTemplateDecl *ConstructorTmpl
2583 = dyn_cast<FunctionTemplateDecl>(*Con);
2584 if (ConstructorTmpl)
2585 Constructor = cast<CXXConstructorDecl>(
2586 ConstructorTmpl->getTemplatedDecl());
2587 else
2588 Constructor = cast<CXXConstructorDecl>(*Con);
2589
2590 if (!Constructor->isInvalidDecl() &&
2591 Constructor->isConvertingConstructor(AllowExplicit)) {
2592 if (ConstructorTmpl)
2593 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2594 &Initializer, 1, CandidateSet);
2595 else
2596 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2597 }
2598 }
2599 }
2600
2601 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2602 // The type we're converting from is a class type, enumerate its conversion
2603 // functions.
2604 CXXRecordDecl *SourceRecordDecl
2605 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
2606
2607 const UnresolvedSet *Conversions
2608 = SourceRecordDecl->getVisibleConversionFunctions();
2609 for (UnresolvedSet::iterator I = Conversions->begin(),
2610 E = Conversions->end();
2611 I != E; ++I) {
2612 NamedDecl *D = *I;
2613 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2614 if (isa<UsingShadowDecl>(D))
2615 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2616
2617 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2618 CXXConversionDecl *Conv;
2619 if (ConvTemplate)
2620 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2621 else
2622 Conv = cast<CXXConversionDecl>(*I);
2623
2624 if (AllowExplicit || !Conv->isExplicit()) {
2625 if (ConvTemplate)
2626 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2627 DestType, CandidateSet);
2628 else
2629 S.AddConversionCandidate(Conv, ActingDC, Initializer, DestType,
2630 CandidateSet);
2631 }
2632 }
2633 }
2634
2635 SourceLocation DeclLoc = Initializer->getLocStart();
2636
2637 // Perform overload resolution. If it fails, return the failed result.
2638 OverloadCandidateSet::iterator Best;
2639 if (OverloadingResult Result
2640 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2641 Sequence.SetOverloadFailure(
2642 InitializationSequence::FK_UserConversionOverloadFailed,
2643 Result);
2644 return;
2645 }
2646
2647 FunctionDecl *Function = Best->Function;
2648
2649 if (isa<CXXConstructorDecl>(Function)) {
2650 // Add the user-defined conversion step. Any cv-qualification conversion is
2651 // subsumed by the initialization.
2652 Sequence.AddUserConversionStep(Function, DestType);
2653 return;
2654 }
2655
2656 // Add the user-defined conversion step that calls the conversion function.
2657 QualType ConvType = Function->getResultType().getNonReferenceType();
2658 Sequence.AddUserConversionStep(Function, ConvType);
2659
2660 // If the conversion following the call to the conversion function is
2661 // interesting, add it as a separate step.
2662 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2663 Best->FinalConversion.Third) {
2664 ImplicitConversionSequence ICS;
2665 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2666 ICS.Standard = Best->FinalConversion;
2667 Sequence.AddConversionSequenceStep(ICS, DestType);
2668 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002669}
2670
2671/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2672/// non-class type to another.
2673static void TryImplicitConversion(Sema &S,
2674 const InitializedEntity &Entity,
2675 const InitializationKind &Kind,
2676 Expr *Initializer,
2677 InitializationSequence &Sequence) {
2678 ImplicitConversionSequence ICS
2679 = S.TryImplicitConversion(Initializer, Entity.getType().getType(),
2680 /*SuppressUserConversions=*/true,
2681 /*AllowExplicit=*/false,
2682 /*ForceRValue=*/false,
2683 /*FIXME:InOverloadResolution=*/false,
2684 /*UserCast=*/Kind.isExplicitCast());
2685
2686 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
2687 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2688 return;
2689 }
2690
2691 Sequence.AddConversionSequenceStep(ICS, Entity.getType().getType());
2692}
2693
2694InitializationSequence::InitializationSequence(Sema &S,
2695 const InitializedEntity &Entity,
2696 const InitializationKind &Kind,
2697 Expr **Args,
2698 unsigned NumArgs) {
2699 ASTContext &Context = S.Context;
2700
2701 // C++0x [dcl.init]p16:
2702 // The semantics of initializers are as follows. The destination type is
2703 // the type of the object or reference being initialized and the source
2704 // type is the type of the initializer expression. The source type is not
2705 // defined when the initializer is a braced-init-list or when it is a
2706 // parenthesized list of expressions.
2707 QualType DestType = Entity.getType().getType();
2708
2709 if (DestType->isDependentType() ||
2710 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2711 SequenceKind = DependentSequence;
2712 return;
2713 }
2714
2715 QualType SourceType;
2716 Expr *Initializer = 0;
2717 if (Kind.getKind() == InitializationKind::IK_Copy) {
2718 Initializer = Args[0];
2719 if (!isa<InitListExpr>(Initializer))
2720 SourceType = Initializer->getType();
2721 }
2722
2723 // - If the initializer is a braced-init-list, the object is
2724 // list-initialized (8.5.4).
2725 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2726 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00002727 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00002728 }
2729
2730 // - If the destination type is a reference type, see 8.5.3.
2731 if (DestType->isReferenceType()) {
2732 // C++0x [dcl.init.ref]p1:
2733 // A variable declared to be a T& or T&&, that is, "reference to type T"
2734 // (8.3.2), shall be initialized by an object, or function, of type T or
2735 // by an object that can be converted into a T.
2736 // (Therefore, multiple arguments are not permitted.)
2737 if (NumArgs != 1)
2738 SetFailed(FK_TooManyInitsForReference);
2739 else
2740 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2741 return;
2742 }
2743
2744 // - If the destination type is an array of characters, an array of
2745 // char16_t, an array of char32_t, or an array of wchar_t, and the
2746 // initializer is a string literal, see 8.5.2.
2747 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2748 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2749 return;
2750 }
2751
2752 // - If the initializer is (), the object is value-initialized.
2753 if (Kind.getKind() == InitializationKind::IK_Value) {
2754 TryValueInitialization(S, Entity, Kind, *this);
2755 return;
2756 }
2757
2758 // - Otherwise, if the destination type is an array, the program is
2759 // ill-formed.
2760 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2761 if (AT->getElementType()->isAnyCharacterType())
2762 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2763 else
2764 SetFailed(FK_ArrayNeedsInitList);
2765
2766 return;
2767 }
2768
2769 // - If the destination type is a (possibly cv-qualified) class type:
2770 if (DestType->isRecordType()) {
2771 // - If the initialization is direct-initialization, or if it is
2772 // copy-initialization where the cv-unqualified version of the
2773 // source type is the same class as, or a derived class of, the
2774 // class of the destination, constructors are considered. [...]
2775 if (Kind.getKind() == InitializationKind::IK_Direct ||
2776 (Kind.getKind() == InitializationKind::IK_Copy &&
2777 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2778 S.IsDerivedFrom(SourceType, DestType))))
2779 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs, *this);
2780 // - Otherwise (i.e., for the remaining copy-initialization cases),
2781 // user-defined conversion sequences that can convert from the source
2782 // type to the destination type or (when a conversion function is
2783 // used) to a derived class thereof are enumerated as described in
2784 // 13.3.1.4, and the best one is chosen through overload resolution
2785 // (13.3).
2786 else
2787 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2788 return;
2789 }
2790
2791 // - Otherwise, if the source type is a (possibly cv-qualified) class
2792 // type, conversion functions are considered.
2793 if (SourceType->isRecordType()) {
2794 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2795 return;
2796 }
2797
2798 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00002799 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00002800 // conversions (Clause 4) will be used, if necessary, to convert the
2801 // initializer expression to the cv-unqualified version of the
2802 // destination type; no user-defined conversions are considered.
2803 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
2804}
2805
2806InitializationSequence::~InitializationSequence() {
2807 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
2808 StepEnd = Steps.end();
2809 Step != StepEnd; ++Step)
2810 Step->Destroy();
2811}
2812
2813//===----------------------------------------------------------------------===//
2814// Perform initialization
2815//===----------------------------------------------------------------------===//
2816
2817Action::OwningExprResult
2818InitializationSequence::Perform(Sema &S,
2819 const InitializedEntity &Entity,
2820 const InitializationKind &Kind,
Douglas Gregord87b61f2009-12-10 17:56:55 +00002821 Action::MultiExprArg Args,
2822 QualType *ResultType) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002823 if (SequenceKind == FailedSequence) {
2824 unsigned NumArgs = Args.size();
2825 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
2826 return S.ExprError();
2827 }
2828
2829 if (SequenceKind == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002830 // If the declaration is a non-dependent, incomplete array type
2831 // that has an initializer, then its type will be completed once
2832 // the initializer is instantiated.
2833 if (ResultType && !Entity.getType().getType()->isDependentType() &&
2834 Args.size() == 1) {
2835 QualType DeclType = Entity.getType().getType();
2836 if (const IncompleteArrayType *ArrayT
2837 = S.Context.getAsIncompleteArrayType(DeclType)) {
2838 // FIXME: We don't currently have the ability to accurately
2839 // compute the length of an initializer list without
2840 // performing full type-checking of the initializer list
2841 // (since we have to determine where braces are implicitly
2842 // introduced and such). So, we fall back to making the array
2843 // type a dependently-sized array type with no specified
2844 // bound.
2845 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
2846 SourceRange Brackets;
2847 // Scavange the location of the brackets from the entity, if we can.
2848 if (isa<IncompleteArrayTypeLoc>(Entity.getType())) {
2849 IncompleteArrayTypeLoc ArrayLoc
2850 = cast<IncompleteArrayTypeLoc>(Entity.getType());
2851 Brackets = ArrayLoc.getBracketsRange();
2852 }
2853
2854 *ResultType
2855 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
2856 /*NumElts=*/0,
2857 ArrayT->getSizeModifier(),
2858 ArrayT->getIndexTypeCVRQualifiers(),
2859 Brackets);
2860 }
2861
2862 }
2863 }
2864
Douglas Gregor20093b42009-12-09 23:02:17 +00002865 if (Kind.getKind() == InitializationKind::IK_Copy)
2866 return Sema::OwningExprResult(S, Args.release()[0]);
2867
2868 unsigned NumArgs = Args.size();
2869 return S.Owned(new (S.Context) ParenListExpr(S.Context,
2870 SourceLocation(),
2871 (Expr **)Args.release(),
2872 NumArgs,
2873 SourceLocation()));
2874 }
2875
2876 QualType DestType = Entity.getType().getType().getNonReferenceType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00002877 if (ResultType)
2878 *ResultType = Entity.getType().getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002879
2880 Sema::OwningExprResult CurInit(S);
2881 // For copy initialization and any other initialization forms that
2882 // only have a single initializer, we start with the (only)
2883 // initializer we have.
2884 // FIXME: DPG is not happy about this. There's confusion regarding whether
2885 // we're supposed to start the conversion from the solitary initializer or
2886 // from the set of arguments.
2887 if (Kind.getKind() == InitializationKind::IK_Copy ||
2888 SequenceKind == ReferenceBinding) {
2889 assert(Args.size() == 1);
2890 CurInit = Sema::OwningExprResult(S, Args.release()[0]);
2891 if (CurInit.isInvalid())
2892 return S.ExprError();
2893 }
2894
2895 // Walk through the computed steps for the initialization sequence,
2896 // performing the specified conversions along the way.
2897 for (step_iterator Step = step_begin(), StepEnd = step_end();
2898 Step != StepEnd; ++Step) {
2899 if (CurInit.isInvalid())
2900 return S.ExprError();
2901
2902 Expr *CurInitExpr = (Expr *)CurInit.get();
2903 QualType SourceType = CurInitExpr->getType();
2904
2905 switch (Step->Kind) {
2906 case SK_ResolveAddressOfOverloadedFunction:
2907 // Overload resolution determined which function invoke; update the
2908 // initializer to reflect that choice.
2909 CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function);
2910 break;
2911
2912 case SK_CastDerivedToBaseRValue:
2913 case SK_CastDerivedToBaseLValue: {
2914 // We have a derived-to-base cast that produces either an rvalue or an
2915 // lvalue. Perform that cast.
2916
2917 // Casts to inaccessible base classes are allowed with C-style casts.
2918 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
2919 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
2920 CurInitExpr->getLocStart(),
2921 CurInitExpr->getSourceRange(),
2922 IgnoreBaseAccess))
2923 return S.ExprError();
2924
2925 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
2926 CastExpr::CK_DerivedToBase,
2927 (Expr*)CurInit.release(),
2928 Step->Kind == SK_CastDerivedToBaseLValue));
2929 break;
2930 }
2931
2932 case SK_BindReference:
2933 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
2934 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
2935 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
2936 << Entity.getType().getType().isVolatileQualified()
2937 << BitField->getDeclName()
2938 << CurInitExpr->getSourceRange();
2939 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
2940 return S.ExprError();
2941 }
2942
2943 // Reference binding does not have any corresponding ASTs.
2944
2945 // Check exception specifications
2946 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
2947 return S.ExprError();
2948 break;
2949
2950 case SK_BindReferenceToTemporary:
2951 // Check exception specifications
2952 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
2953 return S.ExprError();
2954
2955 // FIXME: At present, we have no AST to describe when we need to make a
2956 // temporary to bind a reference to. We should.
2957 break;
2958
2959 case SK_UserConversion: {
2960 // We have a user-defined conversion that invokes either a constructor
2961 // or a conversion function.
2962 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
2963 if (CXXConstructorDecl *Constructor
2964 = dyn_cast<CXXConstructorDecl>(Step->Function)) {
2965 // Build a call to the selected constructor.
2966 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
2967 SourceLocation Loc = CurInitExpr->getLocStart();
2968 CurInit.release(); // Ownership transferred into MultiExprArg, below.
2969
2970 // Determine the arguments required to actually perform the constructor
2971 // call.
2972 if (S.CompleteConstructorCall(Constructor,
2973 Sema::MultiExprArg(S,
2974 (void **)&CurInitExpr,
2975 1),
2976 Loc, ConstructorArgs))
2977 return S.ExprError();
2978
2979 // Build the an expression that constructs a temporary.
2980 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
2981 move_arg(ConstructorArgs));
2982 if (CurInit.isInvalid())
2983 return S.ExprError();
2984
2985 CastKind = CastExpr::CK_ConstructorConversion;
2986 } else {
2987 // Build a call to the conversion function.
2988 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function);
2989
2990 // FIXME: Should we move this initialization into a separate
2991 // derived-to-base conversion? I believe the answer is "no", because
2992 // we don't want to turn off access control here for c-style casts.
2993 if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion))
2994 return S.ExprError();
2995
2996 // Do a little dance to make sure that CurInit has the proper
2997 // pointer.
2998 CurInit.release();
2999
3000 // Build the actual call to the conversion function.
3001 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3002 if (CurInit.isInvalid() || !CurInit.get())
3003 return S.ExprError();
3004
3005 CastKind = CastExpr::CK_UserDefinedConversion;
3006 }
3007
3008 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3009 CurInitExpr = CurInit.takeAs<Expr>();
3010 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3011 CastKind,
3012 CurInitExpr,
3013 false));
3014 break;
3015 }
3016
3017 case SK_QualificationConversionLValue:
3018 case SK_QualificationConversionRValue:
3019 // Perform a qualification conversion; these can never go wrong.
3020 S.ImpCastExprToType(CurInitExpr, Step->Type,
3021 CastExpr::CK_NoOp,
3022 Step->Kind == SK_QualificationConversionLValue);
3023 CurInit.release();
3024 CurInit = S.Owned(CurInitExpr);
3025 break;
3026
3027 case SK_ConversionSequence:
3028 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, "converting",
3029 false, false, *Step->ICS))
3030 return S.ExprError();
3031
3032 CurInit.release();
3033 CurInit = S.Owned(CurInitExpr);
3034 break;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003035
3036 case SK_ListInitialization: {
3037 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3038 QualType Ty = Step->Type;
3039 if (S.CheckInitList(InitList, ResultType? *ResultType : Ty))
3040 return S.ExprError();
3041
3042 CurInit.release();
3043 CurInit = S.Owned(InitList);
3044 break;
3045 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003046
3047 case SK_ConstructorInitialization: {
3048 CXXConstructorDecl *Constructor
3049 = cast<CXXConstructorDecl>(Step->Function);
3050
3051 // Build a call to the selected constructor.
3052 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3053 SourceLocation Loc = Kind.getLocation();
3054
3055 // Determine the arguments required to actually perform the constructor
3056 // call.
3057 if (S.CompleteConstructorCall(Constructor, move(Args),
3058 Loc, ConstructorArgs))
3059 return S.ExprError();
3060
3061 // Build the an expression that constructs a temporary.
3062 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3063 move_arg(ConstructorArgs));
3064 if (CurInit.isInvalid())
3065 return S.ExprError();
3066
3067 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3068 break;
3069 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003070 }
3071 }
3072
3073 return move(CurInit);
3074}
3075
3076//===----------------------------------------------------------------------===//
3077// Diagnose initialization failures
3078//===----------------------------------------------------------------------===//
3079bool InitializationSequence::Diagnose(Sema &S,
3080 const InitializedEntity &Entity,
3081 const InitializationKind &Kind,
3082 Expr **Args, unsigned NumArgs) {
3083 if (SequenceKind != FailedSequence)
3084 return false;
3085
3086 QualType DestType = Entity.getType().getType();
3087 switch (Failure) {
3088 case FK_TooManyInitsForReference:
3089 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3090 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
3091 break;
3092
3093 case FK_ArrayNeedsInitList:
3094 case FK_ArrayNeedsInitListOrStringLiteral:
3095 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3096 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3097 break;
3098
3099 case FK_AddressOfOverloadFailed:
3100 S.ResolveAddressOfOverloadedFunction(Args[0],
3101 DestType.getNonReferenceType(),
3102 true);
3103 break;
3104
3105 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00003106 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00003107 switch (FailedOverloadResult) {
3108 case OR_Ambiguous:
3109 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3110 << Args[0]->getType() << DestType.getNonReferenceType()
3111 << Args[0]->getSourceRange();
3112 S.PrintOverloadCandidates(FailedCandidateSet, true);
3113 break;
3114
3115 case OR_No_Viable_Function:
3116 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3117 << Args[0]->getType() << DestType.getNonReferenceType()
3118 << Args[0]->getSourceRange();
3119 S.PrintOverloadCandidates(FailedCandidateSet, false);
3120 break;
3121
3122 case OR_Deleted: {
3123 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3124 << Args[0]->getType() << DestType.getNonReferenceType()
3125 << Args[0]->getSourceRange();
3126 OverloadCandidateSet::iterator Best;
3127 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3128 Kind.getLocation(),
3129 Best);
3130 if (Ovl == OR_Deleted) {
3131 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3132 << Best->Function->isDeleted();
3133 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003134 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00003135 }
3136 break;
3137 }
3138
3139 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003140 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00003141 break;
3142 }
3143 break;
3144
3145 case FK_NonConstLValueReferenceBindingToTemporary:
3146 case FK_NonConstLValueReferenceBindingToUnrelated:
3147 S.Diag(Kind.getLocation(),
3148 Failure == FK_NonConstLValueReferenceBindingToTemporary
3149 ? diag::err_lvalue_reference_bind_to_temporary
3150 : diag::err_lvalue_reference_bind_to_unrelated)
3151 << DestType.getNonReferenceType()
3152 << Args[0]->getType()
3153 << Args[0]->getSourceRange();
3154 break;
3155
3156 case FK_RValueReferenceBindingToLValue:
3157 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3158 << Args[0]->getSourceRange();
3159 break;
3160
3161 case FK_ReferenceInitDropsQualifiers:
3162 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3163 << DestType.getNonReferenceType()
3164 << Args[0]->getType()
3165 << Args[0]->getSourceRange();
3166 break;
3167
3168 case FK_ReferenceInitFailed:
3169 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3170 << DestType.getNonReferenceType()
3171 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3172 << Args[0]->getType()
3173 << Args[0]->getSourceRange();
3174 break;
3175
3176 case FK_ConversionFailed:
3177 S.Diag(Kind.getLocation(), diag::err_cannot_initialize_decl_noname)
3178 << DestType
3179 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3180 << Args[0]->getType()
3181 << Args[0]->getSourceRange();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003182 break;
3183
3184 case FK_TooManyInitsForScalar: {
3185 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
3186
3187 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
3188 << /*scalar=*/2
3189 << SourceRange(InitList->getInit(1)->getLocStart(),
3190 InitList->getLocEnd());
3191 break;
3192 }
3193
3194 case FK_ReferenceBindingToInitList:
3195 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3196 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3197 break;
3198
3199 case FK_InitListBadDestinationType:
3200 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3201 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3202 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00003203
3204 case FK_ConstructorOverloadFailed: {
3205 SourceRange ArgsRange;
3206 if (NumArgs)
3207 ArgsRange = SourceRange(Args[0]->getLocStart(),
3208 Args[NumArgs - 1]->getLocEnd());
3209
3210 // FIXME: Using "DestType" for the entity we're printing is probably
3211 // bad.
3212 switch (FailedOverloadResult) {
3213 case OR_Ambiguous:
3214 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3215 << DestType << ArgsRange;
3216 S.PrintOverloadCandidates(FailedCandidateSet, true);
3217 break;
3218
3219 case OR_No_Viable_Function:
3220 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3221 << DestType << ArgsRange;
3222 S.PrintOverloadCandidates(FailedCandidateSet, false);
3223 break;
3224
3225 case OR_Deleted: {
3226 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3227 << true << DestType << ArgsRange;
3228 OverloadCandidateSet::iterator Best;
3229 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3230 Kind.getLocation(),
3231 Best);
3232 if (Ovl == OR_Deleted) {
3233 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3234 << Best->Function->isDeleted();
3235 } else {
3236 llvm_unreachable("Inconsistent overload resolution?");
3237 }
3238 break;
3239 }
3240
3241 case OR_Success:
3242 llvm_unreachable("Conversion did not fail!");
3243 break;
3244 }
3245 break;
3246 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003247 }
3248
3249 return true;
3250}