blob: 20008a7c1cd508770fb18c604ddc2a6608ce0d8d [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,
Douglas Gregor68647482009-12-16 03:45:30 +000076 Sema::AA_Initializing, DirectInit)) {
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +000077 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)
Douglas Gregor68647482009-12-16 03:45:30 +000084 << DeclType << Init->getType() << Sema::AA_Initializing
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +000085 << 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,
Douglas Gregor68647482009-12-16 03:45:30 +000098 InitType, Init, Sema::AA_Initializing);
Chris Lattnerdd8e0062009-02-24 22:27:37 +000099}
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,
Douglas Gregor99a2e602009-12-16 01:38:02 +0000138 const InitializedEntity &Entity,
139 const InitializationKind &Kind) {
140 SourceLocation InitLoc = Kind.getLocation();
141 DeclarationName InitEntity = Entity.getName();
142 bool DirectInit = (Kind.getKind() == InitializationKind::IK_Direct);
143
Mike Stump1eb44332009-09-09 15:08:12 +0000144 if (DeclType->isDependentType() ||
Douglas Gregorcb78d882009-11-19 18:03:26 +0000145 Init->isTypeDependent() || Init->isValueDependent()) {
146 // We have either a dependent type or a type- or value-dependent
147 // initializer, so we don't perform any additional checking at
148 // this point.
149
150 // If the declaration is a non-dependent, incomplete array type
151 // that has an initializer, then its type will be completed once
Douglas Gregor73460a32009-11-19 23:25:22 +0000152 // the initializer is instantiated.
Douglas Gregorcb78d882009-11-19 18:03:26 +0000153 if (!DeclType->isDependentType()) {
154 if (const IncompleteArrayType *ArrayT
155 = Context.getAsIncompleteArrayType(DeclType)) {
Douglas Gregor73460a32009-11-19 23:25:22 +0000156 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
157 if (!ILE->isTypeDependent()) {
158 // Compute the constant array type from the length of the
159 // initializer list.
160 // FIXME: This will be wrong if there are designated
161 // initializations. Good thing they don't exist in C++!
162 llvm::APInt NumElements(Context.getTypeSize(Context.getSizeType()),
163 ILE->getNumInits());
164 llvm::APInt Zero(Context.getTypeSize(Context.getSizeType()), 0);
165 if (NumElements == Zero) {
166 // Sizing an array implicitly to zero is not allowed by ISO C,
167 // but is supported by GNU.
168 Diag(ILE->getLocStart(), diag::ext_typecheck_zero_array_size);
169 }
170
171 DeclType = Context.getConstantArrayType(ArrayT->getElementType(),
172 NumElements,
173 ArrayT->getSizeModifier(),
174 ArrayT->getIndexTypeCVRQualifiers());
175 return false;
176 }
177 }
178
179 // Make the array type-dependent by making it dependently-sized.
Douglas Gregorcb78d882009-11-19 18:03:26 +0000180 DeclType = Context.getDependentSizedArrayType(ArrayT->getElementType(),
181 /*NumElts=*/0,
182 ArrayT->getSizeModifier(),
183 ArrayT->getIndexTypeCVRQualifiers(),
184 SourceRange());
185 }
186 }
187
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000188 return false;
Douglas Gregorcb78d882009-11-19 18:03:26 +0000189 }
Mike Stump1eb44332009-09-09 15:08:12 +0000190
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000191 // C++ [dcl.init.ref]p1:
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000192 // A variable declared to be a T& or T&&, that is "reference to type T"
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000193 // (8.3.2), shall be initialized by an object, or function, of
194 // type T or by an object that can be converted into a T.
Douglas Gregor52bb5d22009-12-16 16:54:16 +0000195 if (DeclType->isReferenceType()) {
196 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
197 OwningExprResult CurInit = InitSeq.Perform(*this, Entity, Kind,
198 MultiExprArg(*this, (void**)&Init, 1),
199 &DeclType);
200 if (CurInit.isInvalid())
201 return true;
202
203 Init = CurInit.takeAs<Expr>();
204 return false;
205 }
Mike Stump1eb44332009-09-09 15:08:12 +0000206
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000207 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
208 // of unknown size ("[]") or an object type that is not a variable array type.
209 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
210 return Diag(InitLoc, diag::err_variable_object_no_init)
211 << VAT->getSizeExpr()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000212
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000213 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
214 if (!InitList) {
215 // FIXME: Handle wide strings
Chris Lattner79e079d2009-02-24 23:10:27 +0000216 if (Expr *Str = IsStringInit(Init, DeclType, Context)) {
217 CheckStringInit(Str, DeclType, *this);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000218 return false;
219 }
Mike Stump1eb44332009-09-09 15:08:12 +0000220
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000221 // C++ [dcl.init]p14:
222 // -- If the destination type is a (possibly cv-qualified) class
223 // type:
224 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
225 QualType DeclTypeC = Context.getCanonicalType(DeclType);
226 QualType InitTypeC = Context.getCanonicalType(Init->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000227
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000228 // -- If the initialization is direct-initialization, or if it is
229 // copy-initialization where the cv-unqualified version of the
230 // source type is the same class as, or a derived class of, the
231 // class of the destination, constructors are considered.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000232 if ((DeclTypeC.getLocalUnqualifiedType()
233 == InitTypeC.getLocalUnqualifiedType()) ||
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000234 IsDerivedFrom(InitTypeC, DeclTypeC)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000235 const CXXRecordDecl *RD =
Ted Kremenek6217b802009-07-29 21:53:49 +0000236 cast<CXXRecordDecl>(DeclType->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000237
Anders Carlssonbffed8a2009-05-27 16:38:58 +0000238 // No need to make a CXXConstructExpr if both the ctor and dtor are
239 // trivial.
240 if (RD->hasTrivialConstructor() && RD->hasTrivialDestructor())
241 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000242
Douglas Gregor39da0b82009-09-09 23:08:42 +0000243 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
244
Douglas Gregor20093b42009-12-09 23:02:17 +0000245 // FIXME: Poor location information
246 InitializationKind InitKind
247 = InitializationKind::CreateCopy(Init->getLocStart(),
248 SourceLocation());
249 if (DirectInit)
250 InitKind = InitializationKind::CreateDirect(Init->getLocStart(),
251 SourceLocation(),
252 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000253 CXXConstructorDecl *Constructor
Douglas Gregor39da0b82009-09-09 23:08:42 +0000254 = PerformInitializationByConstructor(DeclType,
255 MultiExprArg(*this,
256 (void **)&Init, 1),
257 InitLoc, Init->getSourceRange(),
Douglas Gregor20093b42009-12-09 23:02:17 +0000258 InitEntity, InitKind,
Douglas Gregor39da0b82009-09-09 23:08:42 +0000259 ConstructorArgs);
Anders Carlsson2078bb92009-05-27 16:10:08 +0000260 if (!Constructor)
261 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000262
263 OwningExprResult InitResult =
Anders Carlssonec8e5ea2009-09-05 07:40:38 +0000264 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000265 DeclType, Constructor,
Douglas Gregor39da0b82009-09-09 23:08:42 +0000266 move_arg(ConstructorArgs));
Anders Carlssonda3f4e22009-08-25 05:12:04 +0000267 if (InitResult.isInvalid())
268 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000269
Anders Carlssonda3f4e22009-08-25 05:12:04 +0000270 Init = InitResult.takeAs<Expr>();
Anders Carlsson2078bb92009-05-27 16:10:08 +0000271 return false;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000272 }
Mike Stump1eb44332009-09-09 15:08:12 +0000273
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000274 // -- Otherwise (i.e., for the remaining copy-initialization
275 // cases), user-defined conversion sequences that can
276 // convert from the source type to the destination type or
277 // (when a conversion function is used) to a derived class
278 // thereof are enumerated as described in 13.3.1.4, and the
279 // best one is chosen through overload resolution
280 // (13.3). If the conversion cannot be done or is
281 // ambiguous, the initialization is ill-formed. The
282 // function selected is called with the initializer
283 // expression as its argument; if the function is a
284 // constructor, the call initializes a temporary of the
285 // destination type.
Mike Stump390b4cc2009-05-16 07:39:55 +0000286 // FIXME: We're pretending to do copy elision here; return to this when we
287 // have ASTs for such things.
Douglas Gregor68647482009-12-16 03:45:30 +0000288 if (!PerformImplicitConversion(Init, DeclType, Sema::AA_Initializing))
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000289 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000290
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000291 if (InitEntity)
292 return Diag(InitLoc, diag::err_cannot_initialize_decl)
Chris Lattnerb78d8332009-06-26 04:45:06 +0000293 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
294 << Init->getType() << Init->getSourceRange();
295 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000296 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
297 << Init->getType() << Init->getSourceRange();
298 }
Mike Stump1eb44332009-09-09 15:08:12 +0000299
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000300 // C99 6.7.8p16.
301 if (DeclType->isArrayType())
302 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
Chris Lattnerb78d8332009-06-26 04:45:06 +0000303 << Init->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000304
Chris Lattner95e8d652009-02-24 22:46:58 +0000305 return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
Mike Stump1eb44332009-09-09 15:08:12 +0000306 }
307
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000308 bool hadError = CheckInitList(Entity, InitList, DeclType);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000309 Init = InitList;
310 return hadError;
311}
312
313//===----------------------------------------------------------------------===//
314// Semantic checking for initializer lists.
315//===----------------------------------------------------------------------===//
316
Douglas Gregor9e80f722009-01-29 01:05:33 +0000317/// @brief Semantic checking for initializer lists.
318///
319/// The InitListChecker class contains a set of routines that each
320/// handle the initialization of a certain kind of entity, e.g.,
321/// arrays, vectors, struct/union types, scalars, etc. The
322/// InitListChecker itself performs a recursive walk of the subobject
323/// structure of the type to be initialized, while stepping through
324/// the initializer list one element at a time. The IList and Index
325/// parameters to each of the Check* routines contain the active
326/// (syntactic) initializer list and the index into that initializer
327/// list that represents the current initializer. Each routine is
328/// responsible for moving that Index forward as it consumes elements.
329///
330/// Each Check* routine also has a StructuredList/StructuredIndex
331/// arguments, which contains the current the "structured" (semantic)
332/// initializer list and the index into that initializer list where we
333/// are copying initializers as we map them over to the semantic
334/// list. Once we have completed our recursive walk of the subobject
335/// structure, we will have constructed a full semantic initializer
336/// list.
337///
338/// C99 designators cause changes in the initializer list traversal,
339/// because they make the initialization "jump" into a specific
340/// subobject and then continue the initialization from that
341/// point. CheckDesignatedInitializer() recursively steps into the
342/// designated subobject and manages backing out the recursion to
343/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000344namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000345class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000346 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000347 bool hadError;
348 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
349 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000350
351 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000352 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000353 unsigned &StructuredIndex,
354 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000355 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000356 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000357 unsigned &StructuredIndex,
358 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000359 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
360 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000361 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000362 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000363 unsigned &StructuredIndex,
364 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000365 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000366 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000367 InitListExpr *StructuredList,
368 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000369 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000370 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000371 InitListExpr *StructuredList,
372 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000373 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000374 unsigned &Index,
375 InitListExpr *StructuredList,
376 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000377 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000378 InitListExpr *StructuredList,
379 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000380 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
381 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000382 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000383 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000384 unsigned &StructuredIndex,
385 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000386 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
387 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000388 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000389 InitListExpr *StructuredList,
390 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000391 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000392 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000393 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000394 RecordDecl::field_iterator *NextField,
395 llvm::APSInt *NextElementIndex,
396 unsigned &Index,
397 InitListExpr *StructuredList,
398 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000399 bool FinishSubobjectInit,
400 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000401 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
402 QualType CurrentObjectType,
403 InitListExpr *StructuredList,
404 unsigned StructuredIndex,
405 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000406 void UpdateStructuredListElement(InitListExpr *StructuredList,
407 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000408 Expr *expr);
409 int numArrayElements(QualType DeclType);
410 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000411
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000412 void FillInValueInitializations(const InitializedEntity &Entity,
413 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000414public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000415 InitListChecker(Sema &S, const InitializedEntity &Entity,
416 InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000417 bool HadError() { return hadError; }
418
419 // @brief Retrieves the fully-structured initializer list used for
420 // semantic analysis and code generation.
421 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
422};
Chris Lattner8b419b92009-02-24 22:48:58 +0000423} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000424
Douglas Gregor4c678342009-01-28 21:54:33 +0000425/// Recursively replaces NULL values within the given initializer list
426/// with expressions that perform value-initialization of the
427/// appropriate type.
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000428void
429InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
430 InitListExpr *ILE,
431 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000432 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000433 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000434 SourceLocation Loc = ILE->getSourceRange().getBegin();
435 if (ILE->getSyntacticForm())
436 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Ted Kremenek6217b802009-07-29 21:53:49 +0000438 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000439 unsigned Init = 0, NumInits = ILE->getNumInits();
Mike Stump1eb44332009-09-09 15:08:12 +0000440 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000441 Field = RType->getDecl()->field_begin(),
442 FieldEnd = RType->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000443 Field != FieldEnd; ++Field) {
444 if (Field->isUnnamedBitfield())
445 continue;
446
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000447 InitializedEntity MemberEntity
448 = InitializedEntity::InitializeMember(*Field, &Entity);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000449 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000450 // FIXME: We probably don't need to handle references
451 // specially here, since value-initialization of references is
452 // handled in InitializationSequence.
Douglas Gregor930d8b52009-01-30 22:09:00 +0000453 if (Field->getType()->isReferenceType()) {
454 // C++ [dcl.init.aggr]p9:
455 // If an incomplete or empty initializer-list leaves a
456 // member of reference type uninitialized, the program is
Mike Stump1eb44332009-09-09 15:08:12 +0000457 // ill-formed.
Chris Lattner08202542009-02-24 22:50:46 +0000458 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000459 << Field->getType()
460 << ILE->getSyntacticForm()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000461 SemaRef.Diag(Field->getLocation(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000462 diag::note_uninit_reference_member);
463 hadError = true;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000464 return;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000465 }
466
467 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
468 true);
469 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
470 if (!InitSeq) {
471 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000472 hadError = true;
473 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000474 }
Douglas Gregor87fd7032009-02-02 17:43:21 +0000475
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000476 Sema::OwningExprResult MemberInit
477 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
478 Sema::MultiExprArg(SemaRef, 0, 0));
479 if (MemberInit.isInvalid()) {
480 hadError = 0;
481 return;
482 }
483
484 if (hadError) {
485 // Do nothing
486 } else if (Init < NumInits) {
487 ILE->setInit(Init, MemberInit.takeAs<Expr>());
488 } else if (InitSeq.getKind()
489 == InitializationSequence::ConstructorInitialization) {
490 // Value-initialization requires a constructor call, so
491 // extend the initializer list to include the constructor
492 // call and make a note that we'll need to take another pass
493 // through the initializer list.
494 ILE->updateInit(Init, MemberInit.takeAs<Expr>());
495 RequiresSecondPass = true;
496 }
Mike Stump1eb44332009-09-09 15:08:12 +0000497 } else if (InitListExpr *InnerILE
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000498 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000499 FillInValueInitializations(MemberEntity, InnerILE,
500 RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000501 ++Init;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000502
503 // Only look at the first initialization of a union.
504 if (RType->getDecl()->isUnion())
505 break;
Douglas Gregor4c678342009-01-28 21:54:33 +0000506 }
507
508 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000509 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000510
511 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000513 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000514 unsigned NumInits = ILE->getNumInits();
515 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000516 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000517 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000518 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
519 NumElements = CAType->getSize().getZExtValue();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000520 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
521 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000522 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000523 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000524 NumElements = VType->getNumElements();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000525 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
526 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000527 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000528 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000529
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000530
Douglas Gregor87fd7032009-02-02 17:43:21 +0000531 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000532 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayOrVectorElement)
533 ElementEntity.setElementIndex(Init);
534
Douglas Gregor87fd7032009-02-02 17:43:21 +0000535 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000536 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
537 true);
538 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
539 if (!InitSeq) {
540 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000541 hadError = true;
542 return;
543 }
544
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000545 Sema::OwningExprResult ElementInit
546 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
547 Sema::MultiExprArg(SemaRef, 0, 0));
548 if (ElementInit.isInvalid()) {
549 hadError = 0;
550 return;
551 }
552
553 if (hadError) {
554 // Do nothing
555 } else if (Init < NumInits) {
556 ILE->setInit(Init, ElementInit.takeAs<Expr>());
557 } else if (InitSeq.getKind()
558 == InitializationSequence::ConstructorInitialization) {
559 // Value-initialization requires a constructor call, so
560 // extend the initializer list to include the constructor
561 // call and make a note that we'll need to take another pass
562 // through the initializer list.
563 ILE->updateInit(Init, ElementInit.takeAs<Expr>());
564 RequiresSecondPass = true;
565 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000566 } else if (InitListExpr *InnerILE
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000567 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
568 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000569 }
570}
571
Chris Lattner68355a52009-01-29 05:10:57 +0000572
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000573InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
574 InitListExpr *IL, QualType &T)
Chris Lattner08202542009-02-24 22:50:46 +0000575 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000576 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000577
Eli Friedmanb85f7072008-05-19 19:16:24 +0000578 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000579 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000580 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000581 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000582 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
583 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000584
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000585 if (!hadError) {
586 bool RequiresSecondPass = false;
587 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
588 if (RequiresSecondPass)
589 FillInValueInitializations(Entity, FullyStructuredList,
590 RequiresSecondPass);
591 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000592}
593
594int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000595 // FIXME: use a proper constant
596 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000597 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000598 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000599 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
600 }
601 return maxElements;
602}
603
604int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000605 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000606 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000607 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000608 Field = structDecl->field_begin(),
609 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000610 Field != FieldEnd; ++Field) {
611 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
612 ++InitializableMembers;
613 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000614 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000615 return std::min(InitializableMembers, 1);
616 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000617}
618
Mike Stump1eb44332009-09-09 15:08:12 +0000619void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000620 QualType T, unsigned &Index,
621 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000622 unsigned &StructuredIndex,
623 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000624 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000625
Steve Naroff0cca7492008-05-01 22:18:59 +0000626 if (T->isArrayType())
627 maxElements = numArrayElements(T);
628 else if (T->isStructureType() || T->isUnionType())
629 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000630 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000631 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000632 else
633 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000634
Eli Friedman402256f2008-05-25 13:49:22 +0000635 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000636 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000637 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000638 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000639 hadError = true;
640 return;
641 }
642
Douglas Gregor4c678342009-01-28 21:54:33 +0000643 // Build a structured initializer list corresponding to this subobject.
644 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000645 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
646 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000647 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
648 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000649 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000650
Douglas Gregor4c678342009-01-28 21:54:33 +0000651 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000652 unsigned StartIndex = Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000653 CheckListElementTypes(ParentIList, T, false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000654 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000655 StructuredSubobjectInitIndex,
656 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000657 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000658 StructuredSubobjectInitList->setType(T);
659
Douglas Gregored8a93d2009-03-01 17:12:46 +0000660 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000661 // range corresponds with the end of the last initializer it used.
662 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000663 SourceLocation EndLoc
Douglas Gregor87fd7032009-02-02 17:43:21 +0000664 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
665 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
666 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000667}
668
Steve Naroffa647caa2008-05-06 00:23:44 +0000669void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000670 unsigned &Index,
671 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000672 unsigned &StructuredIndex,
673 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000674 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000675 SyntacticToSemantic[IList] = StructuredList;
676 StructuredList->setSyntacticForm(IList);
Mike Stump1eb44332009-09-09 15:08:12 +0000677 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000678 StructuredIndex, TopLevelObject);
Steve Naroffa647caa2008-05-06 00:23:44 +0000679 IList->setType(T);
Douglas Gregor4c678342009-01-28 21:54:33 +0000680 StructuredList->setType(T);
Eli Friedman638e1442008-05-25 13:22:35 +0000681 if (hadError)
682 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000683
Eli Friedman638e1442008-05-25 13:22:35 +0000684 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000685 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000686 if (StructuredIndex == 1 &&
687 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000688 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000689 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000690 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000691 hadError = true;
692 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000693 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000694 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000695 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000696 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000697 // Don't complain for incomplete types, since we'll get an error
698 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000699 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000700 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000701 CurrentObjectType->isArrayType()? 0 :
702 CurrentObjectType->isVectorType()? 1 :
703 CurrentObjectType->isScalarType()? 2 :
704 CurrentObjectType->isUnionType()? 3 :
705 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000706
707 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000708 if (SemaRef.getLangOptions().CPlusPlus) {
709 DK = diag::err_excess_initializers;
710 hadError = true;
711 }
Nate Begeman08634522009-07-07 21:53:06 +0000712 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
713 DK = diag::err_excess_initializers;
714 hadError = true;
715 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000716
Chris Lattner08202542009-02-24 22:50:46 +0000717 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000718 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000719 }
720 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000721
Eli Friedman759f2522009-05-16 11:45:48 +0000722 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000723 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000724 << IList->getSourceRange()
Chris Lattner29d9c1a2009-12-06 17:36:05 +0000725 << CodeModificationHint::CreateRemoval(IList->getLocStart())
726 << CodeModificationHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000727}
728
Eli Friedmanb85f7072008-05-19 19:16:24 +0000729void InitListChecker::CheckListElementTypes(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000730 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000731 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000732 unsigned &Index,
733 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000734 unsigned &StructuredIndex,
735 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000736 if (DeclType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000737 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000738 } else if (DeclType->isVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000739 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000740 } else if (DeclType->isAggregateType()) {
741 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000742 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000743 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000744 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000745 StructuredList, StructuredIndex,
746 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000747 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000748 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000749 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000750 false);
Douglas Gregor4c678342009-01-28 21:54:33 +0000751 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
752 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000753 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000754 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000755 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
756 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000757 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000758 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000759 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000760 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000761 } else if (DeclType->isRecordType()) {
762 // C++ [dcl.init]p14:
763 // [...] If the class is an aggregate (8.5.1), and the initializer
764 // is a brace-enclosed list, see 8.5.1.
765 //
766 // Note: 8.5.1 is handled below; here, we diagnose the case where
767 // we have an initializer list and a destination type that is not
768 // an aggregate.
769 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000770 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000771 << DeclType << IList->getSourceRange();
772 hadError = true;
773 } else if (DeclType->isReferenceType()) {
774 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000775 } else {
776 // In C, all types are either scalars or aggregates, but
Mike Stump1eb44332009-09-09 15:08:12 +0000777 // additional handling is needed here for C++ (and possibly others?).
Steve Naroff0cca7492008-05-01 22:18:59 +0000778 assert(0 && "Unsupported initializer type");
779 }
780}
781
Eli Friedmanb85f7072008-05-19 19:16:24 +0000782void InitListChecker::CheckSubElementType(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000783 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000784 unsigned &Index,
785 InitListExpr *StructuredList,
786 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000787 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000788 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
789 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000790 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000791 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000792 = getStructuredSubobjectInit(IList, Index, ElemType,
793 StructuredList, StructuredIndex,
794 SubInitList->getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +0000795 CheckExplicitInitList(SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000796 newStructuredList, newStructuredIndex);
797 ++StructuredIndex;
798 ++Index;
Chris Lattner79e079d2009-02-24 23:10:27 +0000799 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
800 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000801 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000802 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000803 } else if (ElemType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000804 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000805 } else if (ElemType->isReferenceType()) {
806 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000807 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000808 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000809 // C++ [dcl.init.aggr]p12:
810 // All implicit type conversions (clause 4) are considered when
811 // initializing the aggregate member with an ini- tializer from
812 // an initializer-list. If the initializer can initialize a
813 // member, the member is initialized. [...]
Mike Stump1eb44332009-09-09 15:08:12 +0000814 ImplicitConversionSequence ICS
Anders Carlssond28b4282009-08-27 17:18:13 +0000815 = SemaRef.TryCopyInitialization(expr, ElemType,
816 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +0000817 /*ForceRValue=*/false,
818 /*InOverloadResolution=*/false);
Anders Carlssond28b4282009-08-27 17:18:13 +0000819
Douglas Gregor930d8b52009-01-30 22:09:00 +0000820 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Mike Stump1eb44332009-09-09 15:08:12 +0000821 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregor68647482009-12-16 03:45:30 +0000822 Sema::AA_Initializing))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000823 hadError = true;
824 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
825 ++Index;
826 return;
827 }
828
829 // Fall through for subaggregate initialization
830 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000831 // C99 6.7.8p13:
Douglas Gregor930d8b52009-01-30 22:09:00 +0000832 //
833 // The initializer for a structure or union object that has
834 // automatic storage duration shall be either an initializer
835 // list as described below, or a single expression that has
836 // compatible structure or union type. In the latter case, the
837 // initial value of the object, including unnamed members, is
838 // that of the expression.
Eli Friedman6b5374f2009-06-13 10:38:46 +0000839 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman8718a6a2009-05-29 18:22:49 +0000840 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000841 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
842 ++Index;
843 return;
844 }
845
846 // Fall through for subaggregate initialization
847 }
848
849 // C++ [dcl.init.aggr]p12:
Mike Stump1eb44332009-09-09 15:08:12 +0000850 //
Douglas Gregor930d8b52009-01-30 22:09:00 +0000851 // [...] Otherwise, if the member is itself a non-empty
852 // subaggregate, brace elision is assumed and the initializer is
853 // considered for the initialization of the first member of
854 // the subaggregate.
855 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000856 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000857 StructuredIndex);
858 ++StructuredIndex;
859 } else {
860 // We cannot initialize this element, so let
861 // PerformCopyInitialization produce the appropriate diagnostic.
Douglas Gregor68647482009-12-16 03:45:30 +0000862 SemaRef.PerformCopyInitialization(expr, ElemType, Sema::AA_Initializing);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000863 hadError = true;
864 ++Index;
865 ++StructuredIndex;
866 }
867 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000868}
869
Douglas Gregor930d8b52009-01-30 22:09:00 +0000870void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000871 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000872 InitListExpr *StructuredList,
873 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000874 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000875 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000876 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000877 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000878 diag::err_many_braces_around_scalar_init)
879 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000880 hadError = true;
881 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000882 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000883 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000884 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000885 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor05c13a32009-01-22 00:58:24 +0000886 diag::err_designator_for_scalar_init)
887 << DeclType << expr->getSourceRange();
888 hadError = true;
889 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000890 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000891 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000892 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000893
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000894 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner08202542009-02-24 22:50:46 +0000895 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedmanbb504d32008-05-19 20:12:18 +0000896 hadError = true; // types weren't compatible.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000897 else if (savExpr != expr) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000898 // The type was promoted, update initializer list.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000899 IList->setInit(Index, expr);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000900 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000901 if (hadError)
902 ++StructuredIndex;
903 else
904 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000905 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000906 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000907 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000908 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000909 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000910 ++Index;
911 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000912 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000913 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000914}
915
Douglas Gregor930d8b52009-01-30 22:09:00 +0000916void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
917 unsigned &Index,
918 InitListExpr *StructuredList,
919 unsigned &StructuredIndex) {
920 if (Index < IList->getNumInits()) {
921 Expr *expr = IList->getInit(Index);
922 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000923 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000924 << DeclType << IList->getSourceRange();
925 hadError = true;
926 ++Index;
927 ++StructuredIndex;
928 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000929 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000930
931 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000932 if (SemaRef.CheckReferenceInit(expr, DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +0000933 /*FIXME:*/expr->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000934 /*SuppressUserConversions=*/false,
935 /*AllowExplicit=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +0000936 /*ForceRValue=*/false))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000937 hadError = true;
938 else if (savExpr != expr) {
939 // The type was promoted, update initializer list.
940 IList->setInit(Index, expr);
941 }
942 if (hadError)
943 ++StructuredIndex;
944 else
945 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
946 ++Index;
947 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000948 // FIXME: It would be wonderful if we could point at the actual member. In
949 // general, it would be useful to pass location information down the stack,
950 // so that we know the location (or decl) of the "current object" being
951 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000952 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000953 diag::err_init_reference_member_uninitialized)
954 << DeclType
955 << IList->getSourceRange();
956 hadError = true;
957 ++Index;
958 ++StructuredIndex;
959 return;
960 }
961}
962
Mike Stump1eb44332009-09-09 15:08:12 +0000963void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000964 unsigned &Index,
965 InitListExpr *StructuredList,
966 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000967 if (Index < IList->getNumInits()) {
John McCall183700f2009-09-21 23:43:11 +0000968 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000969 unsigned maxElements = VT->getNumElements();
970 unsigned numEltsInit = 0;
Steve Naroff0cca7492008-05-01 22:18:59 +0000971 QualType elementType = VT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +0000972
Nate Begeman2ef13e52009-08-10 23:49:36 +0000973 if (!SemaRef.getLangOptions().OpenCL) {
974 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
975 // Don't attempt to go past the end of the init list
976 if (Index >= IList->getNumInits())
977 break;
978 CheckSubElementType(IList, elementType, Index,
979 StructuredList, StructuredIndex);
980 }
981 } else {
982 // OpenCL initializers allows vectors to be constructed from vectors.
983 for (unsigned i = 0; i < maxElements; ++i) {
984 // Don't attempt to go past the end of the init list
985 if (Index >= IList->getNumInits())
986 break;
987 QualType IType = IList->getInit(Index)->getType();
988 if (!IType->isVectorType()) {
989 CheckSubElementType(IList, elementType, Index,
990 StructuredList, StructuredIndex);
991 ++numEltsInit;
992 } else {
John McCall183700f2009-09-21 23:43:11 +0000993 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000994 unsigned numIElts = IVT->getNumElements();
995 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
996 numIElts);
997 CheckSubElementType(IList, VecType, Index,
998 StructuredList, StructuredIndex);
999 numEltsInit += numIElts;
1000 }
1001 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001002 }
Mike Stump1eb44332009-09-09 15:08:12 +00001003
Nate Begeman2ef13e52009-08-10 23:49:36 +00001004 // OpenCL & AltiVec require all elements to be initialized.
1005 if (numEltsInit != maxElements)
1006 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
1007 SemaRef.Diag(IList->getSourceRange().getBegin(),
1008 diag::err_vector_incorrect_num_initializers)
1009 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +00001010 }
1011}
1012
Mike Stump1eb44332009-09-09 15:08:12 +00001013void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001014 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001015 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001016 unsigned &Index,
1017 InitListExpr *StructuredList,
1018 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001019 // Check for the special-case of initializing an array with a string.
1020 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +00001021 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
1022 SemaRef.Context)) {
1023 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +00001024 // We place the string literal directly into the resulting
1025 // initializer list. This is the only place where the structure
1026 // of the structured initializer list doesn't match exactly,
1027 // because doing so would involve allocating one character
1028 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +00001029 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +00001030 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001031 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001032 return;
1033 }
1034 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001035 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +00001036 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001037 // Check for VLAs; in standard C it would be possible to check this
1038 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1039 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +00001040 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001041 diag::err_variable_object_no_init)
1042 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001043 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001044 ++Index;
1045 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001046 return;
1047 }
1048
Douglas Gregor05c13a32009-01-22 00:58:24 +00001049 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001050 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1051 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001052 bool maxElementsKnown = false;
1053 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +00001054 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001055 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001056 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001057 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001058 maxElementsKnown = true;
1059 }
1060
Chris Lattner08202542009-02-24 22:50:46 +00001061 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001062 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001063 while (Index < IList->getNumInits()) {
1064 Expr *Init = IList->getInit(Index);
1065 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001066 // If we're not the subobject that matches up with the '{' for
1067 // the designator, we shouldn't be handling the
1068 // designator. Return immediately.
1069 if (!SubobjectIsDesignatorContext)
1070 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001071
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001072 // Handle this designated initializer. elementIndex will be
1073 // updated to be the next array element we'll initialize.
Mike Stump1eb44332009-09-09 15:08:12 +00001074 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001075 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001076 StructuredList, StructuredIndex, true,
1077 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001078 hadError = true;
1079 continue;
1080 }
1081
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001082 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1083 maxElements.extend(elementIndex.getBitWidth());
1084 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1085 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001086 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001087
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001088 // If the array is of incomplete type, keep track of the number of
1089 // elements in the initializer.
1090 if (!maxElementsKnown && elementIndex > maxElements)
1091 maxElements = elementIndex;
1092
Douglas Gregor05c13a32009-01-22 00:58:24 +00001093 continue;
1094 }
1095
1096 // If we know the maximum number of elements, and we've already
1097 // hit it, stop consuming elements in the initializer list.
1098 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001099 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001100
1101 // Check this element.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001102 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001103 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001104 ++elementIndex;
1105
1106 // If the array is of incomplete type, keep track of the number of
1107 // elements in the initializer.
1108 if (!maxElementsKnown && elementIndex > maxElements)
1109 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001110 }
Eli Friedman587cbdf2009-05-29 20:17:55 +00001111 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001112 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001113 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001114 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001115 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001116 // Sizing an array implicitly to zero is not allowed by ISO C,
1117 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001118 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001119 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001120 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001121
Mike Stump1eb44332009-09-09 15:08:12 +00001122 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001123 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001124 }
1125}
1126
Mike Stump1eb44332009-09-09 15:08:12 +00001127void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
1128 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001129 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001130 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001131 unsigned &Index,
1132 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001133 unsigned &StructuredIndex,
1134 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001135 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001136
Eli Friedmanb85f7072008-05-19 19:16:24 +00001137 // If the record is invalid, some of it's members are invalid. To avoid
1138 // confusion, we forgo checking the intializer for the entire record.
1139 if (structDecl->isInvalidDecl()) {
1140 hadError = true;
1141 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001142 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001143
1144 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1145 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001146 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001147 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001148 Field != FieldEnd; ++Field) {
1149 if (Field->getDeclName()) {
1150 StructuredList->setInitializedFieldInUnion(*Field);
1151 break;
1152 }
1153 }
1154 return;
1155 }
1156
Douglas Gregor05c13a32009-01-22 00:58:24 +00001157 // If structDecl is a forward declaration, this loop won't do
1158 // anything except look at designated initializers; That's okay,
1159 // because an error should get printed out elsewhere. It might be
1160 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001161 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001162 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001163 bool InitializedSomething = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001164 while (Index < IList->getNumInits()) {
1165 Expr *Init = IList->getInit(Index);
1166
1167 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001168 // If we're not the subobject that matches up with the '{' for
1169 // the designator, we shouldn't be handling the
1170 // designator. Return immediately.
1171 if (!SubobjectIsDesignatorContext)
1172 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001173
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001174 // Handle this designated initializer. Field will be updated to
1175 // the next field that we'll be initializing.
Mike Stump1eb44332009-09-09 15:08:12 +00001176 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001177 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001178 StructuredList, StructuredIndex,
1179 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001180 hadError = true;
1181
Douglas Gregordfb5e592009-02-12 19:00:39 +00001182 InitializedSomething = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001183 continue;
1184 }
1185
1186 if (Field == FieldEnd) {
1187 // We've run out of fields. We're done.
1188 break;
1189 }
1190
Douglas Gregordfb5e592009-02-12 19:00:39 +00001191 // We've already initialized a member of a union. We're done.
1192 if (InitializedSomething && DeclType->isUnionType())
1193 break;
1194
Douglas Gregor44b43212008-12-11 16:49:14 +00001195 // If we've hit the flexible array member at the end, we're done.
1196 if (Field->getType()->isIncompleteArrayType())
1197 break;
1198
Douglas Gregor0bb76892009-01-29 16:53:55 +00001199 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001200 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001201 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001202 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001203 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001204
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001205 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001206 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001207 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001208
1209 if (DeclType->isUnionType()) {
1210 // Initialize the first field within the union.
1211 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001212 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001213
1214 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001215 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001216
Mike Stump1eb44332009-09-09 15:08:12 +00001217 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001218 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001219 return;
1220
1221 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001222 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001223 (!isa<InitListExpr>(IList->getInit(Index)) ||
1224 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001225 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001226 diag::err_flexible_array_init_nonempty)
1227 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001228 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001229 << *Field;
1230 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001231 ++Index;
1232 return;
1233 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001234 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001235 diag::ext_flexible_array_init)
1236 << IList->getInit(Index)->getSourceRange().getBegin();
1237 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1238 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001239 }
1240
Douglas Gregora6457962009-03-20 00:32:56 +00001241 if (isa<InitListExpr>(IList->getInit(Index)))
1242 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1243 StructuredIndex);
1244 else
1245 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1246 StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001247}
Steve Naroff0cca7492008-05-01 22:18:59 +00001248
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001249/// \brief Expand a field designator that refers to a member of an
1250/// anonymous struct or union into a series of field designators that
1251/// refers to the field within the appropriate subobject.
1252///
1253/// Field/FieldIndex will be updated to point to the (new)
1254/// currently-designated field.
1255static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001256 DesignatedInitExpr *DIE,
1257 unsigned DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001258 FieldDecl *Field,
1259 RecordDecl::field_iterator &FieldIter,
1260 unsigned &FieldIndex) {
1261 typedef DesignatedInitExpr::Designator Designator;
1262
1263 // Build the path from the current object to the member of the
1264 // anonymous struct/union (backwards).
1265 llvm::SmallVector<FieldDecl *, 4> Path;
1266 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump1eb44332009-09-09 15:08:12 +00001267
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001268 // Build the replacement designators.
1269 llvm::SmallVector<Designator, 4> Replacements;
1270 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1271 FI = Path.rbegin(), FIEnd = Path.rend();
1272 FI != FIEnd; ++FI) {
1273 if (FI + 1 == FIEnd)
Mike Stump1eb44332009-09-09 15:08:12 +00001274 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001275 DIE->getDesignator(DesigIdx)->getDotLoc(),
1276 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1277 else
1278 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1279 SourceLocation()));
1280 Replacements.back().setField(*FI);
1281 }
1282
1283 // Expand the current designator into the set of replacement
1284 // designators, so we have a full subobject path down to where the
1285 // member of the anonymous struct/union is actually stored.
Mike Stump1eb44332009-09-09 15:08:12 +00001286 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001287 &Replacements[0] + Replacements.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001288
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001289 // Update FieldIter/FieldIndex;
1290 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001291 FieldIter = Record->field_begin();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001292 FieldIndex = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001293 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001294 FieldIter != FEnd; ++FieldIter) {
1295 if (FieldIter->isUnnamedBitfield())
1296 continue;
1297
1298 if (*FieldIter == Path.back())
1299 return;
1300
1301 ++FieldIndex;
1302 }
1303
1304 assert(false && "Unable to find anonymous struct/union field");
1305}
1306
Douglas Gregor05c13a32009-01-22 00:58:24 +00001307/// @brief Check the well-formedness of a C99 designated initializer.
1308///
1309/// Determines whether the designated initializer @p DIE, which
1310/// resides at the given @p Index within the initializer list @p
1311/// IList, is well-formed for a current object of type @p DeclType
1312/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001313/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001314/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001315///
1316/// @param IList The initializer list in which this designated
1317/// initializer occurs.
1318///
Douglas Gregor71199712009-04-15 04:56:10 +00001319/// @param DIE The designated initializer expression.
1320///
1321/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001322///
1323/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1324/// into which the designation in @p DIE should refer.
1325///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001326/// @param NextField If non-NULL and the first designator in @p DIE is
1327/// a field, this will be set to the field declaration corresponding
1328/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001329///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001330/// @param NextElementIndex If non-NULL and the first designator in @p
1331/// DIE is an array designator or GNU array-range designator, this
1332/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001333///
1334/// @param Index Index into @p IList where the designated initializer
1335/// @p DIE occurs.
1336///
Douglas Gregor4c678342009-01-28 21:54:33 +00001337/// @param StructuredList The initializer list expression that
1338/// describes all of the subobject initializers in the order they'll
1339/// actually be initialized.
1340///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001341/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001342bool
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001343InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001344 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001345 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001346 QualType &CurrentObjectType,
1347 RecordDecl::field_iterator *NextField,
1348 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001349 unsigned &Index,
1350 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001351 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001352 bool FinishSubobjectInit,
1353 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001354 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001355 // Check the actual initialization for the designated object type.
1356 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001357
1358 // Temporarily remove the designator expression from the
1359 // initializer list that the child calls see, so that we don't try
1360 // to re-process the designator.
1361 unsigned OldIndex = Index;
1362 IList->setInit(OldIndex, DIE->getInit());
1363
1364 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001365 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001366
1367 // Restore the designated initializer expression in the syntactic
1368 // form of the initializer list.
1369 if (IList->getInit(OldIndex) != DIE->getInit())
1370 DIE->setInit(IList->getInit(OldIndex));
1371 IList->setInit(OldIndex, DIE);
1372
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001373 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001374 }
1375
Douglas Gregor71199712009-04-15 04:56:10 +00001376 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001377 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001378 "Need a non-designated initializer list to start from");
1379
Douglas Gregor71199712009-04-15 04:56:10 +00001380 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001381 // Determine the structural initializer list that corresponds to the
1382 // current subobject.
1383 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001384 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001385 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001386 SourceRange(D->getStartLocation(),
1387 DIE->getSourceRange().getEnd()));
1388 assert(StructuredList && "Expected a structured initializer list");
1389
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001390 if (D->isFieldDesignator()) {
1391 // C99 6.7.8p7:
1392 //
1393 // If a designator has the form
1394 //
1395 // . identifier
1396 //
1397 // then the current object (defined below) shall have
1398 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001399 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001400 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001401 if (!RT) {
1402 SourceLocation Loc = D->getDotLoc();
1403 if (Loc.isInvalid())
1404 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001405 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1406 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001407 ++Index;
1408 return true;
1409 }
1410
Douglas Gregor4c678342009-01-28 21:54:33 +00001411 // Note: we perform a linear search of the fields here, despite
1412 // the fact that we have a faster lookup method, because we always
1413 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001414 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001415 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001416 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001417 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001418 Field = RT->getDecl()->field_begin(),
1419 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001420 for (; Field != FieldEnd; ++Field) {
1421 if (Field->isUnnamedBitfield())
1422 continue;
1423
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001424 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor4c678342009-01-28 21:54:33 +00001425 break;
1426
1427 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001428 }
1429
Douglas Gregor4c678342009-01-28 21:54:33 +00001430 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001431 // There was no normal field in the struct with the designated
1432 // name. Perform another lookup for this name, which may find
1433 // something that we can't designate (e.g., a member function),
1434 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001435 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001436 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4c678342009-01-28 21:54:33 +00001437 if (Lookup.first == Lookup.second) {
1438 // Name lookup didn't find anything.
Chris Lattner08202542009-02-24 22:50:46 +00001439 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregor4c678342009-01-28 21:54:33 +00001440 << FieldName << CurrentObjectType;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001441 ++Index;
1442 return true;
1443 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1444 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1445 ->isAnonymousStructOrUnion()) {
1446 // Handle an field designator that refers to a member of an
1447 // anonymous struct or union.
Mike Stump1eb44332009-09-09 15:08:12 +00001448 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001449 cast<FieldDecl>(*Lookup.first),
1450 Field, FieldIndex);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001451 D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001452 } else {
1453 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001454 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001455 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001456 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001457 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001458 ++Index;
1459 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001460 }
1461 } else if (!KnownField &&
1462 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor4c678342009-01-28 21:54:33 +00001463 ->isAnonymousStructOrUnion()) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001464 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1465 Field, FieldIndex);
1466 D = DIE->getDesignator(DesigIdx);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001467 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001468
1469 // All of the fields of a union are located at the same place in
1470 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001471 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001472 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001473 StructuredList->setInitializedFieldInUnion(*Field);
1474 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001475
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001476 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001477 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001478
Douglas Gregor4c678342009-01-28 21:54:33 +00001479 // Make sure that our non-designated initializer list has space
1480 // for a subobject corresponding to this field.
1481 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001482 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001483
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001484 // This designator names a flexible array member.
1485 if (Field->getType()->isIncompleteArrayType()) {
1486 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001487 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001488 // We can't designate an object within the flexible array
1489 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001490 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001491 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001492 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001493 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001494 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001495 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001496 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001497 << *Field;
1498 Invalid = true;
1499 }
1500
1501 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1502 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001503 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001504 diag::err_flexible_array_init_needs_braces)
1505 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001506 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001507 << *Field;
1508 Invalid = true;
1509 }
1510
1511 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001512 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001513 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001514 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001515 diag::err_flexible_array_init_nonempty)
1516 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001517 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001518 << *Field;
1519 Invalid = true;
1520 }
1521
1522 if (Invalid) {
1523 ++Index;
1524 return true;
1525 }
1526
1527 // Initialize the array.
1528 bool prevHadError = hadError;
1529 unsigned newStructuredIndex = FieldIndex;
1530 unsigned OldIndex = Index;
1531 IList->setInit(Index, DIE->getInit());
Mike Stump1eb44332009-09-09 15:08:12 +00001532 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001533 StructuredList, newStructuredIndex);
1534 IList->setInit(OldIndex, DIE);
1535 if (hadError && !prevHadError) {
1536 ++Field;
1537 ++FieldIndex;
1538 if (NextField)
1539 *NextField = Field;
1540 StructuredIndex = FieldIndex;
1541 return true;
1542 }
1543 } else {
1544 // Recurse to check later designated subobjects.
1545 QualType FieldType = (*Field)->getType();
1546 unsigned newStructuredIndex = FieldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001547 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1548 Index, StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001549 true, false))
1550 return true;
1551 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001552
1553 // Find the position of the next field to be initialized in this
1554 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001555 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001556 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001557
1558 // If this the first designator, our caller will continue checking
1559 // the rest of this struct/class/union subobject.
1560 if (IsFirstDesignator) {
1561 if (NextField)
1562 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001563 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001564 return false;
1565 }
1566
Douglas Gregor34e79462009-01-28 23:36:17 +00001567 if (!FinishSubobjectInit)
1568 return false;
1569
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001570 // We've already initialized something in the union; we're done.
1571 if (RT->getDecl()->isUnion())
1572 return hadError;
1573
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001574 // Check the remaining fields within this class/struct/union subobject.
1575 bool prevHadError = hadError;
Douglas Gregor4c678342009-01-28 21:54:33 +00001576 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1577 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001578 return hadError && !prevHadError;
1579 }
1580
1581 // C99 6.7.8p6:
1582 //
1583 // If a designator has the form
1584 //
1585 // [ constant-expression ]
1586 //
1587 // then the current object (defined below) shall have array
1588 // type and the expression shall be an integer constant
1589 // expression. If the array is of unknown size, any
1590 // nonnegative value is valid.
1591 //
1592 // Additionally, cope with the GNU extension that permits
1593 // designators of the form
1594 //
1595 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001596 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001597 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001598 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001599 << CurrentObjectType;
1600 ++Index;
1601 return true;
1602 }
1603
1604 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001605 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1606 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001607 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001608 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001609 DesignatedEndIndex = DesignatedStartIndex;
1610 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001611 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001612
Mike Stump1eb44332009-09-09 15:08:12 +00001613
1614 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001615 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001616 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001617 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001618 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001619
Chris Lattner3bf68932009-04-25 21:59:05 +00001620 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001621 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001622 }
1623
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001624 if (isa<ConstantArrayType>(AT)) {
1625 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001626 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1627 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1628 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1629 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1630 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001631 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001632 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001633 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001634 << IndexExpr->getSourceRange();
1635 ++Index;
1636 return true;
1637 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001638 } else {
1639 // Make sure the bit-widths and signedness match.
1640 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1641 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001642 else if (DesignatedStartIndex.getBitWidth() <
1643 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001644 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1645 DesignatedStartIndex.setIsUnsigned(true);
1646 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001647 }
Mike Stump1eb44332009-09-09 15:08:12 +00001648
Douglas Gregor4c678342009-01-28 21:54:33 +00001649 // Make sure that our non-designated initializer list has space
1650 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001651 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001652 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001653 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001654
Douglas Gregor34e79462009-01-28 23:36:17 +00001655 // Repeatedly perform subobject initializations in the range
1656 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001657
Douglas Gregor34e79462009-01-28 23:36:17 +00001658 // Move to the next designator
1659 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1660 unsigned OldIndex = Index;
Douglas Gregor34e79462009-01-28 23:36:17 +00001661 while (DesignatedStartIndex <= DesignatedEndIndex) {
1662 // Recurse to check later designated subobjects.
1663 QualType ElementType = AT->getElementType();
1664 Index = OldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001665 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1666 Index, StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001667 (DesignatedStartIndex == DesignatedEndIndex),
1668 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001669 return true;
1670
1671 // Move to the next index in the array that we'll be initializing.
1672 ++DesignatedStartIndex;
1673 ElementIndex = DesignatedStartIndex.getZExtValue();
1674 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001675
1676 // If this the first designator, our caller will continue checking
1677 // the rest of this array subobject.
1678 if (IsFirstDesignator) {
1679 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001680 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001681 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001682 return false;
1683 }
Mike Stump1eb44332009-09-09 15:08:12 +00001684
Douglas Gregor34e79462009-01-28 23:36:17 +00001685 if (!FinishSubobjectInit)
1686 return false;
1687
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001688 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001689 bool prevHadError = hadError;
Douglas Gregorfdf55692009-02-09 19:45:19 +00001690 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001691 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001692 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001693}
1694
Douglas Gregor4c678342009-01-28 21:54:33 +00001695// Get the structured initializer list for a subobject of type
1696// @p CurrentObjectType.
1697InitListExpr *
1698InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1699 QualType CurrentObjectType,
1700 InitListExpr *StructuredList,
1701 unsigned StructuredIndex,
1702 SourceRange InitRange) {
1703 Expr *ExistingInit = 0;
1704 if (!StructuredList)
1705 ExistingInit = SyntacticToSemantic[IList];
1706 else if (StructuredIndex < StructuredList->getNumInits())
1707 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001708
Douglas Gregor4c678342009-01-28 21:54:33 +00001709 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1710 return Result;
1711
1712 if (ExistingInit) {
1713 // We are creating an initializer list that initializes the
1714 // subobjects of the current object, but there was already an
1715 // initialization that completely initialized the current
1716 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001717 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001718 // struct X { int a, b; };
1719 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001720 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001721 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1722 // designated initializer re-initializes the whole
1723 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001724 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001725 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001726 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001727 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001728 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001729 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001730 << ExistingInit->getSourceRange();
1731 }
1732
Mike Stump1eb44332009-09-09 15:08:12 +00001733 InitListExpr *Result
1734 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001735 InitRange.getEnd());
1736
Douglas Gregor4c678342009-01-28 21:54:33 +00001737 Result->setType(CurrentObjectType);
1738
Douglas Gregorfa219202009-03-20 23:58:33 +00001739 // Pre-allocate storage for the structured initializer list.
1740 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001741 unsigned NumInits = 0;
1742 if (!StructuredList)
1743 NumInits = IList->getNumInits();
1744 else if (Index < IList->getNumInits()) {
1745 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1746 NumInits = SubList->getNumInits();
1747 }
1748
Mike Stump1eb44332009-09-09 15:08:12 +00001749 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001750 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1751 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1752 NumElements = CAType->getSize().getZExtValue();
1753 // Simple heuristic so that we don't allocate a very large
1754 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001755 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001756 NumElements = 0;
1757 }
John McCall183700f2009-09-21 23:43:11 +00001758 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001759 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001760 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001761 RecordDecl *RDecl = RType->getDecl();
1762 if (RDecl->isUnion())
1763 NumElements = 1;
1764 else
Mike Stump1eb44332009-09-09 15:08:12 +00001765 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001766 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001767 }
1768
Douglas Gregor08457732009-03-21 18:13:52 +00001769 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001770 NumElements = IList->getNumInits();
1771
1772 Result->reserveInits(NumElements);
1773
Douglas Gregor4c678342009-01-28 21:54:33 +00001774 // Link this new initializer list into the structured initializer
1775 // lists.
1776 if (StructuredList)
1777 StructuredList->updateInit(StructuredIndex, Result);
1778 else {
1779 Result->setSyntacticForm(IList);
1780 SyntacticToSemantic[IList] = Result;
1781 }
1782
1783 return Result;
1784}
1785
1786/// Update the initializer at index @p StructuredIndex within the
1787/// structured initializer list to the value @p expr.
1788void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1789 unsigned &StructuredIndex,
1790 Expr *expr) {
1791 // No structured initializer list to update
1792 if (!StructuredList)
1793 return;
1794
1795 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1796 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001797 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001798 diag::warn_initializer_overrides)
1799 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001800 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001801 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001802 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001803 << PrevInit->getSourceRange();
1804 }
Mike Stump1eb44332009-09-09 15:08:12 +00001805
Douglas Gregor4c678342009-01-28 21:54:33 +00001806 ++StructuredIndex;
1807}
1808
Douglas Gregor05c13a32009-01-22 00:58:24 +00001809/// Check that the given Index expression is a valid array designator
1810/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001811/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001812/// and produces a reasonable diagnostic if there is a
1813/// failure. Returns true if there was an error, false otherwise. If
1814/// everything went okay, Value will receive the value of the constant
1815/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001816static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001817CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001818 SourceLocation Loc = Index->getSourceRange().getBegin();
1819
1820 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001821 if (S.VerifyIntegerConstantExpression(Index, &Value))
1822 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001823
Chris Lattner3bf68932009-04-25 21:59:05 +00001824 if (Value.isSigned() && Value.isNegative())
1825 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001826 << Value.toString(10) << Index->getSourceRange();
1827
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001828 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001829 return false;
1830}
1831
1832Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1833 SourceLocation Loc,
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001834 bool GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001835 OwningExprResult Init) {
1836 typedef DesignatedInitExpr::Designator ASTDesignator;
1837
1838 bool Invalid = false;
1839 llvm::SmallVector<ASTDesignator, 32> Designators;
1840 llvm::SmallVector<Expr *, 32> InitExpressions;
1841
1842 // Build designators and check array designator expressions.
1843 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1844 const Designator &D = Desig.getDesignator(Idx);
1845 switch (D.getKind()) {
1846 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001847 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001848 D.getFieldLoc()));
1849 break;
1850
1851 case Designator::ArrayDesignator: {
1852 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1853 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001854 if (!Index->isTypeDependent() &&
1855 !Index->isValueDependent() &&
1856 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001857 Invalid = true;
1858 else {
1859 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001860 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001861 D.getRBracketLoc()));
1862 InitExpressions.push_back(Index);
1863 }
1864 break;
1865 }
1866
1867 case Designator::ArrayRangeDesignator: {
1868 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1869 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1870 llvm::APSInt StartValue;
1871 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001872 bool StartDependent = StartIndex->isTypeDependent() ||
1873 StartIndex->isValueDependent();
1874 bool EndDependent = EndIndex->isTypeDependent() ||
1875 EndIndex->isValueDependent();
1876 if ((!StartDependent &&
1877 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1878 (!EndDependent &&
1879 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001880 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001881 else {
1882 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001883 if (StartDependent || EndDependent) {
1884 // Nothing to compute.
1885 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregord6f584f2009-01-23 22:22:29 +00001886 EndValue.extend(StartValue.getBitWidth());
1887 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1888 StartValue.extend(EndValue.getBitWidth());
1889
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001890 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001891 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001892 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001893 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1894 Invalid = true;
1895 } else {
1896 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001897 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001898 D.getEllipsisLoc(),
1899 D.getRBracketLoc()));
1900 InitExpressions.push_back(StartIndex);
1901 InitExpressions.push_back(EndIndex);
1902 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001903 }
1904 break;
1905 }
1906 }
1907 }
1908
1909 if (Invalid || Init.isInvalid())
1910 return ExprError();
1911
1912 // Clear out the expressions within the designation.
1913 Desig.ClearExprs(*this);
1914
1915 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001916 = DesignatedInitExpr::Create(Context,
1917 Designators.data(), Designators.size(),
1918 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001919 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001920 return Owned(DIE);
1921}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001922
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001923bool Sema::CheckInitList(const InitializedEntity &Entity,
1924 InitListExpr *&InitList, QualType &DeclType) {
1925 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001926 if (!CheckInitList.HadError())
1927 InitList = CheckInitList.getFullyStructuredList();
1928
1929 return CheckInitList.HadError();
1930}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001931
Douglas Gregor20093b42009-12-09 23:02:17 +00001932//===----------------------------------------------------------------------===//
1933// Initialization entity
1934//===----------------------------------------------------------------------===//
1935
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001936InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1937 const InitializedEntity &Parent)
1938 : Kind(EK_ArrayOrVectorElement), Parent(&Parent), Index(Index)
1939{
1940 if (isa<ArrayType>(Parent.TL.getType())) {
1941 TL = cast<ArrayTypeLoc>(Parent.TL).getElementLoc();
1942 return;
1943 }
1944
1945 // FIXME: should be able to get type location information for vectors, too.
1946
1947 QualType T;
1948 if (const ArrayType *AT = Context.getAsArrayType(Parent.TL.getType()))
1949 T = AT->getElementType();
1950 else
1951 T = Parent.TL.getType()->getAs<VectorType>()->getElementType();
1952
1953 // FIXME: Once we've gone through the effort to create the fake
1954 // TypeSourceInfo, should we cache it somewhere? (If not, we "leak" it).
1955 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(T);
1956 DI->getTypeLoc().initialize(Parent.TL.getSourceRange().getBegin());
1957 TL = DI->getTypeLoc();
1958}
1959
Douglas Gregor20093b42009-12-09 23:02:17 +00001960void InitializedEntity::InitDeclLoc() {
1961 assert((Kind == EK_Variable || Kind == EK_Parameter || Kind == EK_Member) &&
1962 "InitDeclLoc cannot be used with non-declaration entities.");
1963
1964 if (TypeSourceInfo *DI = VariableOrMember->getTypeSourceInfo()) {
1965 TL = DI->getTypeLoc();
1966 return;
1967 }
1968
1969 // FIXME: Once we've gone through the effort to create the fake
1970 // TypeSourceInfo, should we cache it in the declaration?
1971 // (If not, we "leak" it).
1972 TypeSourceInfo *DI = VariableOrMember->getASTContext()
1973 .CreateTypeSourceInfo(VariableOrMember->getType());
1974 DI->getTypeLoc().initialize(VariableOrMember->getLocation());
1975 TL = DI->getTypeLoc();
1976}
1977
1978InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1979 CXXBaseSpecifier *Base)
1980{
1981 InitializedEntity Result;
1982 Result.Kind = EK_Base;
1983 Result.Base = Base;
1984 // FIXME: CXXBaseSpecifier should store a TypeLoc.
1985 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Base->getType());
1986 DI->getTypeLoc().initialize(Base->getSourceRange().getBegin());
1987 Result.TL = DI->getTypeLoc();
1988 return Result;
1989}
1990
Douglas Gregor99a2e602009-12-16 01:38:02 +00001991DeclarationName InitializedEntity::getName() const {
1992 switch (getKind()) {
1993 case EK_Variable:
1994 case EK_Parameter:
1995 case EK_Member:
1996 return VariableOrMember->getDeclName();
1997
1998 case EK_Result:
1999 case EK_Exception:
2000 case EK_Temporary:
2001 case EK_Base:
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002002 case EK_ArrayOrVectorElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002003 return DeclarationName();
2004 }
2005
2006 // Silence GCC warning
2007 return DeclarationName();
2008}
2009
Douglas Gregor20093b42009-12-09 23:02:17 +00002010//===----------------------------------------------------------------------===//
2011// Initialization sequence
2012//===----------------------------------------------------------------------===//
2013
2014void InitializationSequence::Step::Destroy() {
2015 switch (Kind) {
2016 case SK_ResolveAddressOfOverloadedFunction:
2017 case SK_CastDerivedToBaseRValue:
2018 case SK_CastDerivedToBaseLValue:
2019 case SK_BindReference:
2020 case SK_BindReferenceToTemporary:
2021 case SK_UserConversion:
2022 case SK_QualificationConversionRValue:
2023 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002024 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002025 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002026 case SK_ZeroInitialization:
Douglas Gregor20093b42009-12-09 23:02:17 +00002027 break;
2028
2029 case SK_ConversionSequence:
2030 delete ICS;
2031 }
2032}
2033
2034void InitializationSequence::AddAddressOverloadResolutionStep(
2035 FunctionDecl *Function) {
2036 Step S;
2037 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2038 S.Type = Function->getType();
2039 S.Function = Function;
2040 Steps.push_back(S);
2041}
2042
2043void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2044 bool IsLValue) {
2045 Step S;
2046 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
2047 S.Type = BaseType;
2048 Steps.push_back(S);
2049}
2050
2051void InitializationSequence::AddReferenceBindingStep(QualType T,
2052 bool BindingTemporary) {
2053 Step S;
2054 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2055 S.Type = T;
2056 Steps.push_back(S);
2057}
2058
Eli Friedman03981012009-12-11 02:42:07 +00002059void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2060 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002061 Step S;
2062 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002063 S.Type = T;
Douglas Gregor20093b42009-12-09 23:02:17 +00002064 S.Function = Function;
2065 Steps.push_back(S);
2066}
2067
2068void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2069 bool IsLValue) {
2070 Step S;
2071 S.Kind = IsLValue? SK_QualificationConversionLValue
2072 : SK_QualificationConversionRValue;
2073 S.Type = Ty;
2074 Steps.push_back(S);
2075}
2076
2077void InitializationSequence::AddConversionSequenceStep(
2078 const ImplicitConversionSequence &ICS,
2079 QualType T) {
2080 Step S;
2081 S.Kind = SK_ConversionSequence;
2082 S.Type = T;
2083 S.ICS = new ImplicitConversionSequence(ICS);
2084 Steps.push_back(S);
2085}
2086
Douglas Gregord87b61f2009-12-10 17:56:55 +00002087void InitializationSequence::AddListInitializationStep(QualType T) {
2088 Step S;
2089 S.Kind = SK_ListInitialization;
2090 S.Type = T;
2091 Steps.push_back(S);
2092}
2093
Douglas Gregor51c56d62009-12-14 20:49:26 +00002094void
2095InitializationSequence::AddConstructorInitializationStep(
2096 CXXConstructorDecl *Constructor,
2097 QualType T) {
2098 Step S;
2099 S.Kind = SK_ConstructorInitialization;
2100 S.Type = T;
2101 S.Function = Constructor;
2102 Steps.push_back(S);
2103}
2104
Douglas Gregor71d17402009-12-15 00:01:57 +00002105void InitializationSequence::AddZeroInitializationStep(QualType T) {
2106 Step S;
2107 S.Kind = SK_ZeroInitialization;
2108 S.Type = T;
2109 Steps.push_back(S);
2110}
2111
Douglas Gregor20093b42009-12-09 23:02:17 +00002112void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2113 OverloadingResult Result) {
2114 SequenceKind = FailedSequence;
2115 this->Failure = Failure;
2116 this->FailedOverloadResult = Result;
2117}
2118
2119//===----------------------------------------------------------------------===//
2120// Attempt initialization
2121//===----------------------------------------------------------------------===//
2122
2123/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregord87b61f2009-12-10 17:56:55 +00002124static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002125 const InitializedEntity &Entity,
2126 const InitializationKind &Kind,
2127 InitListExpr *InitList,
2128 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002129 // FIXME: We only perform rudimentary checking of list
2130 // initializations at this point, then assume that any list
2131 // initialization of an array, aggregate, or scalar will be
2132 // well-formed. We we actually "perform" list initialization, we'll
2133 // do all of the necessary checking. C++0x initializer lists will
2134 // force us to perform more checking here.
2135 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2136
2137 QualType DestType = Entity.getType().getType();
2138
2139 // C++ [dcl.init]p13:
2140 // If T is a scalar type, then a declaration of the form
2141 //
2142 // T x = { a };
2143 //
2144 // is equivalent to
2145 //
2146 // T x = a;
2147 if (DestType->isScalarType()) {
2148 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2149 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2150 return;
2151 }
2152
2153 // Assume scalar initialization from a single value works.
2154 } else if (DestType->isAggregateType()) {
2155 // Assume aggregate initialization works.
2156 } else if (DestType->isVectorType()) {
2157 // Assume vector initialization works.
2158 } else if (DestType->isReferenceType()) {
2159 // FIXME: C++0x defines behavior for this.
2160 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2161 return;
2162 } else if (DestType->isRecordType()) {
2163 // FIXME: C++0x defines behavior for this
2164 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2165 }
2166
2167 // Add a general "list initialization" step.
2168 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002169}
2170
2171/// \brief Try a reference initialization that involves calling a conversion
2172/// function.
2173///
2174/// FIXME: look intos DRs 656, 896
2175static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2176 const InitializedEntity &Entity,
2177 const InitializationKind &Kind,
2178 Expr *Initializer,
2179 bool AllowRValues,
2180 InitializationSequence &Sequence) {
2181 QualType DestType = Entity.getType().getType();
2182 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2183 QualType T1 = cv1T1.getUnqualifiedType();
2184 QualType cv2T2 = Initializer->getType();
2185 QualType T2 = cv2T2.getUnqualifiedType();
2186
2187 bool DerivedToBase;
2188 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2189 T1, T2, DerivedToBase) &&
2190 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002191 (void)DerivedToBase;
Douglas Gregor20093b42009-12-09 23:02:17 +00002192
2193 // Build the candidate set directly in the initialization sequence
2194 // structure, so that it will persist if we fail.
2195 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2196 CandidateSet.clear();
2197
2198 // Determine whether we are allowed to call explicit constructors or
2199 // explicit conversion operators.
2200 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2201
2202 const RecordType *T1RecordType = 0;
2203 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2204 // The type we're converting to is a class type. Enumerate its constructors
2205 // to see if there is a suitable conversion.
2206 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2207
2208 DeclarationName ConstructorName
2209 = S.Context.DeclarationNames.getCXXConstructorName(
2210 S.Context.getCanonicalType(T1).getUnqualifiedType());
2211 DeclContext::lookup_iterator Con, ConEnd;
2212 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2213 Con != ConEnd; ++Con) {
2214 // Find the constructor (which may be a template).
2215 CXXConstructorDecl *Constructor = 0;
2216 FunctionTemplateDecl *ConstructorTmpl
2217 = dyn_cast<FunctionTemplateDecl>(*Con);
2218 if (ConstructorTmpl)
2219 Constructor = cast<CXXConstructorDecl>(
2220 ConstructorTmpl->getTemplatedDecl());
2221 else
2222 Constructor = cast<CXXConstructorDecl>(*Con);
2223
2224 if (!Constructor->isInvalidDecl() &&
2225 Constructor->isConvertingConstructor(AllowExplicit)) {
2226 if (ConstructorTmpl)
2227 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2228 &Initializer, 1, CandidateSet);
2229 else
2230 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2231 }
2232 }
2233 }
2234
2235 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2236 // The type we're converting from is a class type, enumerate its conversion
2237 // functions.
2238 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2239
2240 // Determine the type we are converting to. If we are allowed to
2241 // convert to an rvalue, take the type that the destination type
2242 // refers to.
2243 QualType ToType = AllowRValues? cv1T1 : DestType;
2244
2245 const UnresolvedSet *Conversions
2246 = T2RecordDecl->getVisibleConversionFunctions();
2247 for (UnresolvedSet::iterator I = Conversions->begin(),
2248 E = Conversions->end();
2249 I != E; ++I) {
2250 NamedDecl *D = *I;
2251 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2252 if (isa<UsingShadowDecl>(D))
2253 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2254
2255 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2256 CXXConversionDecl *Conv;
2257 if (ConvTemplate)
2258 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2259 else
2260 Conv = cast<CXXConversionDecl>(*I);
2261
2262 // If the conversion function doesn't return a reference type,
2263 // it can't be considered for this conversion unless we're allowed to
2264 // consider rvalues.
2265 // FIXME: Do we need to make sure that we only consider conversion
2266 // candidates with reference-compatible results? That might be needed to
2267 // break recursion.
2268 if ((AllowExplicit || !Conv->isExplicit()) &&
2269 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2270 if (ConvTemplate)
2271 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2272 ToType, CandidateSet);
2273 else
2274 S.AddConversionCandidate(Conv, ActingDC, Initializer, cv1T1,
2275 CandidateSet);
2276 }
2277 }
2278 }
2279
2280 SourceLocation DeclLoc = Initializer->getLocStart();
2281
2282 // Perform overload resolution. If it fails, return the failed result.
2283 OverloadCandidateSet::iterator Best;
2284 if (OverloadingResult Result
2285 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2286 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002287
Douglas Gregor20093b42009-12-09 23:02:17 +00002288 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002289
2290 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002291 if (isa<CXXConversionDecl>(Function))
2292 T2 = Function->getResultType();
2293 else
2294 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002295
2296 // Add the user-defined conversion step.
2297 Sequence.AddUserConversionStep(Function, T2.getNonReferenceType());
2298
2299 // Determine whether we need to perform derived-to-base or
2300 // cv-qualification adjustments.
Douglas Gregor20093b42009-12-09 23:02:17 +00002301 bool NewDerivedToBase = false;
2302 Sema::ReferenceCompareResult NewRefRelationship
2303 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2304 NewDerivedToBase);
2305 assert(NewRefRelationship != Sema::Ref_Incompatible &&
2306 "Overload resolution picked a bad conversion function");
2307 (void)NewRefRelationship;
2308 if (NewDerivedToBase)
2309 Sequence.AddDerivedToBaseCastStep(
2310 S.Context.getQualifiedType(T1,
2311 T2.getNonReferenceType().getQualifiers()),
2312 /*isLValue=*/true);
2313
2314 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2315 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2316
2317 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2318 return OR_Success;
2319}
2320
2321/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2322static void TryReferenceInitialization(Sema &S,
2323 const InitializedEntity &Entity,
2324 const InitializationKind &Kind,
2325 Expr *Initializer,
2326 InitializationSequence &Sequence) {
2327 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2328
2329 QualType DestType = Entity.getType().getType();
2330 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2331 QualType T1 = cv1T1.getUnqualifiedType();
2332 QualType cv2T2 = Initializer->getType();
2333 QualType T2 = cv2T2.getUnqualifiedType();
2334 SourceLocation DeclLoc = Initializer->getLocStart();
2335
2336 // If the initializer is the address of an overloaded function, try
2337 // to resolve the overloaded function. If all goes well, T2 is the
2338 // type of the resulting function.
2339 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2340 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2341 T1,
2342 false);
2343 if (!Fn) {
2344 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2345 return;
2346 }
2347
2348 Sequence.AddAddressOverloadResolutionStep(Fn);
2349 cv2T2 = Fn->getType();
2350 T2 = cv2T2.getUnqualifiedType();
2351 }
2352
2353 // FIXME: Rvalue references
2354 bool ForceRValue = false;
2355
2356 // Compute some basic properties of the types and the initializer.
2357 bool isLValueRef = DestType->isLValueReferenceType();
2358 bool isRValueRef = !isLValueRef;
2359 bool DerivedToBase = false;
2360 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2361 Initializer->isLvalue(S.Context);
2362 Sema::ReferenceCompareResult RefRelationship
2363 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2364
2365 // C++0x [dcl.init.ref]p5:
2366 // A reference to type "cv1 T1" is initialized by an expression of type
2367 // "cv2 T2" as follows:
2368 //
2369 // - If the reference is an lvalue reference and the initializer
2370 // expression
2371 OverloadingResult ConvOvlResult = OR_Success;
2372 if (isLValueRef) {
2373 if (InitLvalue == Expr::LV_Valid &&
2374 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2375 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2376 // reference-compatible with "cv2 T2," or
2377 //
2378 // Per C++ [over.best.ics]p2, we ignore whether the lvalue is a
2379 // bit-field when we're determining whether the reference initialization
2380 // can occur. This property will be checked by PerformInitialization.
2381 if (DerivedToBase)
2382 Sequence.AddDerivedToBaseCastStep(
2383 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()),
2384 /*isLValue=*/true);
2385 if (cv1T1.getQualifiers() != cv2T2.getQualifiers())
2386 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
2387 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/false);
2388 return;
2389 }
2390
2391 // - has a class type (i.e., T2 is a class type), where T1 is not
2392 // reference-related to T2, and can be implicitly converted to an
2393 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2394 // with "cv3 T3" (this conversion is selected by enumerating the
2395 // applicable conversion functions (13.3.1.6) and choosing the best
2396 // one through overload resolution (13.3)),
2397 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2398 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2399 Initializer,
2400 /*AllowRValues=*/false,
2401 Sequence);
2402 if (ConvOvlResult == OR_Success)
2403 return;
2404 }
2405 }
2406
2407 // - Otherwise, the reference shall be an lvalue reference to a
2408 // non-volatile const type (i.e., cv1 shall be const), or the reference
2409 // shall be an rvalue reference and the initializer expression shall
2410 // be an rvalue.
2411 if (!((isLValueRef && cv1T1.getCVRQualifiers() == Qualifiers::Const) ||
2412 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2413 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2414 Sequence.SetOverloadFailure(
2415 InitializationSequence::FK_ReferenceInitOverloadFailed,
2416 ConvOvlResult);
2417 else if (isLValueRef)
2418 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2419 ? (RefRelationship == Sema::Ref_Related
2420 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2421 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2422 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2423 else
2424 Sequence.SetFailed(
2425 InitializationSequence::FK_RValueReferenceBindingToLValue);
2426
2427 return;
2428 }
2429
2430 // - If T1 and T2 are class types and
2431 if (T1->isRecordType() && T2->isRecordType()) {
2432 // - the initializer expression is an rvalue and "cv1 T1" is
2433 // reference-compatible with "cv2 T2", or
2434 if (InitLvalue != Expr::LV_Valid &&
2435 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2436 if (DerivedToBase)
2437 Sequence.AddDerivedToBaseCastStep(
2438 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()),
2439 /*isLValue=*/false);
2440 if (cv1T1.getQualifiers() != cv2T2.getQualifiers())
2441 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2442 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2443 return;
2444 }
2445
2446 // - T1 is not reference-related to T2 and the initializer expression
2447 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2448 // conversion is selected by enumerating the applicable conversion
2449 // functions (13.3.1.6) and choosing the best one through overload
2450 // resolution (13.3)),
2451 if (RefRelationship == Sema::Ref_Incompatible) {
2452 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2453 Kind, Initializer,
2454 /*AllowRValues=*/true,
2455 Sequence);
2456 if (ConvOvlResult)
2457 Sequence.SetOverloadFailure(
2458 InitializationSequence::FK_ReferenceInitOverloadFailed,
2459 ConvOvlResult);
2460
2461 return;
2462 }
2463
2464 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2465 return;
2466 }
2467
2468 // - If the initializer expression is an rvalue, with T2 an array type,
2469 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2470 // is bound to the object represented by the rvalue (see 3.10).
2471 // FIXME: How can an array type be reference-compatible with anything?
2472 // Don't we mean the element types of T1 and T2?
2473
2474 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2475 // from the initializer expression using the rules for a non-reference
2476 // copy initialization (8.5). The reference is then bound to the
2477 // temporary. [...]
2478 // Determine whether we are allowed to call explicit constructors or
2479 // explicit conversion operators.
2480 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2481 ImplicitConversionSequence ICS
2482 = S.TryImplicitConversion(Initializer, cv1T1,
2483 /*SuppressUserConversions=*/false, AllowExplicit,
2484 /*ForceRValue=*/false,
2485 /*FIXME:InOverloadResolution=*/false,
2486 /*UserCast=*/Kind.isExplicitCast());
2487
2488 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
2489 // FIXME: Use the conversion function set stored in ICS to turn
2490 // this into an overloading ambiguity diagnostic. However, we need
2491 // to keep that set as an OverloadCandidateSet rather than as some
2492 // other kind of set.
2493 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
2494 return;
2495 }
2496
2497 // [...] If T1 is reference-related to T2, cv1 must be the
2498 // same cv-qualification as, or greater cv-qualification
2499 // than, cv2; otherwise, the program is ill-formed.
2500 if (RefRelationship == Sema::Ref_Related &&
2501 !cv1T1.isAtLeastAsQualifiedAs(cv2T2)) {
2502 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2503 return;
2504 }
2505
2506 // Perform the actual conversion.
2507 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2508 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2509 return;
2510}
2511
2512/// \brief Attempt character array initialization from a string literal
2513/// (C++ [dcl.init.string], C99 6.7.8).
2514static void TryStringLiteralInitialization(Sema &S,
2515 const InitializedEntity &Entity,
2516 const InitializationKind &Kind,
2517 Expr *Initializer,
2518 InitializationSequence &Sequence) {
2519 // FIXME: Implement!
2520}
2521
Douglas Gregor20093b42009-12-09 23:02:17 +00002522/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2523/// enumerates the constructors of the initialized entity and performs overload
2524/// resolution to select the best.
2525static void TryConstructorInitialization(Sema &S,
2526 const InitializedEntity &Entity,
2527 const InitializationKind &Kind,
2528 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002529 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002530 InitializationSequence &Sequence) {
Douglas Gregora6ca6502009-12-14 20:57:13 +00002531 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002532
2533 // Build the candidate set directly in the initialization sequence
2534 // structure, so that it will persist if we fail.
2535 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2536 CandidateSet.clear();
2537
2538 // Determine whether we are allowed to call explicit constructors or
2539 // explicit conversion operators.
2540 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2541 Kind.getKind() == InitializationKind::IK_Value ||
2542 Kind.getKind() == InitializationKind::IK_Default);
2543
2544 // The type we're converting to is a class type. Enumerate its constructors
2545 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002546 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2547 assert(DestRecordType && "Constructor initialization requires record type");
2548 CXXRecordDecl *DestRecordDecl
2549 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2550
2551 DeclarationName ConstructorName
2552 = S.Context.DeclarationNames.getCXXConstructorName(
2553 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2554 DeclContext::lookup_iterator Con, ConEnd;
2555 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2556 Con != ConEnd; ++Con) {
2557 // Find the constructor (which may be a template).
2558 CXXConstructorDecl *Constructor = 0;
2559 FunctionTemplateDecl *ConstructorTmpl
2560 = dyn_cast<FunctionTemplateDecl>(*Con);
2561 if (ConstructorTmpl)
2562 Constructor = cast<CXXConstructorDecl>(
2563 ConstructorTmpl->getTemplatedDecl());
2564 else
2565 Constructor = cast<CXXConstructorDecl>(*Con);
2566
2567 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002568 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002569 if (ConstructorTmpl)
2570 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2571 Args, NumArgs, CandidateSet);
2572 else
2573 S.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2574 }
2575 }
2576
2577 SourceLocation DeclLoc = Kind.getLocation();
2578
2579 // Perform overload resolution. If it fails, return the failed result.
2580 OverloadCandidateSet::iterator Best;
2581 if (OverloadingResult Result
2582 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2583 Sequence.SetOverloadFailure(
2584 InitializationSequence::FK_ConstructorOverloadFailed,
2585 Result);
2586 return;
2587 }
2588
2589 // Add the constructor initialization step. Any cv-qualification conversion is
2590 // subsumed by the initialization.
2591 Sequence.AddConstructorInitializationStep(
2592 cast<CXXConstructorDecl>(Best->Function),
2593 DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002594}
2595
Douglas Gregor71d17402009-12-15 00:01:57 +00002596/// \brief Attempt value initialization (C++ [dcl.init]p7).
2597static void TryValueInitialization(Sema &S,
2598 const InitializedEntity &Entity,
2599 const InitializationKind &Kind,
2600 InitializationSequence &Sequence) {
2601 // C++ [dcl.init]p5:
2602 //
2603 // To value-initialize an object of type T means:
2604 QualType T = Entity.getType().getType();
2605
2606 // -- if T is an array type, then each element is value-initialized;
2607 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2608 T = AT->getElementType();
2609
2610 if (const RecordType *RT = T->getAs<RecordType>()) {
2611 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2612 // -- if T is a class type (clause 9) with a user-declared
2613 // constructor (12.1), then the default constructor for T is
2614 // called (and the initialization is ill-formed if T has no
2615 // accessible default constructor);
2616 //
2617 // FIXME: we really want to refer to a single subobject of the array,
2618 // but Entity doesn't have a way to capture that (yet).
2619 if (ClassDecl->hasUserDeclaredConstructor())
2620 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2621
2622 // FIXME: non-union class type w/ non-trivial default constructor gets
2623 // zero-initialized, then constructor gets called.
2624 }
2625 }
2626
2627 Sequence.AddZeroInitializationStep(Entity.getType().getType());
2628 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2629}
2630
Douglas Gregor99a2e602009-12-16 01:38:02 +00002631/// \brief Attempt default initialization (C++ [dcl.init]p6).
2632static void TryDefaultInitialization(Sema &S,
2633 const InitializedEntity &Entity,
2634 const InitializationKind &Kind,
2635 InitializationSequence &Sequence) {
2636 assert(Kind.getKind() == InitializationKind::IK_Default);
2637
2638 // C++ [dcl.init]p6:
2639 // To default-initialize an object of type T means:
2640 // - if T is an array type, each element is default-initialized;
2641 QualType DestType = Entity.getType().getType();
2642 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2643 DestType = Array->getElementType();
2644
2645 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2646 // constructor for T is called (and the initialization is ill-formed if
2647 // T has no accessible default constructor);
2648 if (DestType->isRecordType()) {
2649 // FIXME: If a program calls for the default initialization of an object of
2650 // a const-qualified type T, T shall be a class type with a user-provided
2651 // default constructor.
2652 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2653 Sequence);
2654 }
2655
2656 // - otherwise, no initialization is performed.
2657 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2658
2659 // If a program calls for the default initialization of an object of
2660 // a const-qualified type T, T shall be a class type with a user-provided
2661 // default constructor.
2662 if (DestType.isConstQualified())
2663 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2664}
2665
Douglas Gregor20093b42009-12-09 23:02:17 +00002666/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2667/// which enumerates all conversion functions and performs overload resolution
2668/// to select the best.
2669static void TryUserDefinedConversion(Sema &S,
2670 const InitializedEntity &Entity,
2671 const InitializationKind &Kind,
2672 Expr *Initializer,
2673 InitializationSequence &Sequence) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002674 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2675
2676 QualType DestType = Entity.getType().getType();
2677 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2678 QualType SourceType = Initializer->getType();
2679 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2680 "Must have a class type to perform a user-defined conversion");
2681
2682 // Build the candidate set directly in the initialization sequence
2683 // structure, so that it will persist if we fail.
2684 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2685 CandidateSet.clear();
2686
2687 // Determine whether we are allowed to call explicit constructors or
2688 // explicit conversion operators.
2689 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2690
2691 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2692 // The type we're converting to is a class type. Enumerate its constructors
2693 // to see if there is a suitable conversion.
2694 CXXRecordDecl *DestRecordDecl
2695 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2696
2697 DeclarationName ConstructorName
2698 = S.Context.DeclarationNames.getCXXConstructorName(
2699 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2700 DeclContext::lookup_iterator Con, ConEnd;
2701 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2702 Con != ConEnd; ++Con) {
2703 // Find the constructor (which may be a template).
2704 CXXConstructorDecl *Constructor = 0;
2705 FunctionTemplateDecl *ConstructorTmpl
2706 = dyn_cast<FunctionTemplateDecl>(*Con);
2707 if (ConstructorTmpl)
2708 Constructor = cast<CXXConstructorDecl>(
2709 ConstructorTmpl->getTemplatedDecl());
2710 else
2711 Constructor = cast<CXXConstructorDecl>(*Con);
2712
2713 if (!Constructor->isInvalidDecl() &&
2714 Constructor->isConvertingConstructor(AllowExplicit)) {
2715 if (ConstructorTmpl)
2716 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2717 &Initializer, 1, CandidateSet);
2718 else
2719 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2720 }
2721 }
2722 }
2723
2724 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2725 // The type we're converting from is a class type, enumerate its conversion
2726 // functions.
2727 CXXRecordDecl *SourceRecordDecl
2728 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
2729
2730 const UnresolvedSet *Conversions
2731 = SourceRecordDecl->getVisibleConversionFunctions();
2732 for (UnresolvedSet::iterator I = Conversions->begin(),
2733 E = Conversions->end();
2734 I != E; ++I) {
2735 NamedDecl *D = *I;
2736 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2737 if (isa<UsingShadowDecl>(D))
2738 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2739
2740 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2741 CXXConversionDecl *Conv;
2742 if (ConvTemplate)
2743 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2744 else
2745 Conv = cast<CXXConversionDecl>(*I);
2746
2747 if (AllowExplicit || !Conv->isExplicit()) {
2748 if (ConvTemplate)
2749 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2750 DestType, CandidateSet);
2751 else
2752 S.AddConversionCandidate(Conv, ActingDC, Initializer, DestType,
2753 CandidateSet);
2754 }
2755 }
2756 }
2757
2758 SourceLocation DeclLoc = Initializer->getLocStart();
2759
2760 // Perform overload resolution. If it fails, return the failed result.
2761 OverloadCandidateSet::iterator Best;
2762 if (OverloadingResult Result
2763 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2764 Sequence.SetOverloadFailure(
2765 InitializationSequence::FK_UserConversionOverloadFailed,
2766 Result);
2767 return;
2768 }
2769
2770 FunctionDecl *Function = Best->Function;
2771
2772 if (isa<CXXConstructorDecl>(Function)) {
2773 // Add the user-defined conversion step. Any cv-qualification conversion is
2774 // subsumed by the initialization.
2775 Sequence.AddUserConversionStep(Function, DestType);
2776 return;
2777 }
2778
2779 // Add the user-defined conversion step that calls the conversion function.
2780 QualType ConvType = Function->getResultType().getNonReferenceType();
2781 Sequence.AddUserConversionStep(Function, ConvType);
2782
2783 // If the conversion following the call to the conversion function is
2784 // interesting, add it as a separate step.
2785 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2786 Best->FinalConversion.Third) {
2787 ImplicitConversionSequence ICS;
2788 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2789 ICS.Standard = Best->FinalConversion;
2790 Sequence.AddConversionSequenceStep(ICS, DestType);
2791 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002792}
2793
2794/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2795/// non-class type to another.
2796static void TryImplicitConversion(Sema &S,
2797 const InitializedEntity &Entity,
2798 const InitializationKind &Kind,
2799 Expr *Initializer,
2800 InitializationSequence &Sequence) {
2801 ImplicitConversionSequence ICS
2802 = S.TryImplicitConversion(Initializer, Entity.getType().getType(),
2803 /*SuppressUserConversions=*/true,
2804 /*AllowExplicit=*/false,
2805 /*ForceRValue=*/false,
2806 /*FIXME:InOverloadResolution=*/false,
2807 /*UserCast=*/Kind.isExplicitCast());
2808
2809 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
2810 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2811 return;
2812 }
2813
2814 Sequence.AddConversionSequenceStep(ICS, Entity.getType().getType());
2815}
2816
2817InitializationSequence::InitializationSequence(Sema &S,
2818 const InitializedEntity &Entity,
2819 const InitializationKind &Kind,
2820 Expr **Args,
2821 unsigned NumArgs) {
2822 ASTContext &Context = S.Context;
2823
2824 // C++0x [dcl.init]p16:
2825 // The semantics of initializers are as follows. The destination type is
2826 // the type of the object or reference being initialized and the source
2827 // type is the type of the initializer expression. The source type is not
2828 // defined when the initializer is a braced-init-list or when it is a
2829 // parenthesized list of expressions.
2830 QualType DestType = Entity.getType().getType();
2831
2832 if (DestType->isDependentType() ||
2833 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2834 SequenceKind = DependentSequence;
2835 return;
2836 }
2837
2838 QualType SourceType;
2839 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00002840 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002841 Initializer = Args[0];
2842 if (!isa<InitListExpr>(Initializer))
2843 SourceType = Initializer->getType();
2844 }
2845
2846 // - If the initializer is a braced-init-list, the object is
2847 // list-initialized (8.5.4).
2848 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2849 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00002850 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00002851 }
2852
2853 // - If the destination type is a reference type, see 8.5.3.
2854 if (DestType->isReferenceType()) {
2855 // C++0x [dcl.init.ref]p1:
2856 // A variable declared to be a T& or T&&, that is, "reference to type T"
2857 // (8.3.2), shall be initialized by an object, or function, of type T or
2858 // by an object that can be converted into a T.
2859 // (Therefore, multiple arguments are not permitted.)
2860 if (NumArgs != 1)
2861 SetFailed(FK_TooManyInitsForReference);
2862 else
2863 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2864 return;
2865 }
2866
2867 // - If the destination type is an array of characters, an array of
2868 // char16_t, an array of char32_t, or an array of wchar_t, and the
2869 // initializer is a string literal, see 8.5.2.
2870 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2871 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2872 return;
2873 }
2874
2875 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002876 if (Kind.getKind() == InitializationKind::IK_Value ||
2877 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002878 TryValueInitialization(S, Entity, Kind, *this);
2879 return;
2880 }
2881
Douglas Gregor99a2e602009-12-16 01:38:02 +00002882 // Handle default initialization.
2883 if (Kind.getKind() == InitializationKind::IK_Default){
2884 TryDefaultInitialization(S, Entity, Kind, *this);
2885 return;
2886 }
2887
Douglas Gregor20093b42009-12-09 23:02:17 +00002888 // - Otherwise, if the destination type is an array, the program is
2889 // ill-formed.
2890 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2891 if (AT->getElementType()->isAnyCharacterType())
2892 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2893 else
2894 SetFailed(FK_ArrayNeedsInitList);
2895
2896 return;
2897 }
2898
2899 // - If the destination type is a (possibly cv-qualified) class type:
2900 if (DestType->isRecordType()) {
2901 // - If the initialization is direct-initialization, or if it is
2902 // copy-initialization where the cv-unqualified version of the
2903 // source type is the same class as, or a derived class of, the
2904 // class of the destination, constructors are considered. [...]
2905 if (Kind.getKind() == InitializationKind::IK_Direct ||
2906 (Kind.getKind() == InitializationKind::IK_Copy &&
2907 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2908 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor71d17402009-12-15 00:01:57 +00002909 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
2910 Entity.getType().getType(), *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00002911 // - Otherwise (i.e., for the remaining copy-initialization cases),
2912 // user-defined conversion sequences that can convert from the source
2913 // type to the destination type or (when a conversion function is
2914 // used) to a derived class thereof are enumerated as described in
2915 // 13.3.1.4, and the best one is chosen through overload resolution
2916 // (13.3).
2917 else
2918 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2919 return;
2920 }
2921
Douglas Gregor99a2e602009-12-16 01:38:02 +00002922 if (NumArgs > 1) {
2923 SetFailed(FK_TooManyInitsForScalar);
2924 return;
2925 }
2926 assert(NumArgs == 1 && "Zero-argument case handled above");
2927
Douglas Gregor20093b42009-12-09 23:02:17 +00002928 // - Otherwise, if the source type is a (possibly cv-qualified) class
2929 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002930 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002931 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2932 return;
2933 }
2934
2935 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00002936 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00002937 // conversions (Clause 4) will be used, if necessary, to convert the
2938 // initializer expression to the cv-unqualified version of the
2939 // destination type; no user-defined conversions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002940 setSequenceKind(StandardConversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00002941 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
2942}
2943
2944InitializationSequence::~InitializationSequence() {
2945 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
2946 StepEnd = Steps.end();
2947 Step != StepEnd; ++Step)
2948 Step->Destroy();
2949}
2950
2951//===----------------------------------------------------------------------===//
2952// Perform initialization
2953//===----------------------------------------------------------------------===//
2954
2955Action::OwningExprResult
2956InitializationSequence::Perform(Sema &S,
2957 const InitializedEntity &Entity,
2958 const InitializationKind &Kind,
Douglas Gregord87b61f2009-12-10 17:56:55 +00002959 Action::MultiExprArg Args,
2960 QualType *ResultType) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002961 if (SequenceKind == FailedSequence) {
2962 unsigned NumArgs = Args.size();
2963 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
2964 return S.ExprError();
2965 }
2966
2967 if (SequenceKind == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002968 // If the declaration is a non-dependent, incomplete array type
2969 // that has an initializer, then its type will be completed once
2970 // the initializer is instantiated.
2971 if (ResultType && !Entity.getType().getType()->isDependentType() &&
2972 Args.size() == 1) {
2973 QualType DeclType = Entity.getType().getType();
2974 if (const IncompleteArrayType *ArrayT
2975 = S.Context.getAsIncompleteArrayType(DeclType)) {
2976 // FIXME: We don't currently have the ability to accurately
2977 // compute the length of an initializer list without
2978 // performing full type-checking of the initializer list
2979 // (since we have to determine where braces are implicitly
2980 // introduced and such). So, we fall back to making the array
2981 // type a dependently-sized array type with no specified
2982 // bound.
2983 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
2984 SourceRange Brackets;
2985 // Scavange the location of the brackets from the entity, if we can.
2986 if (isa<IncompleteArrayTypeLoc>(Entity.getType())) {
2987 IncompleteArrayTypeLoc ArrayLoc
2988 = cast<IncompleteArrayTypeLoc>(Entity.getType());
2989 Brackets = ArrayLoc.getBracketsRange();
2990 }
2991
2992 *ResultType
2993 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
2994 /*NumElts=*/0,
2995 ArrayT->getSizeModifier(),
2996 ArrayT->getIndexTypeCVRQualifiers(),
2997 Brackets);
2998 }
2999
3000 }
3001 }
3002
Douglas Gregor20093b42009-12-09 23:02:17 +00003003 if (Kind.getKind() == InitializationKind::IK_Copy)
3004 return Sema::OwningExprResult(S, Args.release()[0]);
3005
3006 unsigned NumArgs = Args.size();
3007 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3008 SourceLocation(),
3009 (Expr **)Args.release(),
3010 NumArgs,
3011 SourceLocation()));
3012 }
3013
Douglas Gregor99a2e602009-12-16 01:38:02 +00003014 if (SequenceKind == NoInitialization)
3015 return S.Owned((Expr *)0);
3016
Douglas Gregor20093b42009-12-09 23:02:17 +00003017 QualType DestType = Entity.getType().getType().getNonReferenceType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003018 if (ResultType)
3019 *ResultType = Entity.getType().getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003020
Douglas Gregor99a2e602009-12-16 01:38:02 +00003021 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3022
3023 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3024
3025 // For initialization steps that start with a single initializer,
3026 // grab the only argument out the Args and place it into the "current"
3027 // initializer.
3028 switch (Steps.front().Kind) {
3029 case SK_ResolveAddressOfOverloadedFunction:
3030 case SK_CastDerivedToBaseRValue:
3031 case SK_CastDerivedToBaseLValue:
3032 case SK_BindReference:
3033 case SK_BindReferenceToTemporary:
3034 case SK_UserConversion:
3035 case SK_QualificationConversionLValue:
3036 case SK_QualificationConversionRValue:
3037 case SK_ConversionSequence:
3038 case SK_ListInitialization:
3039 assert(Args.size() == 1);
3040 CurInit = Sema::OwningExprResult(S,
3041 ((Expr **)(Args.get()))[0]->Retain());
3042 if (CurInit.isInvalid())
3043 return S.ExprError();
3044 break;
3045
3046 case SK_ConstructorInitialization:
3047 case SK_ZeroInitialization:
3048 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003049 }
3050
3051 // Walk through the computed steps for the initialization sequence,
3052 // performing the specified conversions along the way.
3053 for (step_iterator Step = step_begin(), StepEnd = step_end();
3054 Step != StepEnd; ++Step) {
3055 if (CurInit.isInvalid())
3056 return S.ExprError();
3057
3058 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003059 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003060
3061 switch (Step->Kind) {
3062 case SK_ResolveAddressOfOverloadedFunction:
3063 // Overload resolution determined which function invoke; update the
3064 // initializer to reflect that choice.
3065 CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function);
3066 break;
3067
3068 case SK_CastDerivedToBaseRValue:
3069 case SK_CastDerivedToBaseLValue: {
3070 // We have a derived-to-base cast that produces either an rvalue or an
3071 // lvalue. Perform that cast.
3072
3073 // Casts to inaccessible base classes are allowed with C-style casts.
3074 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3075 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3076 CurInitExpr->getLocStart(),
3077 CurInitExpr->getSourceRange(),
3078 IgnoreBaseAccess))
3079 return S.ExprError();
3080
3081 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3082 CastExpr::CK_DerivedToBase,
3083 (Expr*)CurInit.release(),
3084 Step->Kind == SK_CastDerivedToBaseLValue));
3085 break;
3086 }
3087
3088 case SK_BindReference:
3089 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3090 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3091 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
3092 << Entity.getType().getType().isVolatileQualified()
3093 << BitField->getDeclName()
3094 << CurInitExpr->getSourceRange();
3095 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3096 return S.ExprError();
3097 }
3098
3099 // Reference binding does not have any corresponding ASTs.
3100
3101 // Check exception specifications
3102 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3103 return S.ExprError();
3104 break;
3105
3106 case SK_BindReferenceToTemporary:
3107 // Check exception specifications
3108 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3109 return S.ExprError();
3110
3111 // FIXME: At present, we have no AST to describe when we need to make a
3112 // temporary to bind a reference to. We should.
3113 break;
3114
3115 case SK_UserConversion: {
3116 // We have a user-defined conversion that invokes either a constructor
3117 // or a conversion function.
3118 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
3119 if (CXXConstructorDecl *Constructor
3120 = dyn_cast<CXXConstructorDecl>(Step->Function)) {
3121 // Build a call to the selected constructor.
3122 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3123 SourceLocation Loc = CurInitExpr->getLocStart();
3124 CurInit.release(); // Ownership transferred into MultiExprArg, below.
3125
3126 // Determine the arguments required to actually perform the constructor
3127 // call.
3128 if (S.CompleteConstructorCall(Constructor,
3129 Sema::MultiExprArg(S,
3130 (void **)&CurInitExpr,
3131 1),
3132 Loc, ConstructorArgs))
3133 return S.ExprError();
3134
3135 // Build the an expression that constructs a temporary.
3136 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3137 move_arg(ConstructorArgs));
3138 if (CurInit.isInvalid())
3139 return S.ExprError();
3140
3141 CastKind = CastExpr::CK_ConstructorConversion;
3142 } else {
3143 // Build a call to the conversion function.
3144 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function);
3145
3146 // FIXME: Should we move this initialization into a separate
3147 // derived-to-base conversion? I believe the answer is "no", because
3148 // we don't want to turn off access control here for c-style casts.
3149 if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion))
3150 return S.ExprError();
3151
3152 // Do a little dance to make sure that CurInit has the proper
3153 // pointer.
3154 CurInit.release();
3155
3156 // Build the actual call to the conversion function.
3157 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3158 if (CurInit.isInvalid() || !CurInit.get())
3159 return S.ExprError();
3160
3161 CastKind = CastExpr::CK_UserDefinedConversion;
3162 }
3163
3164 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3165 CurInitExpr = CurInit.takeAs<Expr>();
3166 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3167 CastKind,
3168 CurInitExpr,
3169 false));
3170 break;
3171 }
3172
3173 case SK_QualificationConversionLValue:
3174 case SK_QualificationConversionRValue:
3175 // Perform a qualification conversion; these can never go wrong.
3176 S.ImpCastExprToType(CurInitExpr, Step->Type,
3177 CastExpr::CK_NoOp,
3178 Step->Kind == SK_QualificationConversionLValue);
3179 CurInit.release();
3180 CurInit = S.Owned(CurInitExpr);
3181 break;
3182
3183 case SK_ConversionSequence:
Douglas Gregor68647482009-12-16 03:45:30 +00003184 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor20093b42009-12-09 23:02:17 +00003185 false, false, *Step->ICS))
3186 return S.ExprError();
3187
3188 CurInit.release();
3189 CurInit = S.Owned(CurInitExpr);
3190 break;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003191
3192 case SK_ListInitialization: {
3193 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3194 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00003195 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregord87b61f2009-12-10 17:56:55 +00003196 return S.ExprError();
3197
3198 CurInit.release();
3199 CurInit = S.Owned(InitList);
3200 break;
3201 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003202
3203 case SK_ConstructorInitialization: {
3204 CXXConstructorDecl *Constructor
3205 = cast<CXXConstructorDecl>(Step->Function);
3206
3207 // Build a call to the selected constructor.
3208 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3209 SourceLocation Loc = Kind.getLocation();
3210
3211 // Determine the arguments required to actually perform the constructor
3212 // call.
3213 if (S.CompleteConstructorCall(Constructor, move(Args),
3214 Loc, ConstructorArgs))
3215 return S.ExprError();
3216
3217 // Build the an expression that constructs a temporary.
3218 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3219 move_arg(ConstructorArgs));
3220 if (CurInit.isInvalid())
3221 return S.ExprError();
3222
Douglas Gregor51c56d62009-12-14 20:49:26 +00003223 break;
3224 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003225
3226 case SK_ZeroInitialization: {
Douglas Gregorcb57fb92009-12-16 06:35:08 +00003227 if (Kind.getKind() == InitializationKind::IK_Value &&
3228 S.getLangOptions().CPlusPlus &&
3229 !Kind.isImplicitValueInit())
Douglas Gregor71d17402009-12-15 00:01:57 +00003230 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3231 Kind.getRange().getBegin(),
3232 Kind.getRange().getEnd()));
3233 else
3234 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
3235 break;
3236 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003237 }
3238 }
3239
3240 return move(CurInit);
3241}
3242
3243//===----------------------------------------------------------------------===//
3244// Diagnose initialization failures
3245//===----------------------------------------------------------------------===//
3246bool InitializationSequence::Diagnose(Sema &S,
3247 const InitializedEntity &Entity,
3248 const InitializationKind &Kind,
3249 Expr **Args, unsigned NumArgs) {
3250 if (SequenceKind != FailedSequence)
3251 return false;
3252
3253 QualType DestType = Entity.getType().getType();
3254 switch (Failure) {
3255 case FK_TooManyInitsForReference:
3256 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3257 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
3258 break;
3259
3260 case FK_ArrayNeedsInitList:
3261 case FK_ArrayNeedsInitListOrStringLiteral:
3262 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3263 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3264 break;
3265
3266 case FK_AddressOfOverloadFailed:
3267 S.ResolveAddressOfOverloadedFunction(Args[0],
3268 DestType.getNonReferenceType(),
3269 true);
3270 break;
3271
3272 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00003273 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00003274 switch (FailedOverloadResult) {
3275 case OR_Ambiguous:
3276 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3277 << Args[0]->getType() << DestType.getNonReferenceType()
3278 << Args[0]->getSourceRange();
3279 S.PrintOverloadCandidates(FailedCandidateSet, true);
3280 break;
3281
3282 case OR_No_Viable_Function:
3283 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3284 << Args[0]->getType() << DestType.getNonReferenceType()
3285 << Args[0]->getSourceRange();
3286 S.PrintOverloadCandidates(FailedCandidateSet, false);
3287 break;
3288
3289 case OR_Deleted: {
3290 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3291 << Args[0]->getType() << DestType.getNonReferenceType()
3292 << Args[0]->getSourceRange();
3293 OverloadCandidateSet::iterator Best;
3294 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3295 Kind.getLocation(),
3296 Best);
3297 if (Ovl == OR_Deleted) {
3298 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3299 << Best->Function->isDeleted();
3300 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003301 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00003302 }
3303 break;
3304 }
3305
3306 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003307 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00003308 break;
3309 }
3310 break;
3311
3312 case FK_NonConstLValueReferenceBindingToTemporary:
3313 case FK_NonConstLValueReferenceBindingToUnrelated:
3314 S.Diag(Kind.getLocation(),
3315 Failure == FK_NonConstLValueReferenceBindingToTemporary
3316 ? diag::err_lvalue_reference_bind_to_temporary
3317 : diag::err_lvalue_reference_bind_to_unrelated)
3318 << DestType.getNonReferenceType()
3319 << Args[0]->getType()
3320 << Args[0]->getSourceRange();
3321 break;
3322
3323 case FK_RValueReferenceBindingToLValue:
3324 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3325 << Args[0]->getSourceRange();
3326 break;
3327
3328 case FK_ReferenceInitDropsQualifiers:
3329 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3330 << DestType.getNonReferenceType()
3331 << Args[0]->getType()
3332 << Args[0]->getSourceRange();
3333 break;
3334
3335 case FK_ReferenceInitFailed:
3336 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3337 << DestType.getNonReferenceType()
3338 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3339 << Args[0]->getType()
3340 << Args[0]->getSourceRange();
3341 break;
3342
3343 case FK_ConversionFailed:
3344 S.Diag(Kind.getLocation(), diag::err_cannot_initialize_decl_noname)
3345 << DestType
3346 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3347 << Args[0]->getType()
3348 << Args[0]->getSourceRange();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003349 break;
3350
3351 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003352 SourceRange R;
3353
3354 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3355 R = SourceRange(InitList->getInit(1)->getLocStart(),
3356 InitList->getLocEnd());
3357 else
3358 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00003359
3360 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor99a2e602009-12-16 01:38:02 +00003361 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003362 break;
3363 }
3364
3365 case FK_ReferenceBindingToInitList:
3366 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3367 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3368 break;
3369
3370 case FK_InitListBadDestinationType:
3371 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3372 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3373 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00003374
3375 case FK_ConstructorOverloadFailed: {
3376 SourceRange ArgsRange;
3377 if (NumArgs)
3378 ArgsRange = SourceRange(Args[0]->getLocStart(),
3379 Args[NumArgs - 1]->getLocEnd());
3380
3381 // FIXME: Using "DestType" for the entity we're printing is probably
3382 // bad.
3383 switch (FailedOverloadResult) {
3384 case OR_Ambiguous:
3385 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3386 << DestType << ArgsRange;
3387 S.PrintOverloadCandidates(FailedCandidateSet, true);
3388 break;
3389
3390 case OR_No_Viable_Function:
3391 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3392 << DestType << ArgsRange;
3393 S.PrintOverloadCandidates(FailedCandidateSet, false);
3394 break;
3395
3396 case OR_Deleted: {
3397 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3398 << true << DestType << ArgsRange;
3399 OverloadCandidateSet::iterator Best;
3400 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3401 Kind.getLocation(),
3402 Best);
3403 if (Ovl == OR_Deleted) {
3404 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3405 << Best->Function->isDeleted();
3406 } else {
3407 llvm_unreachable("Inconsistent overload resolution?");
3408 }
3409 break;
3410 }
3411
3412 case OR_Success:
3413 llvm_unreachable("Conversion did not fail!");
3414 break;
3415 }
3416 break;
3417 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003418
3419 case FK_DefaultInitOfConst:
3420 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3421 << DestType;
3422 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003423 }
3424
3425 return true;
3426}