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