blob: 8830b8ba60fa36f94a5f6fde87cf1f7e1ba7e6b3 [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"
Douglas Gregor4e0299b2010-01-01 00:03:05 +000019#include "Lookup.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000020#include "Sema.h"
Douglas Gregore4a0bb72009-01-22 00:58:24 +000021#include "clang/Parse/Designator.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000022#include "clang/AST/ASTContext.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000023#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000025#include "clang/AST/TypeLoc.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000027#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000028using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000029
Chris Lattner0cb78032009-02-24 22:27:37 +000030//===----------------------------------------------------------------------===//
31// Sema Initialization Checking
32//===----------------------------------------------------------------------===//
33
Chris Lattnerd8b741c82009-02-24 23:10:27 +000034static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattnera9196812009-02-26 23:26:43 +000035 const ArrayType *AT = Context.getAsArrayType(DeclType);
36 if (!AT) return 0;
37
Eli Friedman893abe42009-05-29 18:22:49 +000038 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
39 return 0;
40
Chris Lattnera9196812009-02-26 23:26:43 +000041 // See if this is a string literal or @encode.
42 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000043
Chris Lattnera9196812009-02-26 23:26:43 +000044 // Handle @encode, which is a narrow string.
45 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
46 return Init;
47
48 // Otherwise we can only handle string literals.
49 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000050 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000051
52 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattnera9196812009-02-26 23:26:43 +000053 // char array can be initialized with a narrow string.
54 // Only allow char x[] = "foo"; not char x[] = L"foo";
55 if (!SL->isWide())
Eli Friedman42a84652009-05-31 10:54:53 +000056 return ElemTy->isCharType() ? Init : 0;
Chris Lattnera9196812009-02-26 23:26:43 +000057
Eli Friedman42a84652009-05-31 10:54:53 +000058 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
59 // correction from DR343): "An array with element type compatible with a
60 // qualified or unqualified version of wchar_t may be initialized by a wide
61 // string literal, optionally enclosed in braces."
62 if (Context.typesAreCompatible(Context.getWCharType(),
63 ElemTy.getUnqualifiedType()))
Chris Lattnera9196812009-02-26 23:26:43 +000064 return Init;
Mike Stump11289f42009-09-09 15:08:12 +000065
Chris Lattner0cb78032009-02-24 22:27:37 +000066 return 0;
67}
68
Anders Carlsson26d05642010-01-23 18:35:41 +000069static Sema::OwningExprResult
Anders Carlsson6cabf312010-01-23 23:23:01 +000070CheckSingleInitializer(const InitializedEntity &Entity,
Anders Carlsson26d05642010-01-23 18:35:41 +000071 Sema::OwningExprResult Init, QualType DeclType, Sema &S){
Anders Carlsson6cabf312010-01-23 23:23:01 +000072 assert(Entity.getType() == DeclType);
Anders Carlsson26d05642010-01-23 18:35:41 +000073 Expr *InitExpr = Init.takeAs<Expr>();
74
Chris Lattner0cb78032009-02-24 22:27:37 +000075 // Get the type before calling CheckSingleAssignmentConstraints(), since
76 // it can promote the expression.
Anders Carlsson26d05642010-01-23 18:35:41 +000077 QualType InitType = InitExpr->getType();
Mike Stump11289f42009-09-09 15:08:12 +000078
Chris Lattner94d2f682009-02-24 22:46:58 +000079 if (S.getLangOptions().CPlusPlus) {
Anders Carlsson6cabf312010-01-23 23:23:01 +000080 // C++ [dcl.init.aggr]p2:
81 // Each member is copy-initialized from the corresponding
82 // initializer-clause
83 Sema::OwningExprResult Result =
84 S.PerformCopyInitialization(Entity, InitExpr->getLocStart(),
85 S.Owned(InitExpr));
Anders Carlsson3cc795a2010-01-23 19:22:30 +000086
87 return move(Result);
Chris Lattner0cb78032009-02-24 22:27:37 +000088 }
Mike Stump11289f42009-09-09 15:08:12 +000089
Chris Lattner94d2f682009-02-24 22:46:58 +000090 Sema::AssignConvertType ConvTy =
Anders Carlsson26d05642010-01-23 18:35:41 +000091 S.CheckSingleAssignmentConstraints(DeclType, InitExpr);
92 if (S.DiagnoseAssignmentResult(ConvTy, InitExpr->getLocStart(), DeclType,
93 InitType, InitExpr, Sema::AA_Initializing))
94 return S.ExprError();
95
96 Init.release();
97 return S.Owned(InitExpr);
Chris Lattner0cb78032009-02-24 22:27:37 +000098}
99
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000100static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
101 // Get the length of the string as parsed.
102 uint64_t StrLength =
103 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
104
Mike Stump11289f42009-09-09 15:08:12 +0000105
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000106 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000107 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +0000108 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +0000109 // being initialized to a string literal.
110 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000111 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +0000112 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +0000113 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
114 ConstVal,
115 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000116 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000117 }
Mike Stump11289f42009-09-09 15:08:12 +0000118
Eli Friedman893abe42009-05-29 18:22:49 +0000119 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000120
Eli Friedman893abe42009-05-29 18:22:49 +0000121 // C99 6.7.8p14. We have an array of character type with known size. However,
122 // the size may be smaller or larger than the string we are initializing.
123 // FIXME: Avoid truncation for 64-bit length strings.
124 if (StrLength-1 > CAT->getSize().getZExtValue())
125 S.Diag(Str->getSourceRange().getBegin(),
126 diag::warn_initializer_string_for_char_array_too_long)
127 << Str->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +0000128
Eli Friedman893abe42009-05-29 18:22:49 +0000129 // Set the type to the actual size that we are initializing. If we have
130 // something like:
131 // char x[1] = "foo";
132 // then this will set the string literal's type to char[1].
133 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000134}
135
Chris Lattner0cb78032009-02-24 22:27:37 +0000136//===----------------------------------------------------------------------===//
137// Semantic checking for initializer lists.
138//===----------------------------------------------------------------------===//
139
Douglas Gregorcde232f2009-01-29 01:05:33 +0000140/// @brief Semantic checking for initializer lists.
141///
142/// The InitListChecker class contains a set of routines that each
143/// handle the initialization of a certain kind of entity, e.g.,
144/// arrays, vectors, struct/union types, scalars, etc. The
145/// InitListChecker itself performs a recursive walk of the subobject
146/// structure of the type to be initialized, while stepping through
147/// the initializer list one element at a time. The IList and Index
148/// parameters to each of the Check* routines contain the active
149/// (syntactic) initializer list and the index into that initializer
150/// list that represents the current initializer. Each routine is
151/// responsible for moving that Index forward as it consumes elements.
152///
153/// Each Check* routine also has a StructuredList/StructuredIndex
154/// arguments, which contains the current the "structured" (semantic)
155/// initializer list and the index into that initializer list where we
156/// are copying initializers as we map them over to the semantic
157/// list. Once we have completed our recursive walk of the subobject
158/// structure, we will have constructed a full semantic initializer
159/// list.
160///
161/// C99 designators cause changes in the initializer list traversal,
162/// because they make the initialization "jump" into a specific
163/// subobject and then continue the initialization from that
164/// point. CheckDesignatedInitializer() recursively steps into the
165/// designated subobject and manages backing out the recursion to
166/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000167namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000168class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000169 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000170 bool hadError;
171 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
172 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000173
Anders Carlsson6cabf312010-01-23 23:23:01 +0000174 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000175 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000176 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000177 unsigned &StructuredIndex,
178 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000179 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000180 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000181 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000182 unsigned &StructuredIndex,
183 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000184 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000185 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000186 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000187 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000188 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000189 unsigned &StructuredIndex,
190 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000191 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000192 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000193 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000194 InitListExpr *StructuredList,
195 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000196 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000197 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000198 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000199 InitListExpr *StructuredList,
200 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000201 void CheckReferenceType(const InitializedEntity &Entity,
202 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000203 unsigned &Index,
204 InitListExpr *StructuredList,
205 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000206 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000207 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000208 InitListExpr *StructuredList,
209 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000210 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000211 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000212 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000213 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000214 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000215 unsigned &StructuredIndex,
216 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000217 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000218 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000219 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000220 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000221 InitListExpr *StructuredList,
222 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000223 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000224 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000225 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000226 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000227 RecordDecl::field_iterator *NextField,
228 llvm::APSInt *NextElementIndex,
229 unsigned &Index,
230 InitListExpr *StructuredList,
231 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000232 bool FinishSubobjectInit,
233 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000234 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
235 QualType CurrentObjectType,
236 InitListExpr *StructuredList,
237 unsigned StructuredIndex,
238 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000239 void UpdateStructuredListElement(InitListExpr *StructuredList,
240 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000241 Expr *expr);
242 int numArrayElements(QualType DeclType);
243 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000244
Douglas Gregor2bb07652009-12-22 00:05:34 +0000245 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
246 const InitializedEntity &ParentEntity,
247 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000248 void FillInValueInitializations(const InitializedEntity &Entity,
249 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000250public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000251 InitListChecker(Sema &S, const InitializedEntity &Entity,
252 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000253 bool HadError() { return hadError; }
254
255 // @brief Retrieves the fully-structured initializer list used for
256 // semantic analysis and code generation.
257 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
258};
Chris Lattner9ececce2009-02-24 22:48:58 +0000259} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000260
Douglas Gregor2bb07652009-12-22 00:05:34 +0000261void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
262 const InitializedEntity &ParentEntity,
263 InitListExpr *ILE,
264 bool &RequiresSecondPass) {
265 SourceLocation Loc = ILE->getSourceRange().getBegin();
266 unsigned NumInits = ILE->getNumInits();
267 InitializedEntity MemberEntity
268 = InitializedEntity::InitializeMember(Field, &ParentEntity);
269 if (Init >= NumInits || !ILE->getInit(Init)) {
270 // FIXME: We probably don't need to handle references
271 // specially here, since value-initialization of references is
272 // handled in InitializationSequence.
273 if (Field->getType()->isReferenceType()) {
274 // C++ [dcl.init.aggr]p9:
275 // If an incomplete or empty initializer-list leaves a
276 // member of reference type uninitialized, the program is
277 // ill-formed.
278 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
279 << Field->getType()
280 << ILE->getSyntacticForm()->getSourceRange();
281 SemaRef.Diag(Field->getLocation(),
282 diag::note_uninit_reference_member);
283 hadError = true;
284 return;
285 }
286
287 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
288 true);
289 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
290 if (!InitSeq) {
291 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
292 hadError = true;
293 return;
294 }
295
296 Sema::OwningExprResult MemberInit
297 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
298 Sema::MultiExprArg(SemaRef, 0, 0));
299 if (MemberInit.isInvalid()) {
300 hadError = true;
301 return;
302 }
303
304 if (hadError) {
305 // Do nothing
306 } else if (Init < NumInits) {
307 ILE->setInit(Init, MemberInit.takeAs<Expr>());
308 } else if (InitSeq.getKind()
309 == InitializationSequence::ConstructorInitialization) {
310 // Value-initialization requires a constructor call, so
311 // extend the initializer list to include the constructor
312 // call and make a note that we'll need to take another pass
313 // through the initializer list.
314 ILE->updateInit(Init, MemberInit.takeAs<Expr>());
315 RequiresSecondPass = true;
316 }
317 } else if (InitListExpr *InnerILE
318 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
319 FillInValueInitializations(MemberEntity, InnerILE,
320 RequiresSecondPass);
321}
322
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000323/// Recursively replaces NULL values within the given initializer list
324/// with expressions that perform value-initialization of the
325/// appropriate type.
Douglas Gregor723796a2009-12-16 06:35:08 +0000326void
327InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
328 InitListExpr *ILE,
329 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000330 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000331 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000332 SourceLocation Loc = ILE->getSourceRange().getBegin();
333 if (ILE->getSyntacticForm())
334 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000335
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000336 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000337 if (RType->getDecl()->isUnion() &&
338 ILE->getInitializedFieldInUnion())
339 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
340 Entity, ILE, RequiresSecondPass);
341 else {
342 unsigned Init = 0;
343 for (RecordDecl::field_iterator
344 Field = RType->getDecl()->field_begin(),
345 FieldEnd = RType->getDecl()->field_end();
346 Field != FieldEnd; ++Field) {
347 if (Field->isUnnamedBitfield())
348 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000349
Douglas Gregor2bb07652009-12-22 00:05:34 +0000350 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000351 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000352
353 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
354 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000355 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000356
Douglas Gregor2bb07652009-12-22 00:05:34 +0000357 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000358
Douglas Gregor2bb07652009-12-22 00:05:34 +0000359 // Only look at the first initialization of a union.
360 if (RType->getDecl()->isUnion())
361 break;
362 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000363 }
364
365 return;
Mike Stump11289f42009-09-09 15:08:12 +0000366 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000367
368 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000369
Douglas Gregor723796a2009-12-16 06:35:08 +0000370 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000371 unsigned NumInits = ILE->getNumInits();
372 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000373 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000374 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000375 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
376 NumElements = CAType->getSize().getZExtValue();
Douglas Gregor723796a2009-12-16 06:35:08 +0000377 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
378 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000379 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000380 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000381 NumElements = VType->getNumElements();
Douglas Gregor723796a2009-12-16 06:35:08 +0000382 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
383 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000384 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000385 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000386
Douglas Gregor723796a2009-12-16 06:35:08 +0000387
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000388 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000389 if (hadError)
390 return;
391
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000392 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
393 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000394 ElementEntity.setElementIndex(Init);
395
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000396 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000397 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
398 true);
399 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
400 if (!InitSeq) {
401 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000402 hadError = true;
403 return;
404 }
405
Douglas Gregor723796a2009-12-16 06:35:08 +0000406 Sema::OwningExprResult ElementInit
407 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
408 Sema::MultiExprArg(SemaRef, 0, 0));
409 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000410 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000411 return;
412 }
413
414 if (hadError) {
415 // Do nothing
416 } else if (Init < NumInits) {
417 ILE->setInit(Init, ElementInit.takeAs<Expr>());
418 } else if (InitSeq.getKind()
419 == InitializationSequence::ConstructorInitialization) {
420 // Value-initialization requires a constructor call, so
421 // extend the initializer list to include the constructor
422 // call and make a note that we'll need to take another pass
423 // through the initializer list.
424 ILE->updateInit(Init, ElementInit.takeAs<Expr>());
425 RequiresSecondPass = true;
426 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000427 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000428 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
429 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000430 }
431}
432
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000433
Douglas Gregor723796a2009-12-16 06:35:08 +0000434InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
435 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000436 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000437 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000438
Eli Friedman23a9e312008-05-19 19:16:24 +0000439 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000440 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000441 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000442 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Anders Carlsson6cabf312010-01-23 23:23:01 +0000443 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000444 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000445 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000446
Douglas Gregor723796a2009-12-16 06:35:08 +0000447 if (!hadError) {
448 bool RequiresSecondPass = false;
449 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000450 if (RequiresSecondPass && !hadError)
Douglas Gregor723796a2009-12-16 06:35:08 +0000451 FillInValueInitializations(Entity, FullyStructuredList,
452 RequiresSecondPass);
453 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000454}
455
456int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000457 // FIXME: use a proper constant
458 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000459 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000460 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000461 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
462 }
463 return maxElements;
464}
465
466int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000467 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000468 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000469 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000470 Field = structDecl->field_begin(),
471 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000472 Field != FieldEnd; ++Field) {
473 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
474 ++InitializableMembers;
475 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000476 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000477 return std::min(InitializableMembers, 1);
478 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000479}
480
Anders Carlsson6cabf312010-01-23 23:23:01 +0000481void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000482 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000483 QualType T, unsigned &Index,
484 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000485 unsigned &StructuredIndex,
486 bool TopLevelObject) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000487 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000488
Steve Narofff8ecff22008-05-01 22:18:59 +0000489 if (T->isArrayType())
490 maxElements = numArrayElements(T);
491 else if (T->isStructureType() || T->isUnionType())
492 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000493 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000494 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000495 else
496 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000497
Eli Friedmane0f832b2008-05-25 13:49:22 +0000498 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000499 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000500 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000501 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000502 hadError = true;
503 return;
504 }
505
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000506 // Build a structured initializer list corresponding to this subobject.
507 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000508 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
509 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000510 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
511 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000512 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000513
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000514 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000515 unsigned StartIndex = Index;
Anders Carlssondbb25a32010-01-23 20:47:59 +0000516 CheckListElementTypes(Entity, ParentIList, T,
517 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000518 StructuredSubobjectInitList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000519 StructuredSubobjectInitIndex,
520 TopLevelObject);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000521 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000522 StructuredSubobjectInitList->setType(T);
523
Douglas Gregor5741efb2009-03-01 17:12:46 +0000524 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000525 // range corresponds with the end of the last initializer it used.
526 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000527 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000528 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
529 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
530 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000531}
532
Anders Carlsson6cabf312010-01-23 23:23:01 +0000533void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000534 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000535 unsigned &Index,
536 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000537 unsigned &StructuredIndex,
538 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000539 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000540 SyntacticToSemantic[IList] = StructuredList;
541 StructuredList->setSyntacticForm(IList);
Anders Carlssond0849252010-01-23 19:55:29 +0000542 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
543 Index, StructuredList, StructuredIndex, TopLevelObject);
Steve Naroff125d73d2008-05-06 00:23:44 +0000544 IList->setType(T);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000545 StructuredList->setType(T);
Eli Friedman85f54972008-05-25 13:22:35 +0000546 if (hadError)
547 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000548
Eli Friedman85f54972008-05-25 13:22:35 +0000549 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000550 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000551 if (StructuredIndex == 1 &&
552 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000553 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000554 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000555 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000556 hadError = true;
557 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000558 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000559 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000560 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000561 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000562 // Don't complain for incomplete types, since we'll get an error
563 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000564 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000565 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000566 CurrentObjectType->isArrayType()? 0 :
567 CurrentObjectType->isVectorType()? 1 :
568 CurrentObjectType->isScalarType()? 2 :
569 CurrentObjectType->isUnionType()? 3 :
570 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000571
572 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000573 if (SemaRef.getLangOptions().CPlusPlus) {
574 DK = diag::err_excess_initializers;
575 hadError = true;
576 }
Nate Begeman425038c2009-07-07 21:53:06 +0000577 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
578 DK = diag::err_excess_initializers;
579 hadError = true;
580 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000581
Chris Lattnerb0912a52009-02-24 22:50:46 +0000582 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000583 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000584 }
585 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000586
Eli Friedman0b4af8f2009-05-16 11:45:48 +0000587 if (T->isScalarType() && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000588 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000589 << IList->getSourceRange()
Chris Lattner3c7b86f2009-12-06 17:36:05 +0000590 << CodeModificationHint::CreateRemoval(IList->getLocStart())
591 << CodeModificationHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000592}
593
Anders Carlsson6cabf312010-01-23 23:23:01 +0000594void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000595 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000596 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000597 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000598 unsigned &Index,
599 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000600 unsigned &StructuredIndex,
601 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000602 if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000603 CheckScalarType(Entity, IList, DeclType, Index,
604 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000605 } else if (DeclType->isVectorType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000606 CheckVectorType(Entity, IList, DeclType, Index,
607 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000608 } else if (DeclType->isAggregateType()) {
609 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000610 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000611 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000612 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000613 StructuredList, StructuredIndex,
614 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000615 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000616 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000617 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000618 false);
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000619 CheckArrayType(Entity, IList, DeclType, Zero,
620 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000621 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000622 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000623 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000624 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
625 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000626 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000627 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000628 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000629 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000630 } else if (DeclType->isRecordType()) {
631 // C++ [dcl.init]p14:
632 // [...] If the class is an aggregate (8.5.1), and the initializer
633 // is a brace-enclosed list, see 8.5.1.
634 //
635 // Note: 8.5.1 is handled below; here, we diagnose the case where
636 // we have an initializer list and a destination type that is not
637 // an aggregate.
638 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000639 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000640 << DeclType << IList->getSourceRange();
641 hadError = true;
642 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000643 CheckReferenceType(Entity, IList, DeclType, Index,
644 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000645 } else {
646 // In C, all types are either scalars or aggregates, but
Mike Stump11289f42009-09-09 15:08:12 +0000647 // additional handling is needed here for C++ (and possibly others?).
Steve Narofff8ecff22008-05-01 22:18:59 +0000648 assert(0 && "Unsupported initializer type");
649 }
650}
651
Anders Carlsson6cabf312010-01-23 23:23:01 +0000652void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000653 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000654 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000655 unsigned &Index,
656 InitListExpr *StructuredList,
657 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000658 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000659 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
660 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000661 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000662 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000663 = getStructuredSubobjectInit(IList, Index, ElemType,
664 StructuredList, StructuredIndex,
665 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000666 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000667 newStructuredList, newStructuredIndex);
668 ++StructuredIndex;
669 ++Index;
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000670 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
671 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000672 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000673 ++Index;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000674 } else if (ElemType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000675 CheckScalarType(Entity, IList, ElemType, Index,
676 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000677 } else if (ElemType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000678 CheckReferenceType(Entity, IList, ElemType, Index,
679 StructuredList, StructuredIndex);
Eli Friedman23a9e312008-05-19 19:16:24 +0000680 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000681 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000682 // C++ [dcl.init.aggr]p12:
683 // All implicit type conversions (clause 4) are considered when
684 // initializing the aggregate member with an ini- tializer from
685 // an initializer-list. If the initializer can initialize a
686 // member, the member is initialized. [...]
Mike Stump11289f42009-09-09 15:08:12 +0000687 ImplicitConversionSequence ICS
Anders Carlsson03068aa2009-08-27 17:18:13 +0000688 = SemaRef.TryCopyInitialization(expr, ElemType,
689 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +0000690 /*ForceRValue=*/false,
691 /*InOverloadResolution=*/false);
Anders Carlsson03068aa2009-08-27 17:18:13 +0000692
John McCall0d1da222010-01-12 00:44:57 +0000693 if (!ICS.isBad()) {
Mike Stump11289f42009-09-09 15:08:12 +0000694 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000695 Sema::AA_Initializing))
Douglas Gregord14247a2009-01-30 22:09:00 +0000696 hadError = true;
697 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
698 ++Index;
699 return;
700 }
701
702 // Fall through for subaggregate initialization
703 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000704 // C99 6.7.8p13:
Douglas Gregord14247a2009-01-30 22:09:00 +0000705 //
706 // The initializer for a structure or union object that has
707 // automatic storage duration shall be either an initializer
708 // list as described below, or a single expression that has
709 // compatible structure or union type. In the latter case, the
710 // initial value of the object, including unnamed members, is
711 // that of the expression.
Eli Friedman9782caa2009-06-13 10:38:46 +0000712 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman893abe42009-05-29 18:22:49 +0000713 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000714 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
715 ++Index;
716 return;
717 }
718
719 // Fall through for subaggregate initialization
720 }
721
722 // C++ [dcl.init.aggr]p12:
Mike Stump11289f42009-09-09 15:08:12 +0000723 //
Douglas Gregord14247a2009-01-30 22:09:00 +0000724 // [...] Otherwise, if the member is itself a non-empty
725 // subaggregate, brace elision is assumed and the initializer is
726 // considered for the initialization of the first member of
727 // the subaggregate.
728 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Anders Carlssondbb25a32010-01-23 20:47:59 +0000729 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
Douglas Gregord14247a2009-01-30 22:09:00 +0000730 StructuredIndex);
731 ++StructuredIndex;
732 } else {
733 // We cannot initialize this element, so let
734 // PerformCopyInitialization produce the appropriate diagnostic.
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000735 SemaRef.PerformCopyInitialization(expr, ElemType, Sema::AA_Initializing);
Douglas Gregord14247a2009-01-30 22:09:00 +0000736 hadError = true;
737 ++Index;
738 ++StructuredIndex;
739 }
740 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000741}
742
Anders Carlsson6cabf312010-01-23 23:23:01 +0000743void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000744 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000745 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000746 InitListExpr *StructuredList,
747 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000748 if (Index < IList->getNumInits()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000749 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000750 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000751 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000752 diag::err_many_braces_around_scalar_init)
753 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000754 hadError = true;
755 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000756 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000757 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000758 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump11289f42009-09-09 15:08:12 +0000759 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000760 diag::err_designator_for_scalar_init)
761 << DeclType << expr->getSourceRange();
762 hadError = true;
763 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000764 ++StructuredIndex;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000765 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000766 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000767
Anders Carlsson26d05642010-01-23 18:35:41 +0000768 Sema::OwningExprResult Result =
Anders Carlssond0849252010-01-23 19:55:29 +0000769 CheckSingleInitializer(Entity, SemaRef.Owned(expr), DeclType, SemaRef);
Anders Carlsson26d05642010-01-23 18:35:41 +0000770
771 Expr *ResultExpr;
772
773 if (Result.isInvalid())
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000774 hadError = true; // types weren't compatible.
Anders Carlsson26d05642010-01-23 18:35:41 +0000775 else {
776 ResultExpr = Result.takeAs<Expr>();
777
778 if (ResultExpr != expr) {
779 // The type was promoted, update initializer list.
780 IList->setInit(Index, ResultExpr);
781 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000782 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000783 if (hadError)
784 ++StructuredIndex;
785 else
Anders Carlsson26d05642010-01-23 18:35:41 +0000786 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
Steve Narofff8ecff22008-05-01 22:18:59 +0000787 ++Index;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000788 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000789 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000790 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000791 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000792 ++Index;
793 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000794 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000795 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000796}
797
Anders Carlsson6cabf312010-01-23 23:23:01 +0000798void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
799 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000800 unsigned &Index,
801 InitListExpr *StructuredList,
802 unsigned &StructuredIndex) {
803 if (Index < IList->getNumInits()) {
804 Expr *expr = IList->getInit(Index);
805 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000806 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000807 << DeclType << IList->getSourceRange();
808 hadError = true;
809 ++Index;
810 ++StructuredIndex;
811 return;
Mike Stump11289f42009-09-09 15:08:12 +0000812 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000813
814 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Anders Carlsson271e3a42009-08-27 17:30:43 +0000815 if (SemaRef.CheckReferenceInit(expr, DeclType,
Douglas Gregorc809cc22009-09-23 23:04:10 +0000816 /*FIXME:*/expr->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +0000817 /*SuppressUserConversions=*/false,
818 /*AllowExplicit=*/false,
Mike Stump11289f42009-09-09 15:08:12 +0000819 /*ForceRValue=*/false))
Douglas Gregord14247a2009-01-30 22:09:00 +0000820 hadError = true;
821 else if (savExpr != expr) {
822 // The type was promoted, update initializer list.
823 IList->setInit(Index, expr);
824 }
825 if (hadError)
826 ++StructuredIndex;
827 else
828 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
829 ++Index;
830 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000831 // FIXME: It would be wonderful if we could point at the actual member. In
832 // general, it would be useful to pass location information down the stack,
833 // so that we know the location (or decl) of the "current object" being
834 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000835 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000836 diag::err_init_reference_member_uninitialized)
837 << DeclType
838 << IList->getSourceRange();
839 hadError = true;
840 ++Index;
841 ++StructuredIndex;
842 return;
843 }
844}
845
Anders Carlsson6cabf312010-01-23 23:23:01 +0000846void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000847 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000848 unsigned &Index,
849 InitListExpr *StructuredList,
850 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000851 if (Index < IList->getNumInits()) {
John McCall9dd450b2009-09-21 23:43:11 +0000852 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000853 unsigned maxElements = VT->getNumElements();
854 unsigned numEltsInit = 0;
Steve Narofff8ecff22008-05-01 22:18:59 +0000855 QualType elementType = VT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +0000856
Nate Begeman5ec4b312009-08-10 23:49:36 +0000857 if (!SemaRef.getLangOptions().OpenCL) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000858 InitializedEntity ElementEntity =
859 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlssond0849252010-01-23 19:55:29 +0000860
Anders Carlsson6cabf312010-01-23 23:23:01 +0000861 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
862 // Don't attempt to go past the end of the init list
863 if (Index >= IList->getNumInits())
864 break;
Anders Carlssond0849252010-01-23 19:55:29 +0000865
Anders Carlsson6cabf312010-01-23 23:23:01 +0000866 ElementEntity.setElementIndex(Index);
867 CheckSubElementType(ElementEntity, IList, elementType, Index,
868 StructuredList, StructuredIndex);
869 }
Nate Begeman5ec4b312009-08-10 23:49:36 +0000870 } else {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000871 InitializedEntity ElementEntity =
872 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
873
Nate Begeman5ec4b312009-08-10 23:49:36 +0000874 // OpenCL initializers allows vectors to be constructed from vectors.
875 for (unsigned i = 0; i < maxElements; ++i) {
876 // Don't attempt to go past the end of the init list
877 if (Index >= IList->getNumInits())
878 break;
Anders Carlsson6cabf312010-01-23 23:23:01 +0000879
880 ElementEntity.setElementIndex(Index);
881
Nate Begeman5ec4b312009-08-10 23:49:36 +0000882 QualType IType = IList->getInit(Index)->getType();
883 if (!IType->isVectorType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000884 CheckSubElementType(ElementEntity, IList, elementType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000885 StructuredList, StructuredIndex);
886 ++numEltsInit;
887 } else {
John McCall9dd450b2009-09-21 23:43:11 +0000888 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000889 unsigned numIElts = IVT->getNumElements();
890 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
891 numIElts);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000892 CheckSubElementType(ElementEntity, IList, VecType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000893 StructuredList, StructuredIndex);
894 numEltsInit += numIElts;
895 }
896 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000897 }
Mike Stump11289f42009-09-09 15:08:12 +0000898
Nate Begeman5ec4b312009-08-10 23:49:36 +0000899 // OpenCL & AltiVec require all elements to be initialized.
900 if (numEltsInit != maxElements)
901 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
902 SemaRef.Diag(IList->getSourceRange().getBegin(),
903 diag::err_vector_incorrect_num_initializers)
904 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000905 }
906}
907
Anders Carlsson6cabf312010-01-23 23:23:01 +0000908void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000909 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000910 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000911 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000912 unsigned &Index,
913 InitListExpr *StructuredList,
914 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000915 // Check for the special-case of initializing an array with a string.
916 if (Index < IList->getNumInits()) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000917 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
918 SemaRef.Context)) {
919 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000920 // We place the string literal directly into the resulting
921 // initializer list. This is the only place where the structure
922 // of the structured initializer list doesn't match exactly,
923 // because doing so would involve allocating one character
924 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000925 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +0000926 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000927 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000928 return;
929 }
930 }
Chris Lattner7adf0762008-08-04 07:31:14 +0000931 if (const VariableArrayType *VAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000932 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman85f54972008-05-25 13:22:35 +0000933 // Check for VLAs; in standard C it would be possible to check this
934 // earlier, but I don't know where clang accepts VLAs (gcc accepts
935 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +0000936 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000937 diag::err_variable_object_no_init)
938 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +0000939 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000940 ++Index;
941 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +0000942 return;
943 }
944
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000945 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000946 llvm::APSInt maxElements(elementIndex.getBitWidth(),
947 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000948 bool maxElementsKnown = false;
949 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000950 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000951 maxElements = CAT->getSize();
Douglas Gregor033d1252009-01-23 16:54:12 +0000952 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000953 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000954 maxElementsKnown = true;
955 }
956
Chris Lattnerb0912a52009-02-24 22:50:46 +0000957 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattner7adf0762008-08-04 07:31:14 +0000958 ->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000959 while (Index < IList->getNumInits()) {
960 Expr *Init = IList->getInit(Index);
961 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000962 // If we're not the subobject that matches up with the '{' for
963 // the designator, we shouldn't be handling the
964 // designator. Return immediately.
965 if (!SubobjectIsDesignatorContext)
966 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000967
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000968 // Handle this designated initializer. elementIndex will be
969 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000970 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000971 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000972 StructuredList, StructuredIndex, true,
973 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000974 hadError = true;
975 continue;
976 }
977
Douglas Gregor033d1252009-01-23 16:54:12 +0000978 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
979 maxElements.extend(elementIndex.getBitWidth());
980 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
981 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000982 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +0000983
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000984 // If the array is of incomplete type, keep track of the number of
985 // elements in the initializer.
986 if (!maxElementsKnown && elementIndex > maxElements)
987 maxElements = elementIndex;
988
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000989 continue;
990 }
991
992 // If we know the maximum number of elements, and we've already
993 // hit it, stop consuming elements in the initializer list.
994 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +0000995 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000996
Anders Carlsson6cabf312010-01-23 23:23:01 +0000997 InitializedEntity ElementEntity =
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000998 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +0000999 Entity);
1000 // Check this element.
1001 CheckSubElementType(ElementEntity, IList, elementType, Index,
1002 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001003 ++elementIndex;
1004
1005 // If the array is of incomplete type, keep track of the number of
1006 // elements in the initializer.
1007 if (!maxElementsKnown && elementIndex > maxElements)
1008 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001009 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001010 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001011 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001012 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001013 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001014 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001015 // Sizing an array implicitly to zero is not allowed by ISO C,
1016 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001017 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001018 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001019 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001020
Mike Stump11289f42009-09-09 15:08:12 +00001021 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001022 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001023 }
1024}
1025
Anders Carlsson6cabf312010-01-23 23:23:01 +00001026void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001027 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001028 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001029 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001030 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001031 unsigned &Index,
1032 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001033 unsigned &StructuredIndex,
1034 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001035 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001036
Eli Friedman23a9e312008-05-19 19:16:24 +00001037 // If the record is invalid, some of it's members are invalid. To avoid
1038 // confusion, we forgo checking the intializer for the entire record.
1039 if (structDecl->isInvalidDecl()) {
1040 hadError = true;
1041 return;
Mike Stump11289f42009-09-09 15:08:12 +00001042 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001043
1044 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1045 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001046 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001047 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001048 Field != FieldEnd; ++Field) {
1049 if (Field->getDeclName()) {
1050 StructuredList->setInitializedFieldInUnion(*Field);
1051 break;
1052 }
1053 }
1054 return;
1055 }
1056
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001057 // If structDecl is a forward declaration, this loop won't do
1058 // anything except look at designated initializers; That's okay,
1059 // because an error should get printed out elsewhere. It might be
1060 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001061 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001062 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001063 bool InitializedSomething = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001064 while (Index < IList->getNumInits()) {
1065 Expr *Init = IList->getInit(Index);
1066
1067 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001068 // If we're not the subobject that matches up with the '{' for
1069 // the designator, we shouldn't be handling the
1070 // designator. Return immediately.
1071 if (!SubobjectIsDesignatorContext)
1072 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001073
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001074 // Handle this designated initializer. Field will be updated to
1075 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001076 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001077 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001078 StructuredList, StructuredIndex,
1079 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001080 hadError = true;
1081
Douglas Gregora9add4e2009-02-12 19:00:39 +00001082 InitializedSomething = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001083 continue;
1084 }
1085
1086 if (Field == FieldEnd) {
1087 // We've run out of fields. We're done.
1088 break;
1089 }
1090
Douglas Gregora9add4e2009-02-12 19:00:39 +00001091 // We've already initialized a member of a union. We're done.
1092 if (InitializedSomething && DeclType->isUnionType())
1093 break;
1094
Douglas Gregor91f84212008-12-11 16:49:14 +00001095 // If we've hit the flexible array member at the end, we're done.
1096 if (Field->getType()->isIncompleteArrayType())
1097 break;
1098
Douglas Gregor51695702009-01-29 16:53:55 +00001099 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001100 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001101 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001102 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001103 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001104
Anders Carlsson6cabf312010-01-23 23:23:01 +00001105 InitializedEntity MemberEntity =
1106 InitializedEntity::InitializeMember(*Field, &Entity);
1107 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1108 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001109 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001110
1111 if (DeclType->isUnionType()) {
1112 // Initialize the first field within the union.
1113 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001114 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001115
1116 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001117 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001118
Mike Stump11289f42009-09-09 15:08:12 +00001119 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001120 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001121 return;
1122
1123 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001124 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001125 (!isa<InitListExpr>(IList->getInit(Index)) ||
1126 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001127 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001128 diag::err_flexible_array_init_nonempty)
1129 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001130 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001131 << *Field;
1132 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001133 ++Index;
1134 return;
1135 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001136 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001137 diag::ext_flexible_array_init)
1138 << IList->getInit(Index)->getSourceRange().getBegin();
1139 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1140 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001141 }
1142
Anders Carlsson6cabf312010-01-23 23:23:01 +00001143 InitializedEntity MemberEntity =
1144 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlssondbb25a32010-01-23 20:47:59 +00001145
Anders Carlsson6cabf312010-01-23 23:23:01 +00001146 if (isa<InitListExpr>(IList->getInit(Index)))
1147 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1148 StructuredList, StructuredIndex);
1149 else
1150 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001151 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001152}
Steve Narofff8ecff22008-05-01 22:18:59 +00001153
Douglas Gregord5846a12009-04-15 06:41:24 +00001154/// \brief Expand a field designator that refers to a member of an
1155/// anonymous struct or union into a series of field designators that
1156/// refers to the field within the appropriate subobject.
1157///
1158/// Field/FieldIndex will be updated to point to the (new)
1159/// currently-designated field.
1160static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001161 DesignatedInitExpr *DIE,
1162 unsigned DesigIdx,
Douglas Gregord5846a12009-04-15 06:41:24 +00001163 FieldDecl *Field,
1164 RecordDecl::field_iterator &FieldIter,
1165 unsigned &FieldIndex) {
1166 typedef DesignatedInitExpr::Designator Designator;
1167
1168 // Build the path from the current object to the member of the
1169 // anonymous struct/union (backwards).
1170 llvm::SmallVector<FieldDecl *, 4> Path;
1171 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump11289f42009-09-09 15:08:12 +00001172
Douglas Gregord5846a12009-04-15 06:41:24 +00001173 // Build the replacement designators.
1174 llvm::SmallVector<Designator, 4> Replacements;
1175 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1176 FI = Path.rbegin(), FIEnd = Path.rend();
1177 FI != FIEnd; ++FI) {
1178 if (FI + 1 == FIEnd)
Mike Stump11289f42009-09-09 15:08:12 +00001179 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001180 DIE->getDesignator(DesigIdx)->getDotLoc(),
1181 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1182 else
1183 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1184 SourceLocation()));
1185 Replacements.back().setField(*FI);
1186 }
1187
1188 // Expand the current designator into the set of replacement
1189 // designators, so we have a full subobject path down to where the
1190 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001191 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001192 &Replacements[0] + Replacements.size());
Mike Stump11289f42009-09-09 15:08:12 +00001193
Douglas Gregord5846a12009-04-15 06:41:24 +00001194 // Update FieldIter/FieldIndex;
1195 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001196 FieldIter = Record->field_begin();
Douglas Gregord5846a12009-04-15 06:41:24 +00001197 FieldIndex = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001198 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregord5846a12009-04-15 06:41:24 +00001199 FieldIter != FEnd; ++FieldIter) {
1200 if (FieldIter->isUnnamedBitfield())
1201 continue;
1202
1203 if (*FieldIter == Path.back())
1204 return;
1205
1206 ++FieldIndex;
1207 }
1208
1209 assert(false && "Unable to find anonymous struct/union field");
1210}
1211
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001212/// @brief Check the well-formedness of a C99 designated initializer.
1213///
1214/// Determines whether the designated initializer @p DIE, which
1215/// resides at the given @p Index within the initializer list @p
1216/// IList, is well-formed for a current object of type @p DeclType
1217/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001218/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001219/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001220///
1221/// @param IList The initializer list in which this designated
1222/// initializer occurs.
1223///
Douglas Gregora5324162009-04-15 04:56:10 +00001224/// @param DIE The designated initializer expression.
1225///
1226/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001227///
1228/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1229/// into which the designation in @p DIE should refer.
1230///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001231/// @param NextField If non-NULL and the first designator in @p DIE is
1232/// a field, this will be set to the field declaration corresponding
1233/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001234///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001235/// @param NextElementIndex If non-NULL and the first designator in @p
1236/// DIE is an array designator or GNU array-range designator, this
1237/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001238///
1239/// @param Index Index into @p IList where the designated initializer
1240/// @p DIE occurs.
1241///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001242/// @param StructuredList The initializer list expression that
1243/// describes all of the subobject initializers in the order they'll
1244/// actually be initialized.
1245///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001246/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001247bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001248InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001249 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001250 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001251 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001252 QualType &CurrentObjectType,
1253 RecordDecl::field_iterator *NextField,
1254 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001255 unsigned &Index,
1256 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001257 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001258 bool FinishSubobjectInit,
1259 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001260 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001261 // Check the actual initialization for the designated object type.
1262 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001263
1264 // Temporarily remove the designator expression from the
1265 // initializer list that the child calls see, so that we don't try
1266 // to re-process the designator.
1267 unsigned OldIndex = Index;
1268 IList->setInit(OldIndex, DIE->getInit());
1269
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001270 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001271 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001272
1273 // Restore the designated initializer expression in the syntactic
1274 // form of the initializer list.
1275 if (IList->getInit(OldIndex) != DIE->getInit())
1276 DIE->setInit(IList->getInit(OldIndex));
1277 IList->setInit(OldIndex, DIE);
1278
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001279 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001280 }
1281
Douglas Gregora5324162009-04-15 04:56:10 +00001282 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001283 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001284 "Need a non-designated initializer list to start from");
1285
Douglas Gregora5324162009-04-15 04:56:10 +00001286 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001287 // Determine the structural initializer list that corresponds to the
1288 // current subobject.
1289 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001290 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001291 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001292 SourceRange(D->getStartLocation(),
1293 DIE->getSourceRange().getEnd()));
1294 assert(StructuredList && "Expected a structured initializer list");
1295
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001296 if (D->isFieldDesignator()) {
1297 // C99 6.7.8p7:
1298 //
1299 // If a designator has the form
1300 //
1301 // . identifier
1302 //
1303 // then the current object (defined below) shall have
1304 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001305 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001306 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001307 if (!RT) {
1308 SourceLocation Loc = D->getDotLoc();
1309 if (Loc.isInvalid())
1310 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001311 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1312 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001313 ++Index;
1314 return true;
1315 }
1316
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001317 // Note: we perform a linear search of the fields here, despite
1318 // the fact that we have a faster lookup method, because we always
1319 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001320 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001321 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001322 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001323 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001324 Field = RT->getDecl()->field_begin(),
1325 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001326 for (; Field != FieldEnd; ++Field) {
1327 if (Field->isUnnamedBitfield())
1328 continue;
1329
Douglas Gregord5846a12009-04-15 06:41:24 +00001330 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001331 break;
1332
1333 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001334 }
1335
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001336 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001337 // There was no normal field in the struct with the designated
1338 // name. Perform another lookup for this name, which may find
1339 // something that we can't designate (e.g., a member function),
1340 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001341 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001342 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001343 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001344 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001345 // Name lookup didn't find anything. Determine whether this
1346 // was a typo for another field name.
1347 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1348 Sema::LookupMemberName);
1349 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl()) &&
1350 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
1351 ReplacementField->getDeclContext()->getLookupContext()
1352 ->Equals(RT->getDecl())) {
1353 SemaRef.Diag(D->getFieldLoc(),
1354 diag::err_field_designator_unknown_suggest)
1355 << FieldName << CurrentObjectType << R.getLookupName()
1356 << CodeModificationHint::CreateReplacement(D->getFieldLoc(),
1357 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001358 SemaRef.Diag(ReplacementField->getLocation(),
1359 diag::note_previous_decl)
1360 << ReplacementField->getDeclName();
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001361 } else {
1362 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1363 << FieldName << CurrentObjectType;
1364 ++Index;
1365 return true;
1366 }
1367 } else if (!KnownField) {
1368 // Determine whether we found a field at all.
1369 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1370 }
1371
1372 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001373 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001374 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001375 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001376 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001377 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001378 ++Index;
1379 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001380 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001381
1382 if (!KnownField &&
1383 cast<RecordDecl>((ReplacementField)->getDeclContext())
1384 ->isAnonymousStructOrUnion()) {
1385 // Handle an field designator that refers to a member of an
1386 // anonymous struct or union.
1387 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1388 ReplacementField,
1389 Field, FieldIndex);
1390 D = DIE->getDesignator(DesigIdx);
1391 } else if (!KnownField) {
1392 // The replacement field comes from typo correction; find it
1393 // in the list of fields.
1394 FieldIndex = 0;
1395 Field = RT->getDecl()->field_begin();
1396 for (; Field != FieldEnd; ++Field) {
1397 if (Field->isUnnamedBitfield())
1398 continue;
1399
1400 if (ReplacementField == *Field ||
1401 Field->getIdentifier() == ReplacementField->getIdentifier())
1402 break;
1403
1404 ++FieldIndex;
1405 }
1406 }
Douglas Gregord5846a12009-04-15 06:41:24 +00001407 } else if (!KnownField &&
1408 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001409 ->isAnonymousStructOrUnion()) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001410 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1411 Field, FieldIndex);
1412 D = DIE->getDesignator(DesigIdx);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001413 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001414
1415 // All of the fields of a union are located at the same place in
1416 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001417 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001418 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001419 StructuredList->setInitializedFieldInUnion(*Field);
1420 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001421
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001422 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001423 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001424
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001425 // Make sure that our non-designated initializer list has space
1426 // for a subobject corresponding to this field.
1427 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001428 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001429
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001430 // This designator names a flexible array member.
1431 if (Field->getType()->isIncompleteArrayType()) {
1432 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001433 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001434 // We can't designate an object within the flexible array
1435 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001436 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001437 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001438 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001439 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001440 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001441 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001442 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001443 << *Field;
1444 Invalid = true;
1445 }
1446
1447 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1448 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001449 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001450 diag::err_flexible_array_init_needs_braces)
1451 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001452 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001453 << *Field;
1454 Invalid = true;
1455 }
1456
1457 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001458 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001459 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001460 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001461 diag::err_flexible_array_init_nonempty)
1462 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001463 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001464 << *Field;
1465 Invalid = true;
1466 }
1467
1468 if (Invalid) {
1469 ++Index;
1470 return true;
1471 }
1472
1473 // Initialize the array.
1474 bool prevHadError = hadError;
1475 unsigned newStructuredIndex = FieldIndex;
1476 unsigned OldIndex = Index;
1477 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001478
1479 InitializedEntity MemberEntity =
1480 InitializedEntity::InitializeMember(*Field, &Entity);
1481 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001482 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001483
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001484 IList->setInit(OldIndex, DIE);
1485 if (hadError && !prevHadError) {
1486 ++Field;
1487 ++FieldIndex;
1488 if (NextField)
1489 *NextField = Field;
1490 StructuredIndex = FieldIndex;
1491 return true;
1492 }
1493 } else {
1494 // Recurse to check later designated subobjects.
1495 QualType FieldType = (*Field)->getType();
1496 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001497
1498 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001499 InitializedEntity::InitializeMember(*Field, &Entity);
1500 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001501 FieldType, 0, 0, Index,
1502 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001503 true, false))
1504 return true;
1505 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001506
1507 // Find the position of the next field to be initialized in this
1508 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001509 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001510 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001511
1512 // If this the first designator, our caller will continue checking
1513 // the rest of this struct/class/union subobject.
1514 if (IsFirstDesignator) {
1515 if (NextField)
1516 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001517 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001518 return false;
1519 }
1520
Douglas Gregor17bd0942009-01-28 23:36:17 +00001521 if (!FinishSubobjectInit)
1522 return false;
1523
Douglas Gregord5846a12009-04-15 06:41:24 +00001524 // We've already initialized something in the union; we're done.
1525 if (RT->getDecl()->isUnion())
1526 return hadError;
1527
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001528 // Check the remaining fields within this class/struct/union subobject.
1529 bool prevHadError = hadError;
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001530
Anders Carlsson6cabf312010-01-23 23:23:01 +00001531 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001532 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001533 return hadError && !prevHadError;
1534 }
1535
1536 // C99 6.7.8p6:
1537 //
1538 // If a designator has the form
1539 //
1540 // [ constant-expression ]
1541 //
1542 // then the current object (defined below) shall have array
1543 // type and the expression shall be an integer constant
1544 // expression. If the array is of unknown size, any
1545 // nonnegative value is valid.
1546 //
1547 // Additionally, cope with the GNU extension that permits
1548 // designators of the form
1549 //
1550 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001551 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001552 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001553 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001554 << CurrentObjectType;
1555 ++Index;
1556 return true;
1557 }
1558
1559 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001560 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1561 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001562 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001563 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001564 DesignatedEndIndex = DesignatedStartIndex;
1565 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001566 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001567
Mike Stump11289f42009-09-09 15:08:12 +00001568
1569 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001570 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001571 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001572 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001573 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001574
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001575 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001576 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001577 }
1578
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001579 if (isa<ConstantArrayType>(AT)) {
1580 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001581 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1582 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1583 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1584 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1585 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001586 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001587 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001588 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001589 << IndexExpr->getSourceRange();
1590 ++Index;
1591 return true;
1592 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001593 } else {
1594 // Make sure the bit-widths and signedness match.
1595 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1596 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001597 else if (DesignatedStartIndex.getBitWidth() <
1598 DesignatedEndIndex.getBitWidth())
Douglas Gregor17bd0942009-01-28 23:36:17 +00001599 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1600 DesignatedStartIndex.setIsUnsigned(true);
1601 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001602 }
Mike Stump11289f42009-09-09 15:08:12 +00001603
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001604 // Make sure that our non-designated initializer list has space
1605 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001606 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001607 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001608 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001609
Douglas Gregor17bd0942009-01-28 23:36:17 +00001610 // Repeatedly perform subobject initializations in the range
1611 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001612
Douglas Gregor17bd0942009-01-28 23:36:17 +00001613 // Move to the next designator
1614 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1615 unsigned OldIndex = Index;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001616
1617 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001618 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001619
Douglas Gregor17bd0942009-01-28 23:36:17 +00001620 while (DesignatedStartIndex <= DesignatedEndIndex) {
1621 // Recurse to check later designated subobjects.
1622 QualType ElementType = AT->getElementType();
1623 Index = OldIndex;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001624
1625 ElementEntity.setElementIndex(ElementIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001626 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001627 ElementType, 0, 0, Index,
1628 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001629 (DesignatedStartIndex == DesignatedEndIndex),
1630 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001631 return true;
1632
1633 // Move to the next index in the array that we'll be initializing.
1634 ++DesignatedStartIndex;
1635 ElementIndex = DesignatedStartIndex.getZExtValue();
1636 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001637
1638 // If this the first designator, our caller will continue checking
1639 // the rest of this array subobject.
1640 if (IsFirstDesignator) {
1641 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001642 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001643 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001644 return false;
1645 }
Mike Stump11289f42009-09-09 15:08:12 +00001646
Douglas Gregor17bd0942009-01-28 23:36:17 +00001647 if (!FinishSubobjectInit)
1648 return false;
1649
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001650 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001651 bool prevHadError = hadError;
Anders Carlsson6cabf312010-01-23 23:23:01 +00001652 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001653 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001654 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001655 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001656}
1657
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001658// Get the structured initializer list for a subobject of type
1659// @p CurrentObjectType.
1660InitListExpr *
1661InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1662 QualType CurrentObjectType,
1663 InitListExpr *StructuredList,
1664 unsigned StructuredIndex,
1665 SourceRange InitRange) {
1666 Expr *ExistingInit = 0;
1667 if (!StructuredList)
1668 ExistingInit = SyntacticToSemantic[IList];
1669 else if (StructuredIndex < StructuredList->getNumInits())
1670 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001671
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001672 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1673 return Result;
1674
1675 if (ExistingInit) {
1676 // We are creating an initializer list that initializes the
1677 // subobjects of the current object, but there was already an
1678 // initialization that completely initialized the current
1679 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001680 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001681 // struct X { int a, b; };
1682 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001683 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001684 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1685 // designated initializer re-initializes the whole
1686 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001687 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001688 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001689 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001690 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001691 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001692 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001693 << ExistingInit->getSourceRange();
1694 }
1695
Mike Stump11289f42009-09-09 15:08:12 +00001696 InitListExpr *Result
1697 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001698 InitRange.getEnd());
1699
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001700 Result->setType(CurrentObjectType);
1701
Douglas Gregor6d00c992009-03-20 23:58:33 +00001702 // Pre-allocate storage for the structured initializer list.
1703 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001704 unsigned NumInits = 0;
1705 if (!StructuredList)
1706 NumInits = IList->getNumInits();
1707 else if (Index < IList->getNumInits()) {
1708 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1709 NumInits = SubList->getNumInits();
1710 }
1711
Mike Stump11289f42009-09-09 15:08:12 +00001712 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001713 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1714 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1715 NumElements = CAType->getSize().getZExtValue();
1716 // Simple heuristic so that we don't allocate a very large
1717 // initializer with many empty entries at the end.
Douglas Gregor221c9a52009-03-21 18:13:52 +00001718 if (NumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001719 NumElements = 0;
1720 }
John McCall9dd450b2009-09-21 23:43:11 +00001721 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001722 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001723 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001724 RecordDecl *RDecl = RType->getDecl();
1725 if (RDecl->isUnion())
1726 NumElements = 1;
1727 else
Mike Stump11289f42009-09-09 15:08:12 +00001728 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001729 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001730 }
1731
Douglas Gregor221c9a52009-03-21 18:13:52 +00001732 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001733 NumElements = IList->getNumInits();
1734
1735 Result->reserveInits(NumElements);
1736
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001737 // Link this new initializer list into the structured initializer
1738 // lists.
1739 if (StructuredList)
1740 StructuredList->updateInit(StructuredIndex, Result);
1741 else {
1742 Result->setSyntacticForm(IList);
1743 SyntacticToSemantic[IList] = Result;
1744 }
1745
1746 return Result;
1747}
1748
1749/// Update the initializer at index @p StructuredIndex within the
1750/// structured initializer list to the value @p expr.
1751void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1752 unsigned &StructuredIndex,
1753 Expr *expr) {
1754 // No structured initializer list to update
1755 if (!StructuredList)
1756 return;
1757
1758 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1759 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001760 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001761 diag::warn_initializer_overrides)
1762 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001763 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001764 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001765 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001766 << PrevInit->getSourceRange();
1767 }
Mike Stump11289f42009-09-09 15:08:12 +00001768
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001769 ++StructuredIndex;
1770}
1771
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001772/// Check that the given Index expression is a valid array designator
1773/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001774/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001775/// and produces a reasonable diagnostic if there is a
1776/// failure. Returns true if there was an error, false otherwise. If
1777/// everything went okay, Value will receive the value of the constant
1778/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001779static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001780CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001781 SourceLocation Loc = Index->getSourceRange().getBegin();
1782
1783 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001784 if (S.VerifyIntegerConstantExpression(Index, &Value))
1785 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001786
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001787 if (Value.isSigned() && Value.isNegative())
1788 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001789 << Value.toString(10) << Index->getSourceRange();
1790
Douglas Gregor51650d32009-01-23 21:04:18 +00001791 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001792 return false;
1793}
1794
1795Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1796 SourceLocation Loc,
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00001797 bool GNUSyntax,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001798 OwningExprResult Init) {
1799 typedef DesignatedInitExpr::Designator ASTDesignator;
1800
1801 bool Invalid = false;
1802 llvm::SmallVector<ASTDesignator, 32> Designators;
1803 llvm::SmallVector<Expr *, 32> InitExpressions;
1804
1805 // Build designators and check array designator expressions.
1806 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1807 const Designator &D = Desig.getDesignator(Idx);
1808 switch (D.getKind()) {
1809 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001810 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001811 D.getFieldLoc()));
1812 break;
1813
1814 case Designator::ArrayDesignator: {
1815 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1816 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001817 if (!Index->isTypeDependent() &&
1818 !Index->isValueDependent() &&
1819 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001820 Invalid = true;
1821 else {
1822 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001823 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001824 D.getRBracketLoc()));
1825 InitExpressions.push_back(Index);
1826 }
1827 break;
1828 }
1829
1830 case Designator::ArrayRangeDesignator: {
1831 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1832 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1833 llvm::APSInt StartValue;
1834 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001835 bool StartDependent = StartIndex->isTypeDependent() ||
1836 StartIndex->isValueDependent();
1837 bool EndDependent = EndIndex->isTypeDependent() ||
1838 EndIndex->isValueDependent();
1839 if ((!StartDependent &&
1840 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1841 (!EndDependent &&
1842 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001843 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001844 else {
1845 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001846 if (StartDependent || EndDependent) {
1847 // Nothing to compute.
1848 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregor7a95b082009-01-23 22:22:29 +00001849 EndValue.extend(StartValue.getBitWidth());
1850 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1851 StartValue.extend(EndValue.getBitWidth());
1852
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001853 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001854 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001855 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001856 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1857 Invalid = true;
1858 } else {
1859 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001860 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001861 D.getEllipsisLoc(),
1862 D.getRBracketLoc()));
1863 InitExpressions.push_back(StartIndex);
1864 InitExpressions.push_back(EndIndex);
1865 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001866 }
1867 break;
1868 }
1869 }
1870 }
1871
1872 if (Invalid || Init.isInvalid())
1873 return ExprError();
1874
1875 // Clear out the expressions within the designation.
1876 Desig.ClearExprs(*this);
1877
1878 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001879 = DesignatedInitExpr::Create(Context,
1880 Designators.data(), Designators.size(),
1881 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001882 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001883 return Owned(DIE);
1884}
Douglas Gregor85df8d82009-01-29 00:45:39 +00001885
Douglas Gregor723796a2009-12-16 06:35:08 +00001886bool Sema::CheckInitList(const InitializedEntity &Entity,
1887 InitListExpr *&InitList, QualType &DeclType) {
1888 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00001889 if (!CheckInitList.HadError())
1890 InitList = CheckInitList.getFullyStructuredList();
1891
1892 return CheckInitList.HadError();
1893}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00001894
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001895//===----------------------------------------------------------------------===//
1896// Initialization entity
1897//===----------------------------------------------------------------------===//
1898
Douglas Gregor723796a2009-12-16 06:35:08 +00001899InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1900 const InitializedEntity &Parent)
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001901 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00001902{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001903 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1904 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001905 Type = AT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001906 } else {
1907 Kind = EK_VectorElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001908 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001909 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001910}
1911
1912InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1913 CXXBaseSpecifier *Base)
1914{
1915 InitializedEntity Result;
1916 Result.Kind = EK_Base;
1917 Result.Base = Base;
Douglas Gregor1b303932009-12-22 15:35:07 +00001918 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001919 return Result;
1920}
1921
Douglas Gregor85dabae2009-12-16 01:38:02 +00001922DeclarationName InitializedEntity::getName() const {
1923 switch (getKind()) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00001924 case EK_Parameter:
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00001925 if (!VariableOrMember)
1926 return DeclarationName();
1927 // Fall through
1928
1929 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001930 case EK_Member:
1931 return VariableOrMember->getDeclName();
1932
1933 case EK_Result:
1934 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00001935 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001936 case EK_Temporary:
1937 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001938 case EK_ArrayElement:
1939 case EK_VectorElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001940 return DeclarationName();
1941 }
1942
1943 // Silence GCC warning
1944 return DeclarationName();
1945}
1946
Douglas Gregora4b592a2009-12-19 03:01:41 +00001947DeclaratorDecl *InitializedEntity::getDecl() const {
1948 switch (getKind()) {
1949 case EK_Variable:
1950 case EK_Parameter:
1951 case EK_Member:
1952 return VariableOrMember;
1953
1954 case EK_Result:
1955 case EK_Exception:
1956 case EK_New:
1957 case EK_Temporary:
1958 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001959 case EK_ArrayElement:
1960 case EK_VectorElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00001961 return 0;
1962 }
1963
1964 // Silence GCC warning
1965 return 0;
1966}
1967
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001968//===----------------------------------------------------------------------===//
1969// Initialization sequence
1970//===----------------------------------------------------------------------===//
1971
1972void InitializationSequence::Step::Destroy() {
1973 switch (Kind) {
1974 case SK_ResolveAddressOfOverloadedFunction:
1975 case SK_CastDerivedToBaseRValue:
1976 case SK_CastDerivedToBaseLValue:
1977 case SK_BindReference:
1978 case SK_BindReferenceToTemporary:
1979 case SK_UserConversion:
1980 case SK_QualificationConversionRValue:
1981 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00001982 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00001983 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00001984 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00001985 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00001986 case SK_StringInit:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001987 break;
1988
1989 case SK_ConversionSequence:
1990 delete ICS;
1991 }
1992}
1993
1994void InitializationSequence::AddAddressOverloadResolutionStep(
1995 FunctionDecl *Function) {
1996 Step S;
1997 S.Kind = SK_ResolveAddressOfOverloadedFunction;
1998 S.Type = Function->getType();
1999 S.Function = Function;
2000 Steps.push_back(S);
2001}
2002
2003void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2004 bool IsLValue) {
2005 Step S;
2006 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
2007 S.Type = BaseType;
2008 Steps.push_back(S);
2009}
2010
2011void InitializationSequence::AddReferenceBindingStep(QualType T,
2012 bool BindingTemporary) {
2013 Step S;
2014 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2015 S.Type = T;
2016 Steps.push_back(S);
2017}
2018
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002019void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2020 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002021 Step S;
2022 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002023 S.Type = T;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002024 S.Function = Function;
2025 Steps.push_back(S);
2026}
2027
2028void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2029 bool IsLValue) {
2030 Step S;
2031 S.Kind = IsLValue? SK_QualificationConversionLValue
2032 : SK_QualificationConversionRValue;
2033 S.Type = Ty;
2034 Steps.push_back(S);
2035}
2036
2037void InitializationSequence::AddConversionSequenceStep(
2038 const ImplicitConversionSequence &ICS,
2039 QualType T) {
2040 Step S;
2041 S.Kind = SK_ConversionSequence;
2042 S.Type = T;
2043 S.ICS = new ImplicitConversionSequence(ICS);
2044 Steps.push_back(S);
2045}
2046
Douglas Gregor51e77d52009-12-10 17:56:55 +00002047void InitializationSequence::AddListInitializationStep(QualType T) {
2048 Step S;
2049 S.Kind = SK_ListInitialization;
2050 S.Type = T;
2051 Steps.push_back(S);
2052}
2053
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002054void
2055InitializationSequence::AddConstructorInitializationStep(
2056 CXXConstructorDecl *Constructor,
2057 QualType T) {
2058 Step S;
2059 S.Kind = SK_ConstructorInitialization;
2060 S.Type = T;
2061 S.Function = Constructor;
2062 Steps.push_back(S);
2063}
2064
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002065void InitializationSequence::AddZeroInitializationStep(QualType T) {
2066 Step S;
2067 S.Kind = SK_ZeroInitialization;
2068 S.Type = T;
2069 Steps.push_back(S);
2070}
2071
Douglas Gregore1314a62009-12-18 05:02:21 +00002072void InitializationSequence::AddCAssignmentStep(QualType T) {
2073 Step S;
2074 S.Kind = SK_CAssignment;
2075 S.Type = T;
2076 Steps.push_back(S);
2077}
2078
Eli Friedman78275202009-12-19 08:11:05 +00002079void InitializationSequence::AddStringInitStep(QualType T) {
2080 Step S;
2081 S.Kind = SK_StringInit;
2082 S.Type = T;
2083 Steps.push_back(S);
2084}
2085
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002086void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2087 OverloadingResult Result) {
2088 SequenceKind = FailedSequence;
2089 this->Failure = Failure;
2090 this->FailedOverloadResult = Result;
2091}
2092
2093//===----------------------------------------------------------------------===//
2094// Attempt initialization
2095//===----------------------------------------------------------------------===//
2096
2097/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregor51e77d52009-12-10 17:56:55 +00002098static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002099 const InitializedEntity &Entity,
2100 const InitializationKind &Kind,
2101 InitListExpr *InitList,
2102 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00002103 // FIXME: We only perform rudimentary checking of list
2104 // initializations at this point, then assume that any list
2105 // initialization of an array, aggregate, or scalar will be
2106 // well-formed. We we actually "perform" list initialization, we'll
2107 // do all of the necessary checking. C++0x initializer lists will
2108 // force us to perform more checking here.
2109 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2110
Douglas Gregor1b303932009-12-22 15:35:07 +00002111 QualType DestType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00002112
2113 // C++ [dcl.init]p13:
2114 // If T is a scalar type, then a declaration of the form
2115 //
2116 // T x = { a };
2117 //
2118 // is equivalent to
2119 //
2120 // T x = a;
2121 if (DestType->isScalarType()) {
2122 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2123 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2124 return;
2125 }
2126
2127 // Assume scalar initialization from a single value works.
2128 } else if (DestType->isAggregateType()) {
2129 // Assume aggregate initialization works.
2130 } else if (DestType->isVectorType()) {
2131 // Assume vector initialization works.
2132 } else if (DestType->isReferenceType()) {
2133 // FIXME: C++0x defines behavior for this.
2134 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2135 return;
2136 } else if (DestType->isRecordType()) {
2137 // FIXME: C++0x defines behavior for this
2138 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2139 }
2140
2141 // Add a general "list initialization" step.
2142 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002143}
2144
2145/// \brief Try a reference initialization that involves calling a conversion
2146/// function.
2147///
2148/// FIXME: look intos DRs 656, 896
2149static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2150 const InitializedEntity &Entity,
2151 const InitializationKind &Kind,
2152 Expr *Initializer,
2153 bool AllowRValues,
2154 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002155 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002156 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2157 QualType T1 = cv1T1.getUnqualifiedType();
2158 QualType cv2T2 = Initializer->getType();
2159 QualType T2 = cv2T2.getUnqualifiedType();
2160
2161 bool DerivedToBase;
2162 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2163 T1, T2, DerivedToBase) &&
2164 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002165 (void)DerivedToBase;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002166
2167 // Build the candidate set directly in the initialization sequence
2168 // structure, so that it will persist if we fail.
2169 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2170 CandidateSet.clear();
2171
2172 // Determine whether we are allowed to call explicit constructors or
2173 // explicit conversion operators.
2174 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2175
2176 const RecordType *T1RecordType = 0;
2177 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2178 // The type we're converting to is a class type. Enumerate its constructors
2179 // to see if there is a suitable conversion.
2180 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2181
2182 DeclarationName ConstructorName
2183 = S.Context.DeclarationNames.getCXXConstructorName(
2184 S.Context.getCanonicalType(T1).getUnqualifiedType());
2185 DeclContext::lookup_iterator Con, ConEnd;
2186 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2187 Con != ConEnd; ++Con) {
2188 // Find the constructor (which may be a template).
2189 CXXConstructorDecl *Constructor = 0;
2190 FunctionTemplateDecl *ConstructorTmpl
2191 = dyn_cast<FunctionTemplateDecl>(*Con);
2192 if (ConstructorTmpl)
2193 Constructor = cast<CXXConstructorDecl>(
2194 ConstructorTmpl->getTemplatedDecl());
2195 else
2196 Constructor = cast<CXXConstructorDecl>(*Con);
2197
2198 if (!Constructor->isInvalidDecl() &&
2199 Constructor->isConvertingConstructor(AllowExplicit)) {
2200 if (ConstructorTmpl)
2201 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2202 &Initializer, 1, CandidateSet);
2203 else
2204 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2205 }
2206 }
2207 }
2208
2209 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2210 // The type we're converting from is a class type, enumerate its conversion
2211 // functions.
2212 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2213
2214 // Determine the type we are converting to. If we are allowed to
2215 // convert to an rvalue, take the type that the destination type
2216 // refers to.
2217 QualType ToType = AllowRValues? cv1T1 : DestType;
2218
John McCallad371252010-01-20 00:46:10 +00002219 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002220 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002221 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2222 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002223 NamedDecl *D = *I;
2224 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2225 if (isa<UsingShadowDecl>(D))
2226 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2227
2228 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2229 CXXConversionDecl *Conv;
2230 if (ConvTemplate)
2231 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2232 else
2233 Conv = cast<CXXConversionDecl>(*I);
2234
2235 // If the conversion function doesn't return a reference type,
2236 // it can't be considered for this conversion unless we're allowed to
2237 // consider rvalues.
2238 // FIXME: Do we need to make sure that we only consider conversion
2239 // candidates with reference-compatible results? That might be needed to
2240 // break recursion.
2241 if ((AllowExplicit || !Conv->isExplicit()) &&
2242 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2243 if (ConvTemplate)
2244 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2245 ToType, CandidateSet);
2246 else
2247 S.AddConversionCandidate(Conv, ActingDC, Initializer, cv1T1,
2248 CandidateSet);
2249 }
2250 }
2251 }
2252
2253 SourceLocation DeclLoc = Initializer->getLocStart();
2254
2255 // Perform overload resolution. If it fails, return the failed result.
2256 OverloadCandidateSet::iterator Best;
2257 if (OverloadingResult Result
2258 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2259 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002260
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002261 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002262
2263 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002264 if (isa<CXXConversionDecl>(Function))
2265 T2 = Function->getResultType();
2266 else
2267 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002268
2269 // Add the user-defined conversion step.
2270 Sequence.AddUserConversionStep(Function, T2.getNonReferenceType());
2271
2272 // Determine whether we need to perform derived-to-base or
2273 // cv-qualification adjustments.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002274 bool NewDerivedToBase = false;
2275 Sema::ReferenceCompareResult NewRefRelationship
2276 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2277 NewDerivedToBase);
2278 assert(NewRefRelationship != Sema::Ref_Incompatible &&
2279 "Overload resolution picked a bad conversion function");
2280 (void)NewRefRelationship;
2281 if (NewDerivedToBase)
2282 Sequence.AddDerivedToBaseCastStep(
2283 S.Context.getQualifiedType(T1,
2284 T2.getNonReferenceType().getQualifiers()),
2285 /*isLValue=*/true);
2286
2287 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2288 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2289
2290 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2291 return OR_Success;
2292}
2293
2294/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2295static void TryReferenceInitialization(Sema &S,
2296 const InitializedEntity &Entity,
2297 const InitializationKind &Kind,
2298 Expr *Initializer,
2299 InitializationSequence &Sequence) {
2300 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2301
Douglas Gregor1b303932009-12-22 15:35:07 +00002302 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002303 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002304 Qualifiers T1Quals;
2305 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002306 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002307 Qualifiers T2Quals;
2308 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002309 SourceLocation DeclLoc = Initializer->getLocStart();
2310
2311 // If the initializer is the address of an overloaded function, try
2312 // to resolve the overloaded function. If all goes well, T2 is the
2313 // type of the resulting function.
2314 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2315 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2316 T1,
2317 false);
2318 if (!Fn) {
2319 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2320 return;
2321 }
2322
2323 Sequence.AddAddressOverloadResolutionStep(Fn);
2324 cv2T2 = Fn->getType();
2325 T2 = cv2T2.getUnqualifiedType();
2326 }
2327
2328 // FIXME: Rvalue references
2329 bool ForceRValue = false;
2330
2331 // Compute some basic properties of the types and the initializer.
2332 bool isLValueRef = DestType->isLValueReferenceType();
2333 bool isRValueRef = !isLValueRef;
2334 bool DerivedToBase = false;
2335 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2336 Initializer->isLvalue(S.Context);
2337 Sema::ReferenceCompareResult RefRelationship
2338 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2339
2340 // C++0x [dcl.init.ref]p5:
2341 // A reference to type "cv1 T1" is initialized by an expression of type
2342 // "cv2 T2" as follows:
2343 //
2344 // - If the reference is an lvalue reference and the initializer
2345 // expression
2346 OverloadingResult ConvOvlResult = OR_Success;
2347 if (isLValueRef) {
2348 if (InitLvalue == Expr::LV_Valid &&
2349 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2350 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2351 // reference-compatible with "cv2 T2," or
2352 //
2353 // Per C++ [over.best.ics]p2, we ignore whether the lvalue is a
2354 // bit-field when we're determining whether the reference initialization
2355 // can occur. This property will be checked by PerformInitialization.
2356 if (DerivedToBase)
2357 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002358 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002359 /*isLValue=*/true);
Chandler Carruth04bdce62010-01-12 20:32:25 +00002360 if (T1Quals != T2Quals)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002361 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
2362 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/false);
2363 return;
2364 }
2365
2366 // - has a class type (i.e., T2 is a class type), where T1 is not
2367 // reference-related to T2, and can be implicitly converted to an
2368 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2369 // with "cv3 T3" (this conversion is selected by enumerating the
2370 // applicable conversion functions (13.3.1.6) and choosing the best
2371 // one through overload resolution (13.3)),
2372 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2373 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2374 Initializer,
2375 /*AllowRValues=*/false,
2376 Sequence);
2377 if (ConvOvlResult == OR_Success)
2378 return;
John McCall0d1da222010-01-12 00:44:57 +00002379 if (ConvOvlResult != OR_No_Viable_Function) {
2380 Sequence.SetOverloadFailure(
2381 InitializationSequence::FK_ReferenceInitOverloadFailed,
2382 ConvOvlResult);
2383 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002384 }
2385 }
2386
2387 // - Otherwise, the reference shall be an lvalue reference to a
2388 // non-volatile const type (i.e., cv1 shall be const), or the reference
2389 // shall be an rvalue reference and the initializer expression shall
2390 // be an rvalue.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002391 if (!((isLValueRef && T1Quals.hasConst()) ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002392 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2393 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2394 Sequence.SetOverloadFailure(
2395 InitializationSequence::FK_ReferenceInitOverloadFailed,
2396 ConvOvlResult);
2397 else if (isLValueRef)
2398 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2399 ? (RefRelationship == Sema::Ref_Related
2400 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2401 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2402 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2403 else
2404 Sequence.SetFailed(
2405 InitializationSequence::FK_RValueReferenceBindingToLValue);
2406
2407 return;
2408 }
2409
2410 // - If T1 and T2 are class types and
2411 if (T1->isRecordType() && T2->isRecordType()) {
2412 // - the initializer expression is an rvalue and "cv1 T1" is
2413 // reference-compatible with "cv2 T2", or
2414 if (InitLvalue != Expr::LV_Valid &&
2415 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2416 if (DerivedToBase)
2417 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002418 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002419 /*isLValue=*/false);
Chandler Carruth04bdce62010-01-12 20:32:25 +00002420 if (T1Quals != T2Quals)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002421 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2422 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2423 return;
2424 }
2425
2426 // - T1 is not reference-related to T2 and the initializer expression
2427 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2428 // conversion is selected by enumerating the applicable conversion
2429 // functions (13.3.1.6) and choosing the best one through overload
2430 // resolution (13.3)),
2431 if (RefRelationship == Sema::Ref_Incompatible) {
2432 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2433 Kind, Initializer,
2434 /*AllowRValues=*/true,
2435 Sequence);
2436 if (ConvOvlResult)
2437 Sequence.SetOverloadFailure(
2438 InitializationSequence::FK_ReferenceInitOverloadFailed,
2439 ConvOvlResult);
2440
2441 return;
2442 }
2443
2444 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2445 return;
2446 }
2447
2448 // - If the initializer expression is an rvalue, with T2 an array type,
2449 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2450 // is bound to the object represented by the rvalue (see 3.10).
2451 // FIXME: How can an array type be reference-compatible with anything?
2452 // Don't we mean the element types of T1 and T2?
2453
2454 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2455 // from the initializer expression using the rules for a non-reference
2456 // copy initialization (8.5). The reference is then bound to the
2457 // temporary. [...]
2458 // Determine whether we are allowed to call explicit constructors or
2459 // explicit conversion operators.
2460 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2461 ImplicitConversionSequence ICS
2462 = S.TryImplicitConversion(Initializer, cv1T1,
2463 /*SuppressUserConversions=*/false, AllowExplicit,
2464 /*ForceRValue=*/false,
2465 /*FIXME:InOverloadResolution=*/false,
2466 /*UserCast=*/Kind.isExplicitCast());
2467
John McCall0d1da222010-01-12 00:44:57 +00002468 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002469 // FIXME: Use the conversion function set stored in ICS to turn
2470 // this into an overloading ambiguity diagnostic. However, we need
2471 // to keep that set as an OverloadCandidateSet rather than as some
2472 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002473 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2474 Sequence.SetOverloadFailure(
2475 InitializationSequence::FK_ReferenceInitOverloadFailed,
2476 ConvOvlResult);
2477 else
2478 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002479 return;
2480 }
2481
2482 // [...] If T1 is reference-related to T2, cv1 must be the
2483 // same cv-qualification as, or greater cv-qualification
2484 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002485 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2486 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002487 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00002488 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002489 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2490 return;
2491 }
2492
2493 // Perform the actual conversion.
2494 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2495 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2496 return;
2497}
2498
2499/// \brief Attempt character array initialization from a string literal
2500/// (C++ [dcl.init.string], C99 6.7.8).
2501static void TryStringLiteralInitialization(Sema &S,
2502 const InitializedEntity &Entity,
2503 const InitializationKind &Kind,
2504 Expr *Initializer,
2505 InitializationSequence &Sequence) {
Eli Friedman78275202009-12-19 08:11:05 +00002506 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregor1b303932009-12-22 15:35:07 +00002507 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002508}
2509
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002510/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2511/// enumerates the constructors of the initialized entity and performs overload
2512/// resolution to select the best.
2513static void TryConstructorInitialization(Sema &S,
2514 const InitializedEntity &Entity,
2515 const InitializationKind &Kind,
2516 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002517 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002518 InitializationSequence &Sequence) {
Douglas Gregore1314a62009-12-18 05:02:21 +00002519 if (Kind.getKind() == InitializationKind::IK_Copy)
2520 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2521 else
2522 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002523
2524 // Build the candidate set directly in the initialization sequence
2525 // structure, so that it will persist if we fail.
2526 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2527 CandidateSet.clear();
2528
2529 // Determine whether we are allowed to call explicit constructors or
2530 // explicit conversion operators.
2531 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2532 Kind.getKind() == InitializationKind::IK_Value ||
2533 Kind.getKind() == InitializationKind::IK_Default);
2534
2535 // The type we're converting to is a class type. Enumerate its constructors
2536 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002537 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2538 assert(DestRecordType && "Constructor initialization requires record type");
2539 CXXRecordDecl *DestRecordDecl
2540 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2541
2542 DeclarationName ConstructorName
2543 = S.Context.DeclarationNames.getCXXConstructorName(
2544 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2545 DeclContext::lookup_iterator Con, ConEnd;
2546 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2547 Con != ConEnd; ++Con) {
2548 // Find the constructor (which may be a template).
2549 CXXConstructorDecl *Constructor = 0;
2550 FunctionTemplateDecl *ConstructorTmpl
2551 = dyn_cast<FunctionTemplateDecl>(*Con);
2552 if (ConstructorTmpl)
2553 Constructor = cast<CXXConstructorDecl>(
2554 ConstructorTmpl->getTemplatedDecl());
2555 else
2556 Constructor = cast<CXXConstructorDecl>(*Con);
2557
2558 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002559 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002560 if (ConstructorTmpl)
2561 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2562 Args, NumArgs, CandidateSet);
2563 else
2564 S.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2565 }
2566 }
2567
2568 SourceLocation DeclLoc = Kind.getLocation();
2569
2570 // Perform overload resolution. If it fails, return the failed result.
2571 OverloadCandidateSet::iterator Best;
2572 if (OverloadingResult Result
2573 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2574 Sequence.SetOverloadFailure(
2575 InitializationSequence::FK_ConstructorOverloadFailed,
2576 Result);
2577 return;
2578 }
2579
2580 // Add the constructor initialization step. Any cv-qualification conversion is
2581 // subsumed by the initialization.
Douglas Gregore1314a62009-12-18 05:02:21 +00002582 if (Kind.getKind() == InitializationKind::IK_Copy) {
2583 Sequence.AddUserConversionStep(Best->Function, DestType);
2584 } else {
2585 Sequence.AddConstructorInitializationStep(
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002586 cast<CXXConstructorDecl>(Best->Function),
Douglas Gregore1314a62009-12-18 05:02:21 +00002587 DestType);
2588 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002589}
2590
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002591/// \brief Attempt value initialization (C++ [dcl.init]p7).
2592static void TryValueInitialization(Sema &S,
2593 const InitializedEntity &Entity,
2594 const InitializationKind &Kind,
2595 InitializationSequence &Sequence) {
2596 // C++ [dcl.init]p5:
2597 //
2598 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00002599 QualType T = Entity.getType();
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002600
2601 // -- if T is an array type, then each element is value-initialized;
2602 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2603 T = AT->getElementType();
2604
2605 if (const RecordType *RT = T->getAs<RecordType>()) {
2606 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2607 // -- if T is a class type (clause 9) with a user-declared
2608 // constructor (12.1), then the default constructor for T is
2609 // called (and the initialization is ill-formed if T has no
2610 // accessible default constructor);
2611 //
2612 // FIXME: we really want to refer to a single subobject of the array,
2613 // but Entity doesn't have a way to capture that (yet).
2614 if (ClassDecl->hasUserDeclaredConstructor())
2615 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2616
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002617 // -- if T is a (possibly cv-qualified) non-union class type
2618 // without a user-provided constructor, then the object is
2619 // zero-initialized and, if T’s implicitly-declared default
2620 // constructor is non-trivial, that constructor is called.
2621 if ((ClassDecl->getTagKind() == TagDecl::TK_class ||
2622 ClassDecl->getTagKind() == TagDecl::TK_struct) &&
2623 !ClassDecl->hasTrivialConstructor()) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002624 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002625 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2626 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002627 }
2628 }
2629
Douglas Gregor1b303932009-12-22 15:35:07 +00002630 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002631 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2632}
2633
Douglas Gregor85dabae2009-12-16 01:38:02 +00002634/// \brief Attempt default initialization (C++ [dcl.init]p6).
2635static void TryDefaultInitialization(Sema &S,
2636 const InitializedEntity &Entity,
2637 const InitializationKind &Kind,
2638 InitializationSequence &Sequence) {
2639 assert(Kind.getKind() == InitializationKind::IK_Default);
2640
2641 // C++ [dcl.init]p6:
2642 // To default-initialize an object of type T means:
2643 // - if T is an array type, each element is default-initialized;
Douglas Gregor1b303932009-12-22 15:35:07 +00002644 QualType DestType = Entity.getType();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002645 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2646 DestType = Array->getElementType();
2647
2648 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2649 // constructor for T is called (and the initialization is ill-formed if
2650 // T has no accessible default constructor);
2651 if (DestType->isRecordType()) {
2652 // FIXME: If a program calls for the default initialization of an object of
2653 // a const-qualified type T, T shall be a class type with a user-provided
2654 // default constructor.
2655 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2656 Sequence);
2657 }
2658
2659 // - otherwise, no initialization is performed.
2660 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2661
2662 // If a program calls for the default initialization of an object of
2663 // a const-qualified type T, T shall be a class type with a user-provided
2664 // default constructor.
2665 if (DestType.isConstQualified())
2666 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2667}
2668
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002669/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2670/// which enumerates all conversion functions and performs overload resolution
2671/// to select the best.
2672static void TryUserDefinedConversion(Sema &S,
2673 const InitializedEntity &Entity,
2674 const InitializationKind &Kind,
2675 Expr *Initializer,
2676 InitializationSequence &Sequence) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002677 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2678
Douglas Gregor1b303932009-12-22 15:35:07 +00002679 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002680 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2681 QualType SourceType = Initializer->getType();
2682 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2683 "Must have a class type to perform a user-defined conversion");
2684
2685 // Build the candidate set directly in the initialization sequence
2686 // structure, so that it will persist if we fail.
2687 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2688 CandidateSet.clear();
2689
2690 // Determine whether we are allowed to call explicit constructors or
2691 // explicit conversion operators.
2692 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2693
2694 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2695 // The type we're converting to is a class type. Enumerate its constructors
2696 // to see if there is a suitable conversion.
2697 CXXRecordDecl *DestRecordDecl
2698 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2699
2700 DeclarationName ConstructorName
2701 = S.Context.DeclarationNames.getCXXConstructorName(
2702 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2703 DeclContext::lookup_iterator Con, ConEnd;
2704 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2705 Con != ConEnd; ++Con) {
2706 // Find the constructor (which may be a template).
2707 CXXConstructorDecl *Constructor = 0;
2708 FunctionTemplateDecl *ConstructorTmpl
2709 = dyn_cast<FunctionTemplateDecl>(*Con);
2710 if (ConstructorTmpl)
2711 Constructor = cast<CXXConstructorDecl>(
2712 ConstructorTmpl->getTemplatedDecl());
2713 else
2714 Constructor = cast<CXXConstructorDecl>(*Con);
2715
2716 if (!Constructor->isInvalidDecl() &&
2717 Constructor->isConvertingConstructor(AllowExplicit)) {
2718 if (ConstructorTmpl)
2719 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2720 &Initializer, 1, CandidateSet);
2721 else
2722 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2723 }
2724 }
2725 }
Eli Friedman78275202009-12-19 08:11:05 +00002726
2727 SourceLocation DeclLoc = Initializer->getLocStart();
2728
Douglas Gregor540c3b02009-12-14 17:27:33 +00002729 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2730 // The type we're converting from is a class type, enumerate its conversion
2731 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00002732
Eli Friedman4afe9a32009-12-20 22:12:03 +00002733 // We can only enumerate the conversion functions for a complete type; if
2734 // the type isn't complete, simply skip this step.
2735 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2736 CXXRecordDecl *SourceRecordDecl
2737 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002738
John McCallad371252010-01-20 00:46:10 +00002739 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00002740 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002741 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman4afe9a32009-12-20 22:12:03 +00002742 E = Conversions->end();
2743 I != E; ++I) {
2744 NamedDecl *D = *I;
2745 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2746 if (isa<UsingShadowDecl>(D))
2747 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2748
2749 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2750 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00002751 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00002752 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002753 else
Eli Friedman4afe9a32009-12-20 22:12:03 +00002754 Conv = cast<CXXConversionDecl>(*I);
2755
2756 if (AllowExplicit || !Conv->isExplicit()) {
2757 if (ConvTemplate)
2758 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC,
2759 Initializer, DestType,
2760 CandidateSet);
2761 else
2762 S.AddConversionCandidate(Conv, ActingDC, Initializer, DestType,
2763 CandidateSet);
2764 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002765 }
2766 }
2767 }
2768
Douglas Gregor540c3b02009-12-14 17:27:33 +00002769 // Perform overload resolution. If it fails, return the failed result.
2770 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00002771 if (OverloadingResult Result
Douglas Gregor540c3b02009-12-14 17:27:33 +00002772 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2773 Sequence.SetOverloadFailure(
2774 InitializationSequence::FK_UserConversionOverloadFailed,
2775 Result);
2776 return;
2777 }
John McCall0d1da222010-01-12 00:44:57 +00002778
Douglas Gregor540c3b02009-12-14 17:27:33 +00002779 FunctionDecl *Function = Best->Function;
2780
2781 if (isa<CXXConstructorDecl>(Function)) {
2782 // Add the user-defined conversion step. Any cv-qualification conversion is
2783 // subsumed by the initialization.
2784 Sequence.AddUserConversionStep(Function, DestType);
2785 return;
2786 }
2787
2788 // Add the user-defined conversion step that calls the conversion function.
2789 QualType ConvType = Function->getResultType().getNonReferenceType();
2790 Sequence.AddUserConversionStep(Function, ConvType);
2791
2792 // If the conversion following the call to the conversion function is
2793 // interesting, add it as a separate step.
2794 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2795 Best->FinalConversion.Third) {
2796 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00002797 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002798 ICS.Standard = Best->FinalConversion;
2799 Sequence.AddConversionSequenceStep(ICS, DestType);
2800 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002801}
2802
2803/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2804/// non-class type to another.
2805static void TryImplicitConversion(Sema &S,
2806 const InitializedEntity &Entity,
2807 const InitializationKind &Kind,
2808 Expr *Initializer,
2809 InitializationSequence &Sequence) {
2810 ImplicitConversionSequence ICS
Douglas Gregor1b303932009-12-22 15:35:07 +00002811 = S.TryImplicitConversion(Initializer, Entity.getType(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002812 /*SuppressUserConversions=*/true,
2813 /*AllowExplicit=*/false,
2814 /*ForceRValue=*/false,
2815 /*FIXME:InOverloadResolution=*/false,
2816 /*UserCast=*/Kind.isExplicitCast());
2817
John McCall0d1da222010-01-12 00:44:57 +00002818 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002819 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2820 return;
2821 }
2822
Douglas Gregor1b303932009-12-22 15:35:07 +00002823 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002824}
2825
2826InitializationSequence::InitializationSequence(Sema &S,
2827 const InitializedEntity &Entity,
2828 const InitializationKind &Kind,
2829 Expr **Args,
2830 unsigned NumArgs) {
2831 ASTContext &Context = S.Context;
2832
2833 // C++0x [dcl.init]p16:
2834 // The semantics of initializers are as follows. The destination type is
2835 // the type of the object or reference being initialized and the source
2836 // type is the type of the initializer expression. The source type is not
2837 // defined when the initializer is a braced-init-list or when it is a
2838 // parenthesized list of expressions.
Douglas Gregor1b303932009-12-22 15:35:07 +00002839 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002840
2841 if (DestType->isDependentType() ||
2842 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2843 SequenceKind = DependentSequence;
2844 return;
2845 }
2846
2847 QualType SourceType;
2848 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00002849 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002850 Initializer = Args[0];
2851 if (!isa<InitListExpr>(Initializer))
2852 SourceType = Initializer->getType();
2853 }
2854
2855 // - If the initializer is a braced-init-list, the object is
2856 // list-initialized (8.5.4).
2857 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2858 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00002859 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002860 }
2861
2862 // - If the destination type is a reference type, see 8.5.3.
2863 if (DestType->isReferenceType()) {
2864 // C++0x [dcl.init.ref]p1:
2865 // A variable declared to be a T& or T&&, that is, "reference to type T"
2866 // (8.3.2), shall be initialized by an object, or function, of type T or
2867 // by an object that can be converted into a T.
2868 // (Therefore, multiple arguments are not permitted.)
2869 if (NumArgs != 1)
2870 SetFailed(FK_TooManyInitsForReference);
2871 else
2872 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2873 return;
2874 }
2875
2876 // - If the destination type is an array of characters, an array of
2877 // char16_t, an array of char32_t, or an array of wchar_t, and the
2878 // initializer is a string literal, see 8.5.2.
2879 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2880 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2881 return;
2882 }
2883
2884 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002885 if (Kind.getKind() == InitializationKind::IK_Value ||
2886 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002887 TryValueInitialization(S, Entity, Kind, *this);
2888 return;
2889 }
2890
Douglas Gregor85dabae2009-12-16 01:38:02 +00002891 // Handle default initialization.
2892 if (Kind.getKind() == InitializationKind::IK_Default){
2893 TryDefaultInitialization(S, Entity, Kind, *this);
2894 return;
2895 }
Douglas Gregore1314a62009-12-18 05:02:21 +00002896
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002897 // - Otherwise, if the destination type is an array, the program is
2898 // ill-formed.
2899 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2900 if (AT->getElementType()->isAnyCharacterType())
2901 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2902 else
2903 SetFailed(FK_ArrayNeedsInitList);
2904
2905 return;
2906 }
Eli Friedman78275202009-12-19 08:11:05 +00002907
2908 // Handle initialization in C
2909 if (!S.getLangOptions().CPlusPlus) {
2910 setSequenceKind(CAssignment);
2911 AddCAssignmentStep(DestType);
2912 return;
2913 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002914
2915 // - If the destination type is a (possibly cv-qualified) class type:
2916 if (DestType->isRecordType()) {
2917 // - If the initialization is direct-initialization, or if it is
2918 // copy-initialization where the cv-unqualified version of the
2919 // source type is the same class as, or a derived class of, the
2920 // class of the destination, constructors are considered. [...]
2921 if (Kind.getKind() == InitializationKind::IK_Direct ||
2922 (Kind.getKind() == InitializationKind::IK_Copy &&
2923 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2924 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002925 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregor1b303932009-12-22 15:35:07 +00002926 Entity.getType(), *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002927 // - Otherwise (i.e., for the remaining copy-initialization cases),
2928 // user-defined conversion sequences that can convert from the source
2929 // type to the destination type or (when a conversion function is
2930 // used) to a derived class thereof are enumerated as described in
2931 // 13.3.1.4, and the best one is chosen through overload resolution
2932 // (13.3).
2933 else
2934 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2935 return;
2936 }
2937
Douglas Gregor85dabae2009-12-16 01:38:02 +00002938 if (NumArgs > 1) {
2939 SetFailed(FK_TooManyInitsForScalar);
2940 return;
2941 }
2942 assert(NumArgs == 1 && "Zero-argument case handled above");
2943
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002944 // - Otherwise, if the source type is a (possibly cv-qualified) class
2945 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002946 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002947 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2948 return;
2949 }
2950
2951 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00002952 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002953 // conversions (Clause 4) will be used, if necessary, to convert the
2954 // initializer expression to the cv-unqualified version of the
2955 // destination type; no user-defined conversions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002956 setSequenceKind(StandardConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002957 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
2958}
2959
2960InitializationSequence::~InitializationSequence() {
2961 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
2962 StepEnd = Steps.end();
2963 Step != StepEnd; ++Step)
2964 Step->Destroy();
2965}
2966
2967//===----------------------------------------------------------------------===//
2968// Perform initialization
2969//===----------------------------------------------------------------------===//
Douglas Gregore1314a62009-12-18 05:02:21 +00002970static Sema::AssignmentAction
2971getAssignmentAction(const InitializedEntity &Entity) {
2972 switch(Entity.getKind()) {
2973 case InitializedEntity::EK_Variable:
2974 case InitializedEntity::EK_New:
2975 return Sema::AA_Initializing;
2976
2977 case InitializedEntity::EK_Parameter:
2978 // FIXME: Can we tell when we're sending vs. passing?
2979 return Sema::AA_Passing;
2980
2981 case InitializedEntity::EK_Result:
2982 return Sema::AA_Returning;
2983
2984 case InitializedEntity::EK_Exception:
2985 case InitializedEntity::EK_Base:
2986 llvm_unreachable("No assignment action for C++-specific initialization");
2987 break;
2988
2989 case InitializedEntity::EK_Temporary:
2990 // FIXME: Can we tell apart casting vs. converting?
2991 return Sema::AA_Casting;
2992
2993 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002994 case InitializedEntity::EK_ArrayElement:
2995 case InitializedEntity::EK_VectorElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00002996 return Sema::AA_Initializing;
2997 }
2998
2999 return Sema::AA_Converting;
3000}
3001
3002static bool shouldBindAsTemporary(const InitializedEntity &Entity,
3003 bool IsCopy) {
3004 switch (Entity.getKind()) {
3005 case InitializedEntity::EK_Result:
3006 case InitializedEntity::EK_Exception:
3007 return !IsCopy;
3008
3009 case InitializedEntity::EK_New:
3010 case InitializedEntity::EK_Variable:
3011 case InitializedEntity::EK_Base:
3012 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003013 case InitializedEntity::EK_ArrayElement:
3014 case InitializedEntity::EK_VectorElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003015 return false;
3016
3017 case InitializedEntity::EK_Parameter:
3018 case InitializedEntity::EK_Temporary:
3019 return true;
3020 }
3021
3022 llvm_unreachable("missed an InitializedEntity kind?");
3023}
3024
3025/// \brief If we need to perform an additional copy of the initialized object
3026/// for this kind of entity (e.g., the result of a function or an object being
3027/// thrown), make the copy.
3028static Sema::OwningExprResult CopyIfRequiredForEntity(Sema &S,
3029 const InitializedEntity &Entity,
Douglas Gregora4b592a2009-12-19 03:01:41 +00003030 const InitializationKind &Kind,
Douglas Gregore1314a62009-12-18 05:02:21 +00003031 Sema::OwningExprResult CurInit) {
3032 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003033
3034 switch (Entity.getKind()) {
3035 case InitializedEntity::EK_Result:
Douglas Gregor1b303932009-12-22 15:35:07 +00003036 if (Entity.getType()->isReferenceType())
Douglas Gregore1314a62009-12-18 05:02:21 +00003037 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003038 Loc = Entity.getReturnLoc();
3039 break;
3040
3041 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003042 Loc = Entity.getThrowLoc();
3043 break;
3044
3045 case InitializedEntity::EK_Variable:
Douglas Gregor1b303932009-12-22 15:35:07 +00003046 if (Entity.getType()->isReferenceType() ||
Douglas Gregora4b592a2009-12-19 03:01:41 +00003047 Kind.getKind() != InitializationKind::IK_Copy)
3048 return move(CurInit);
3049 Loc = Entity.getDecl()->getLocation();
3050 break;
3051
Douglas Gregore1314a62009-12-18 05:02:21 +00003052 case InitializedEntity::EK_Parameter:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003053 // FIXME: Do we need this initialization for a parameter?
3054 return move(CurInit);
3055
Douglas Gregore1314a62009-12-18 05:02:21 +00003056 case InitializedEntity::EK_New:
3057 case InitializedEntity::EK_Temporary:
3058 case InitializedEntity::EK_Base:
3059 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003060 case InitializedEntity::EK_ArrayElement:
3061 case InitializedEntity::EK_VectorElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003062 // We don't need to copy for any of these initialized entities.
3063 return move(CurInit);
3064 }
3065
3066 Expr *CurInitExpr = (Expr *)CurInit.get();
3067 CXXRecordDecl *Class = 0;
3068 if (const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>())
3069 Class = cast<CXXRecordDecl>(Record->getDecl());
3070 if (!Class)
3071 return move(CurInit);
3072
3073 // Perform overload resolution using the class's copy constructors.
3074 DeclarationName ConstructorName
3075 = S.Context.DeclarationNames.getCXXConstructorName(
3076 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
3077 DeclContext::lookup_iterator Con, ConEnd;
3078 OverloadCandidateSet CandidateSet;
3079 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
3080 Con != ConEnd; ++Con) {
3081 // Find the constructor (which may be a template).
3082 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3083 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor507eb872009-12-22 00:34:07 +00003084 !Constructor->isCopyConstructor())
Douglas Gregore1314a62009-12-18 05:02:21 +00003085 continue;
3086
3087 S.AddOverloadCandidate(Constructor, &CurInitExpr, 1, CandidateSet);
3088 }
3089
3090 OverloadCandidateSet::iterator Best;
3091 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3092 case OR_Success:
3093 break;
3094
3095 case OR_No_Viable_Function:
3096 S.Diag(Loc, diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003097 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003098 << CurInitExpr->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003099 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
3100 &CurInitExpr, 1);
Douglas Gregore1314a62009-12-18 05:02:21 +00003101 return S.ExprError();
3102
3103 case OR_Ambiguous:
3104 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003105 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003106 << CurInitExpr->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003107 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_ViableCandidates,
3108 &CurInitExpr, 1);
Douglas Gregore1314a62009-12-18 05:02:21 +00003109 return S.ExprError();
3110
3111 case OR_Deleted:
3112 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003113 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003114 << CurInitExpr->getSourceRange();
3115 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3116 << Best->Function->isDeleted();
3117 return S.ExprError();
3118 }
3119
3120 CurInit.release();
3121 return S.BuildCXXConstructExpr(Loc, CurInitExpr->getType(),
3122 cast<CXXConstructorDecl>(Best->Function),
3123 /*Elidable=*/true,
3124 Sema::MultiExprArg(S,
3125 (void**)&CurInitExpr, 1));
3126}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003127
3128Action::OwningExprResult
3129InitializationSequence::Perform(Sema &S,
3130 const InitializedEntity &Entity,
3131 const InitializationKind &Kind,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003132 Action::MultiExprArg Args,
3133 QualType *ResultType) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003134 if (SequenceKind == FailedSequence) {
3135 unsigned NumArgs = Args.size();
3136 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3137 return S.ExprError();
3138 }
3139
3140 if (SequenceKind == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003141 // If the declaration is a non-dependent, incomplete array type
3142 // that has an initializer, then its type will be completed once
3143 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00003144 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00003145 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003146 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003147 if (const IncompleteArrayType *ArrayT
3148 = S.Context.getAsIncompleteArrayType(DeclType)) {
3149 // FIXME: We don't currently have the ability to accurately
3150 // compute the length of an initializer list without
3151 // performing full type-checking of the initializer list
3152 // (since we have to determine where braces are implicitly
3153 // introduced and such). So, we fall back to making the array
3154 // type a dependently-sized array type with no specified
3155 // bound.
3156 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3157 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00003158
Douglas Gregor51e77d52009-12-10 17:56:55 +00003159 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00003160 if (DeclaratorDecl *DD = Entity.getDecl()) {
3161 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3162 TypeLoc TL = TInfo->getTypeLoc();
3163 if (IncompleteArrayTypeLoc *ArrayLoc
3164 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3165 Brackets = ArrayLoc->getBracketsRange();
3166 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00003167 }
3168
3169 *ResultType
3170 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3171 /*NumElts=*/0,
3172 ArrayT->getSizeModifier(),
3173 ArrayT->getIndexTypeCVRQualifiers(),
3174 Brackets);
3175 }
3176
3177 }
3178 }
3179
Eli Friedmana553d4a2009-12-22 02:35:53 +00003180 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003181 return Sema::OwningExprResult(S, Args.release()[0]);
3182
3183 unsigned NumArgs = Args.size();
3184 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3185 SourceLocation(),
3186 (Expr **)Args.release(),
3187 NumArgs,
3188 SourceLocation()));
3189 }
3190
Douglas Gregor85dabae2009-12-16 01:38:02 +00003191 if (SequenceKind == NoInitialization)
3192 return S.Owned((Expr *)0);
3193
Douglas Gregor1b303932009-12-22 15:35:07 +00003194 QualType DestType = Entity.getType().getNonReferenceType();
3195 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00003196 // the same as Entity.getDecl()->getType() in cases involving type merging,
3197 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003198 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003199 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00003200 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003201
Douglas Gregor85dabae2009-12-16 01:38:02 +00003202 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3203
3204 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3205
3206 // For initialization steps that start with a single initializer,
3207 // grab the only argument out the Args and place it into the "current"
3208 // initializer.
3209 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003210 case SK_ResolveAddressOfOverloadedFunction:
3211 case SK_CastDerivedToBaseRValue:
3212 case SK_CastDerivedToBaseLValue:
3213 case SK_BindReference:
3214 case SK_BindReferenceToTemporary:
3215 case SK_UserConversion:
3216 case SK_QualificationConversionLValue:
3217 case SK_QualificationConversionRValue:
3218 case SK_ConversionSequence:
3219 case SK_ListInitialization:
3220 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003221 case SK_StringInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00003222 assert(Args.size() == 1);
3223 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3224 if (CurInit.isInvalid())
3225 return S.ExprError();
3226 break;
3227
3228 case SK_ConstructorInitialization:
3229 case SK_ZeroInitialization:
3230 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003231 }
3232
3233 // Walk through the computed steps for the initialization sequence,
3234 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003235 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003236 for (step_iterator Step = step_begin(), StepEnd = step_end();
3237 Step != StepEnd; ++Step) {
3238 if (CurInit.isInvalid())
3239 return S.ExprError();
3240
3241 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003242 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003243
3244 switch (Step->Kind) {
3245 case SK_ResolveAddressOfOverloadedFunction:
3246 // Overload resolution determined which function invoke; update the
3247 // initializer to reflect that choice.
3248 CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function);
3249 break;
3250
3251 case SK_CastDerivedToBaseRValue:
3252 case SK_CastDerivedToBaseLValue: {
3253 // We have a derived-to-base cast that produces either an rvalue or an
3254 // lvalue. Perform that cast.
3255
3256 // Casts to inaccessible base classes are allowed with C-style casts.
3257 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3258 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3259 CurInitExpr->getLocStart(),
3260 CurInitExpr->getSourceRange(),
3261 IgnoreBaseAccess))
3262 return S.ExprError();
3263
3264 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3265 CastExpr::CK_DerivedToBase,
3266 (Expr*)CurInit.release(),
3267 Step->Kind == SK_CastDerivedToBaseLValue));
3268 break;
3269 }
3270
3271 case SK_BindReference:
3272 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3273 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3274 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00003275 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003276 << BitField->getDeclName()
3277 << CurInitExpr->getSourceRange();
3278 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3279 return S.ExprError();
3280 }
3281
3282 // Reference binding does not have any corresponding ASTs.
3283
3284 // Check exception specifications
3285 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3286 return S.ExprError();
3287 break;
3288
3289 case SK_BindReferenceToTemporary:
3290 // Check exception specifications
3291 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3292 return S.ExprError();
3293
3294 // FIXME: At present, we have no AST to describe when we need to make a
3295 // temporary to bind a reference to. We should.
3296 break;
3297
3298 case SK_UserConversion: {
3299 // We have a user-defined conversion that invokes either a constructor
3300 // or a conversion function.
3301 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregore1314a62009-12-18 05:02:21 +00003302 bool IsCopy = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003303 if (CXXConstructorDecl *Constructor
3304 = dyn_cast<CXXConstructorDecl>(Step->Function)) {
3305 // Build a call to the selected constructor.
3306 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3307 SourceLocation Loc = CurInitExpr->getLocStart();
3308 CurInit.release(); // Ownership transferred into MultiExprArg, below.
3309
3310 // Determine the arguments required to actually perform the constructor
3311 // call.
3312 if (S.CompleteConstructorCall(Constructor,
3313 Sema::MultiExprArg(S,
3314 (void **)&CurInitExpr,
3315 1),
3316 Loc, ConstructorArgs))
3317 return S.ExprError();
3318
3319 // Build the an expression that constructs a temporary.
3320 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3321 move_arg(ConstructorArgs));
3322 if (CurInit.isInvalid())
3323 return S.ExprError();
3324
3325 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00003326 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3327 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3328 S.IsDerivedFrom(SourceType, Class))
3329 IsCopy = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003330 } else {
3331 // Build a call to the conversion function.
3332 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function);
Douglas Gregore1314a62009-12-18 05:02:21 +00003333
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003334 // FIXME: Should we move this initialization into a separate
3335 // derived-to-base conversion? I believe the answer is "no", because
3336 // we don't want to turn off access control here for c-style casts.
3337 if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion))
3338 return S.ExprError();
3339
3340 // Do a little dance to make sure that CurInit has the proper
3341 // pointer.
3342 CurInit.release();
3343
3344 // Build the actual call to the conversion function.
3345 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3346 if (CurInit.isInvalid() || !CurInit.get())
3347 return S.ExprError();
3348
3349 CastKind = CastExpr::CK_UserDefinedConversion;
3350 }
3351
Douglas Gregore1314a62009-12-18 05:02:21 +00003352 if (shouldBindAsTemporary(Entity, IsCopy))
3353 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3354
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003355 CurInitExpr = CurInit.takeAs<Expr>();
3356 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3357 CastKind,
3358 CurInitExpr,
Douglas Gregore1314a62009-12-18 05:02:21 +00003359 false));
3360
3361 if (!IsCopy)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003362 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003363 break;
3364 }
3365
3366 case SK_QualificationConversionLValue:
3367 case SK_QualificationConversionRValue:
3368 // Perform a qualification conversion; these can never go wrong.
3369 S.ImpCastExprToType(CurInitExpr, Step->Type,
3370 CastExpr::CK_NoOp,
3371 Step->Kind == SK_QualificationConversionLValue);
3372 CurInit.release();
3373 CurInit = S.Owned(CurInitExpr);
3374 break;
3375
3376 case SK_ConversionSequence:
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003377 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003378 false, false, *Step->ICS))
3379 return S.ExprError();
3380
3381 CurInit.release();
3382 CurInit = S.Owned(CurInitExpr);
3383 break;
Douglas Gregor51e77d52009-12-10 17:56:55 +00003384
3385 case SK_ListInitialization: {
3386 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3387 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00003388 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregor51e77d52009-12-10 17:56:55 +00003389 return S.ExprError();
3390
3391 CurInit.release();
3392 CurInit = S.Owned(InitList);
3393 break;
3394 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003395
3396 case SK_ConstructorInitialization: {
3397 CXXConstructorDecl *Constructor
3398 = cast<CXXConstructorDecl>(Step->Function);
3399
3400 // Build a call to the selected constructor.
3401 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3402 SourceLocation Loc = Kind.getLocation();
3403
3404 // Determine the arguments required to actually perform the constructor
3405 // call.
3406 if (S.CompleteConstructorCall(Constructor, move(Args),
3407 Loc, ConstructorArgs))
3408 return S.ExprError();
3409
3410 // Build the an expression that constructs a temporary.
Douglas Gregor1b303932009-12-22 15:35:07 +00003411 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
Douglas Gregor39c778b2009-12-20 22:01:25 +00003412 Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003413 move_arg(ConstructorArgs),
3414 ConstructorInitRequiresZeroInit);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003415 if (CurInit.isInvalid())
3416 return S.ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003417
3418 bool Elidable
3419 = cast<CXXConstructExpr>((Expr *)CurInit.get())->isElidable();
3420 if (shouldBindAsTemporary(Entity, Elidable))
3421 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3422
3423 if (!Elidable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003424 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003425 break;
3426 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003427
3428 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003429 step_iterator NextStep = Step;
3430 ++NextStep;
3431 if (NextStep != StepEnd &&
3432 NextStep->Kind == SK_ConstructorInitialization) {
3433 // The need for zero-initialization is recorded directly into
3434 // the call to the object's constructor within the next step.
3435 ConstructorInitRequiresZeroInit = true;
3436 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3437 S.getLangOptions().CPlusPlus &&
3438 !Kind.isImplicitValueInit()) {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003439 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3440 Kind.getRange().getBegin(),
3441 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003442 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003443 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003444 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003445 break;
3446 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003447
3448 case SK_CAssignment: {
3449 QualType SourceType = CurInitExpr->getType();
3450 Sema::AssignConvertType ConvTy =
3451 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregor96596c92009-12-22 07:24:36 +00003452
3453 // If this is a call, allow conversion to a transparent union.
3454 if (ConvTy != Sema::Compatible &&
3455 Entity.getKind() == InitializedEntity::EK_Parameter &&
3456 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3457 == Sema::Compatible)
3458 ConvTy = Sema::Compatible;
3459
Douglas Gregore1314a62009-12-18 05:02:21 +00003460 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3461 Step->Type, SourceType,
3462 CurInitExpr, getAssignmentAction(Entity)))
3463 return S.ExprError();
3464
3465 CurInit.release();
3466 CurInit = S.Owned(CurInitExpr);
3467 break;
3468 }
Eli Friedman78275202009-12-19 08:11:05 +00003469
3470 case SK_StringInit: {
3471 QualType Ty = Step->Type;
3472 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3473 break;
3474 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003475 }
3476 }
3477
3478 return move(CurInit);
3479}
3480
3481//===----------------------------------------------------------------------===//
3482// Diagnose initialization failures
3483//===----------------------------------------------------------------------===//
3484bool InitializationSequence::Diagnose(Sema &S,
3485 const InitializedEntity &Entity,
3486 const InitializationKind &Kind,
3487 Expr **Args, unsigned NumArgs) {
3488 if (SequenceKind != FailedSequence)
3489 return false;
3490
Douglas Gregor1b303932009-12-22 15:35:07 +00003491 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003492 switch (Failure) {
3493 case FK_TooManyInitsForReference:
3494 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3495 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
3496 break;
3497
3498 case FK_ArrayNeedsInitList:
3499 case FK_ArrayNeedsInitListOrStringLiteral:
3500 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3501 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3502 break;
3503
3504 case FK_AddressOfOverloadFailed:
3505 S.ResolveAddressOfOverloadedFunction(Args[0],
3506 DestType.getNonReferenceType(),
3507 true);
3508 break;
3509
3510 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00003511 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003512 switch (FailedOverloadResult) {
3513 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00003514 if (Failure == FK_UserConversionOverloadFailed)
3515 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3516 << Args[0]->getType() << DestType
3517 << Args[0]->getSourceRange();
3518 else
3519 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3520 << DestType << Args[0]->getType()
3521 << Args[0]->getSourceRange();
3522
John McCallad907772010-01-12 07:18:19 +00003523 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_ViableCandidates,
3524 Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003525 break;
3526
3527 case OR_No_Viable_Function:
3528 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3529 << Args[0]->getType() << DestType.getNonReferenceType()
3530 << Args[0]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003531 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3532 Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003533 break;
3534
3535 case OR_Deleted: {
3536 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3537 << Args[0]->getType() << DestType.getNonReferenceType()
3538 << Args[0]->getSourceRange();
3539 OverloadCandidateSet::iterator Best;
3540 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3541 Kind.getLocation(),
3542 Best);
3543 if (Ovl == OR_Deleted) {
3544 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3545 << Best->Function->isDeleted();
3546 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003547 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003548 }
3549 break;
3550 }
3551
3552 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003553 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003554 break;
3555 }
3556 break;
3557
3558 case FK_NonConstLValueReferenceBindingToTemporary:
3559 case FK_NonConstLValueReferenceBindingToUnrelated:
3560 S.Diag(Kind.getLocation(),
3561 Failure == FK_NonConstLValueReferenceBindingToTemporary
3562 ? diag::err_lvalue_reference_bind_to_temporary
3563 : diag::err_lvalue_reference_bind_to_unrelated)
3564 << DestType.getNonReferenceType()
3565 << Args[0]->getType()
3566 << Args[0]->getSourceRange();
3567 break;
3568
3569 case FK_RValueReferenceBindingToLValue:
3570 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3571 << Args[0]->getSourceRange();
3572 break;
3573
3574 case FK_ReferenceInitDropsQualifiers:
3575 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3576 << DestType.getNonReferenceType()
3577 << Args[0]->getType()
3578 << Args[0]->getSourceRange();
3579 break;
3580
3581 case FK_ReferenceInitFailed:
3582 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3583 << DestType.getNonReferenceType()
3584 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3585 << Args[0]->getType()
3586 << Args[0]->getSourceRange();
3587 break;
3588
3589 case FK_ConversionFailed:
Douglas Gregore1314a62009-12-18 05:02:21 +00003590 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
3591 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003592 << DestType
3593 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3594 << Args[0]->getType()
3595 << Args[0]->getSourceRange();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003596 break;
3597
3598 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003599 SourceRange R;
3600
3601 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3602 R = SourceRange(InitList->getInit(1)->getLocStart(),
3603 InitList->getLocEnd());
3604 else
3605 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00003606
3607 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor85dabae2009-12-16 01:38:02 +00003608 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00003609 break;
3610 }
3611
3612 case FK_ReferenceBindingToInitList:
3613 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3614 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3615 break;
3616
3617 case FK_InitListBadDestinationType:
3618 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3619 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3620 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003621
3622 case FK_ConstructorOverloadFailed: {
3623 SourceRange ArgsRange;
3624 if (NumArgs)
3625 ArgsRange = SourceRange(Args[0]->getLocStart(),
3626 Args[NumArgs - 1]->getLocEnd());
3627
3628 // FIXME: Using "DestType" for the entity we're printing is probably
3629 // bad.
3630 switch (FailedOverloadResult) {
3631 case OR_Ambiguous:
3632 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3633 << DestType << ArgsRange;
John McCall12f97bc2010-01-08 04:41:39 +00003634 S.PrintOverloadCandidates(FailedCandidateSet,
John McCallad907772010-01-12 07:18:19 +00003635 Sema::OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003636 break;
3637
3638 case OR_No_Viable_Function:
3639 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3640 << DestType << ArgsRange;
John McCallad907772010-01-12 07:18:19 +00003641 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3642 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003643 break;
3644
3645 case OR_Deleted: {
3646 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3647 << true << DestType << ArgsRange;
3648 OverloadCandidateSet::iterator Best;
3649 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3650 Kind.getLocation(),
3651 Best);
3652 if (Ovl == OR_Deleted) {
3653 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3654 << Best->Function->isDeleted();
3655 } else {
3656 llvm_unreachable("Inconsistent overload resolution?");
3657 }
3658 break;
3659 }
3660
3661 case OR_Success:
3662 llvm_unreachable("Conversion did not fail!");
3663 break;
3664 }
3665 break;
3666 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003667
3668 case FK_DefaultInitOfConst:
3669 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3670 << DestType;
3671 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003672 }
3673
3674 return true;
3675}
Douglas Gregore1314a62009-12-18 05:02:21 +00003676
3677//===----------------------------------------------------------------------===//
3678// Initialization helper functions
3679//===----------------------------------------------------------------------===//
3680Sema::OwningExprResult
3681Sema::PerformCopyInitialization(const InitializedEntity &Entity,
3682 SourceLocation EqualLoc,
3683 OwningExprResult Init) {
3684 if (Init.isInvalid())
3685 return ExprError();
3686
3687 Expr *InitE = (Expr *)Init.get();
3688 assert(InitE && "No initialization expression?");
3689
3690 if (EqualLoc.isInvalid())
3691 EqualLoc = InitE->getLocStart();
3692
3693 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
3694 EqualLoc);
3695 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
3696 Init.release();
3697 return Seq.Perform(*this, Entity, Kind,
3698 MultiExprArg(*this, (void**)&InitE, 1));
3699}