blob: 307db14b58824f70e0a68ae5e69341ad77464406 [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//
Steve Narofff8ecff22008-05-01 22:18:59 +000014//===----------------------------------------------------------------------===//
15
John McCall8b0666c2010-08-20 18:27:03 +000016#include "clang/Sema/Designator.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
John McCall83024632010-08-25 22:03:47 +000019#include "clang/Sema/SemaInternal.h"
Tanya Lattner5029d562010-03-07 04:17:15 +000020#include "clang/Lex/Preprocessor.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000021#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.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
John McCall66884dd2011-02-21 07:22:22 +000034static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
35 ASTContext &Context) {
Eli Friedman893abe42009-05-29 18:22:49 +000036 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
37 return 0;
38
Chris Lattnera9196812009-02-26 23:26:43 +000039 // See if this is a string literal or @encode.
40 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000041
Chris Lattnera9196812009-02-26 23:26:43 +000042 // Handle @encode, which is a narrow string.
43 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
44 return Init;
45
46 // Otherwise we can only handle string literals.
47 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000048 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000049
50 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattnera9196812009-02-26 23:26:43 +000051 // char array can be initialized with a narrow string.
52 // Only allow char x[] = "foo"; not char x[] = L"foo";
53 if (!SL->isWide())
Eli Friedman42a84652009-05-31 10:54:53 +000054 return ElemTy->isCharType() ? Init : 0;
Chris Lattnera9196812009-02-26 23:26:43 +000055
Eli Friedman42a84652009-05-31 10:54:53 +000056 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
57 // correction from DR343): "An array with element type compatible with a
58 // qualified or unqualified version of wchar_t may be initialized by a wide
59 // string literal, optionally enclosed in braces."
60 if (Context.typesAreCompatible(Context.getWCharType(),
61 ElemTy.getUnqualifiedType()))
Chris Lattnera9196812009-02-26 23:26:43 +000062 return Init;
Mike Stump11289f42009-09-09 15:08:12 +000063
Chris Lattner0cb78032009-02-24 22:27:37 +000064 return 0;
65}
66
John McCall66884dd2011-02-21 07:22:22 +000067static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
68 const ArrayType *arrayType = Context.getAsArrayType(declType);
69 if (!arrayType) return 0;
70
71 return IsStringInit(init, arrayType, Context);
72}
73
John McCall5decec92011-02-21 07:57:55 +000074static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
75 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +000076 // Get the length of the string as parsed.
77 uint64_t StrLength =
78 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
79
Mike Stump11289f42009-09-09 15:08:12 +000080
Chris Lattner0cb78032009-02-24 22:27:37 +000081 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +000082 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +000083 // being initialized to a string literal.
84 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000085 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +000086 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +000087 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
88 ConstVal,
89 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000090 return;
Chris Lattner0cb78032009-02-24 22:27:37 +000091 }
Mike Stump11289f42009-09-09 15:08:12 +000092
Eli Friedman893abe42009-05-29 18:22:49 +000093 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +000094
Eli Friedman554eba92011-04-11 00:23:45 +000095 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +000096 // the size may be smaller or larger than the string we are initializing.
97 // FIXME: Avoid truncation for 64-bit length strings.
Eli Friedman554eba92011-04-11 00:23:45 +000098 if (S.getLangOptions().CPlusPlus) {
Anders Carlssond162fb82011-04-14 00:41:11 +000099 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
100 // For Pascal strings it's OK to strip off the terminating null character,
101 // so the example below is valid:
102 //
103 // unsigned char a[2] = "\pa";
104 if (SL->isPascal())
105 StrLength--;
106 }
107
Eli Friedman554eba92011-04-11 00:23:45 +0000108 // [dcl.init.string]p2
109 if (StrLength > CAT->getSize().getZExtValue())
110 S.Diag(Str->getSourceRange().getBegin(),
111 diag::err_initializer_string_for_char_array_too_long)
112 << Str->getSourceRange();
113 } else {
114 // C99 6.7.8p14.
115 if (StrLength-1 > CAT->getSize().getZExtValue())
116 S.Diag(Str->getSourceRange().getBegin(),
117 diag::warn_initializer_string_for_char_array_too_long)
118 << Str->getSourceRange();
119 }
Mike Stump11289f42009-09-09 15:08:12 +0000120
Eli Friedman893abe42009-05-29 18:22:49 +0000121 // Set the type to the actual size that we are initializing. If we have
122 // something like:
123 // char x[1] = "foo";
124 // then this will set the string literal's type to char[1].
125 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000126}
127
Chris Lattner0cb78032009-02-24 22:27:37 +0000128//===----------------------------------------------------------------------===//
129// Semantic checking for initializer lists.
130//===----------------------------------------------------------------------===//
131
Douglas Gregorcde232f2009-01-29 01:05:33 +0000132/// @brief Semantic checking for initializer lists.
133///
134/// The InitListChecker class contains a set of routines that each
135/// handle the initialization of a certain kind of entity, e.g.,
136/// arrays, vectors, struct/union types, scalars, etc. The
137/// InitListChecker itself performs a recursive walk of the subobject
138/// structure of the type to be initialized, while stepping through
139/// the initializer list one element at a time. The IList and Index
140/// parameters to each of the Check* routines contain the active
141/// (syntactic) initializer list and the index into that initializer
142/// list that represents the current initializer. Each routine is
143/// responsible for moving that Index forward as it consumes elements.
144///
145/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000146/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000147/// initializer list and the index into that initializer list where we
148/// are copying initializers as we map them over to the semantic
149/// list. Once we have completed our recursive walk of the subobject
150/// structure, we will have constructed a full semantic initializer
151/// list.
152///
153/// C99 designators cause changes in the initializer list traversal,
154/// because they make the initialization "jump" into a specific
155/// subobject and then continue the initialization from that
156/// point. CheckDesignatedInitializer() recursively steps into the
157/// designated subobject and manages backing out the recursion to
158/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000159namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000160class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000161 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000162 bool hadError;
163 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
164 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000165
Anders Carlsson6cabf312010-01-23 23:23:01 +0000166 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000167 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000168 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000169 unsigned &StructuredIndex,
170 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000171 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000172 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000173 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000174 unsigned &StructuredIndex,
175 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000176 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000177 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000178 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000179 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000180 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000181 unsigned &StructuredIndex,
182 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000183 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000184 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000185 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000186 InitListExpr *StructuredList,
187 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000188 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000189 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000190 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000191 InitListExpr *StructuredList,
192 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000193 void CheckReferenceType(const InitializedEntity &Entity,
194 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000195 unsigned &Index,
196 InitListExpr *StructuredList,
197 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000198 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000199 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000200 InitListExpr *StructuredList,
201 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000202 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000203 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000204 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000205 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000206 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000207 unsigned &StructuredIndex,
208 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000209 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000210 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000211 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000212 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000213 InitListExpr *StructuredList,
214 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000215 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000216 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000217 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000218 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000219 RecordDecl::field_iterator *NextField,
220 llvm::APSInt *NextElementIndex,
221 unsigned &Index,
222 InitListExpr *StructuredList,
223 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000224 bool FinishSubobjectInit,
225 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000226 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
227 QualType CurrentObjectType,
228 InitListExpr *StructuredList,
229 unsigned StructuredIndex,
230 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000231 void UpdateStructuredListElement(InitListExpr *StructuredList,
232 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000233 Expr *expr);
234 int numArrayElements(QualType DeclType);
235 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000236
Douglas Gregor2bb07652009-12-22 00:05:34 +0000237 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
238 const InitializedEntity &ParentEntity,
239 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000240 void FillInValueInitializations(const InitializedEntity &Entity,
241 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000242public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000243 InitListChecker(Sema &S, const InitializedEntity &Entity,
244 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000245 bool HadError() { return hadError; }
246
247 // @brief Retrieves the fully-structured initializer list used for
248 // semantic analysis and code generation.
249 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
250};
Chris Lattner9ececce2009-02-24 22:48:58 +0000251} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000252
Douglas Gregor2bb07652009-12-22 00:05:34 +0000253void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
254 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000255 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000256 bool &RequiresSecondPass) {
257 SourceLocation Loc = ILE->getSourceRange().getBegin();
258 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000259 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000260 = InitializedEntity::InitializeMember(Field, &ParentEntity);
261 if (Init >= NumInits || !ILE->getInit(Init)) {
262 // FIXME: We probably don't need to handle references
263 // specially here, since value-initialization of references is
264 // handled in InitializationSequence.
265 if (Field->getType()->isReferenceType()) {
266 // C++ [dcl.init.aggr]p9:
267 // If an incomplete or empty initializer-list leaves a
268 // member of reference type uninitialized, the program is
269 // ill-formed.
270 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
271 << Field->getType()
272 << ILE->getSyntacticForm()->getSourceRange();
273 SemaRef.Diag(Field->getLocation(),
274 diag::note_uninit_reference_member);
275 hadError = true;
276 return;
277 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000278
Douglas Gregor2bb07652009-12-22 00:05:34 +0000279 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
280 true);
281 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
282 if (!InitSeq) {
283 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
284 hadError = true;
285 return;
286 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000287
John McCalldadc5752010-08-24 06:29:42 +0000288 ExprResult MemberInit
John McCallfaf5fb42010-08-26 23:41:50 +0000289 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000290 if (MemberInit.isInvalid()) {
291 hadError = true;
292 return;
293 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000294
Douglas Gregor2bb07652009-12-22 00:05:34 +0000295 if (hadError) {
296 // Do nothing
297 } else if (Init < NumInits) {
298 ILE->setInit(Init, MemberInit.takeAs<Expr>());
299 } else if (InitSeq.getKind()
300 == InitializationSequence::ConstructorInitialization) {
301 // Value-initialization requires a constructor call, so
302 // extend the initializer list to include the constructor
303 // call and make a note that we'll need to take another pass
304 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000305 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000306 RequiresSecondPass = true;
307 }
308 } else if (InitListExpr *InnerILE
309 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000310 FillInValueInitializations(MemberEntity, InnerILE,
311 RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000312}
313
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000314/// Recursively replaces NULL values within the given initializer list
315/// with expressions that perform value-initialization of the
316/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000317void
Douglas Gregor723796a2009-12-16 06:35:08 +0000318InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
319 InitListExpr *ILE,
320 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000321 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000322 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000323 SourceLocation Loc = ILE->getSourceRange().getBegin();
324 if (ILE->getSyntacticForm())
325 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000326
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000327 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000328 if (RType->getDecl()->isUnion() &&
329 ILE->getInitializedFieldInUnion())
330 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
331 Entity, ILE, RequiresSecondPass);
332 else {
333 unsigned Init = 0;
334 for (RecordDecl::field_iterator
335 Field = RType->getDecl()->field_begin(),
336 FieldEnd = RType->getDecl()->field_end();
337 Field != FieldEnd; ++Field) {
338 if (Field->isUnnamedBitfield())
339 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000340
Douglas Gregor2bb07652009-12-22 00:05:34 +0000341 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000342 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000343
344 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
345 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000346 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000347
Douglas Gregor2bb07652009-12-22 00:05:34 +0000348 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000349
Douglas Gregor2bb07652009-12-22 00:05:34 +0000350 // Only look at the first initialization of a union.
351 if (RType->getDecl()->isUnion())
352 break;
353 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000354 }
355
356 return;
Mike Stump11289f42009-09-09 15:08:12 +0000357 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000358
359 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000360
Douglas Gregor723796a2009-12-16 06:35:08 +0000361 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000362 unsigned NumInits = ILE->getNumInits();
363 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000364 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000365 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000366 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
367 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000368 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000369 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000370 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000371 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000372 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000373 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000374 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000375 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000376 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000377
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000378
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000379 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000380 if (hadError)
381 return;
382
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000383 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
384 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000385 ElementEntity.setElementIndex(Init);
386
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000387 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000388 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
389 true);
390 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
391 if (!InitSeq) {
392 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000393 hadError = true;
394 return;
395 }
396
John McCalldadc5752010-08-24 06:29:42 +0000397 ExprResult ElementInit
John McCallfaf5fb42010-08-26 23:41:50 +0000398 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregor723796a2009-12-16 06:35:08 +0000399 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000400 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000401 return;
402 }
403
404 if (hadError) {
405 // Do nothing
406 } else if (Init < NumInits) {
407 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000408 } else {
409 // For arrays, just set the expression used for value-initialization
410 // of the rest of elements and exit.
411 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
412 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
413 return;
414 }
415
416 if (InitSeq.getKind()
Douglas Gregor723796a2009-12-16 06:35:08 +0000417 == InitializationSequence::ConstructorInitialization) {
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000418 // Value-initialization requires a constructor call, so
419 // extend the initializer list to include the constructor
420 // call and make a note that we'll need to take another pass
421 // through the initializer list.
422 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
423 RequiresSecondPass = true;
424 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000425 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000426 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000427 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
428 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000429 }
430}
431
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000432
Douglas Gregor723796a2009-12-16 06:35:08 +0000433InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
434 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000435 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000436 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000437
Eli Friedman23a9e312008-05-19 19:16:24 +0000438 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000439 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000440 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000441 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000442 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000443 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000444 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000445
Douglas Gregor723796a2009-12-16 06:35:08 +0000446 if (!hadError) {
447 bool RequiresSecondPass = false;
448 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000449 if (RequiresSecondPass && !hadError)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000450 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000451 RequiresSecondPass);
452 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000453}
454
455int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000456 // FIXME: use a proper constant
457 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000458 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000459 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000460 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
461 }
462 return maxElements;
463}
464
465int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000466 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000467 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000468 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000469 Field = structDecl->field_begin(),
470 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000471 Field != FieldEnd; ++Field) {
472 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
473 ++InitializableMembers;
474 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000475 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000476 return std::min(InitializableMembers, 1);
477 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000478}
479
Anders Carlsson6cabf312010-01-23 23:23:01 +0000480void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000481 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000482 QualType T, unsigned &Index,
483 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000484 unsigned &StructuredIndex,
485 bool TopLevelObject) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000486 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000487
Steve Narofff8ecff22008-05-01 22:18:59 +0000488 if (T->isArrayType())
489 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000490 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000491 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000492 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000493 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000494 else
495 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000496
Eli Friedmane0f832b2008-05-25 13:49:22 +0000497 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000498 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000499 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000500 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000501 hadError = true;
502 return;
503 }
504
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000505 // Build a structured initializer list corresponding to this subobject.
506 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000507 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
508 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000509 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
510 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000511 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000512
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000513 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000514 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000515 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000516 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000517 StructuredSubobjectInitList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000518 StructuredSubobjectInitIndex,
519 TopLevelObject);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000520 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000521 StructuredSubobjectInitList->setType(T);
522
Douglas Gregor5741efb2009-03-01 17:12:46 +0000523 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000524 // range corresponds with the end of the last initializer it used.
525 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000526 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000527 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
528 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
529 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000530
Tanya Lattner5029d562010-03-07 04:17:15 +0000531 // Warn about missing braces.
532 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner5cbff482010-03-07 04:40:06 +0000533 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
534 diag::warn_missing_braces)
Tanya Lattner5029d562010-03-07 04:17:15 +0000535 << StructuredSubobjectInitList->getSourceRange()
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000536 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
Douglas Gregora771f462010-03-31 17:46:05 +0000537 "{")
538 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000539 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregora771f462010-03-31 17:46:05 +0000540 "}");
Tanya Lattner5029d562010-03-07 04:17:15 +0000541 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000542}
543
Anders Carlsson6cabf312010-01-23 23:23:01 +0000544void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000545 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000546 unsigned &Index,
547 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000548 unsigned &StructuredIndex,
549 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000550 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000551 SyntacticToSemantic[IList] = StructuredList;
552 StructuredList->setSyntacticForm(IList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000553 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000554 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregora8a089b2010-07-13 18:40:04 +0000555 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
556 IList->setType(ExprTy);
557 StructuredList->setType(ExprTy);
Eli Friedman85f54972008-05-25 13:22:35 +0000558 if (hadError)
559 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000560
Eli Friedman85f54972008-05-25 13:22:35 +0000561 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000562 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000563 if (StructuredIndex == 1 &&
564 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000565 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000566 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000567 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000568 hadError = true;
569 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000570 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000571 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000572 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000573 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000574 // Don't complain for incomplete types, since we'll get an error
575 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000576 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000577 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000578 CurrentObjectType->isArrayType()? 0 :
579 CurrentObjectType->isVectorType()? 1 :
580 CurrentObjectType->isScalarType()? 2 :
581 CurrentObjectType->isUnionType()? 3 :
582 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000583
584 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000585 if (SemaRef.getLangOptions().CPlusPlus) {
586 DK = diag::err_excess_initializers;
587 hadError = true;
588 }
Nate Begeman425038c2009-07-07 21:53:06 +0000589 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
590 DK = diag::err_excess_initializers;
591 hadError = true;
592 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000593
Chris Lattnerb0912a52009-02-24 22:50:46 +0000594 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000595 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000596 }
597 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000598
Eli Friedman0b4af8f2009-05-16 11:45:48 +0000599 if (T->isScalarType() && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000600 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000601 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000602 << FixItHint::CreateRemoval(IList->getLocStart())
603 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000604}
605
Anders Carlsson6cabf312010-01-23 23:23:01 +0000606void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000607 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000608 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000609 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000610 unsigned &Index,
611 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000612 unsigned &StructuredIndex,
613 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000614 if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000615 CheckScalarType(Entity, IList, DeclType, Index,
616 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000617 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000618 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000619 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000620 } else if (DeclType->isAggregateType()) {
621 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000622 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000623 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000624 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000625 StructuredList, StructuredIndex,
626 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000627 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000628 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000629 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000630 false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000631 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000632 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000633 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000634 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000635 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000636 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
637 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000638 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000639 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000640 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000641 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000642 } else if (DeclType->isRecordType()) {
643 // C++ [dcl.init]p14:
644 // [...] If the class is an aggregate (8.5.1), and the initializer
645 // is a brace-enclosed list, see 8.5.1.
646 //
647 // Note: 8.5.1 is handled below; here, we diagnose the case where
648 // we have an initializer list and a destination type that is not
649 // an aggregate.
650 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000651 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000652 << DeclType << IList->getSourceRange();
653 hadError = true;
654 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000655 CheckReferenceType(Entity, IList, DeclType, Index,
656 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000657 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000658 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
659 << DeclType;
660 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000661 } else {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000662 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
663 << DeclType;
664 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000665 }
666}
667
Anders Carlsson6cabf312010-01-23 23:23:01 +0000668void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000669 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000670 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000671 unsigned &Index,
672 InitListExpr *StructuredList,
673 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000674 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000675 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
676 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000677 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000678 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000679 = getStructuredSubobjectInit(IList, Index, ElemType,
680 StructuredList, StructuredIndex,
681 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000682 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000683 newStructuredList, newStructuredIndex);
684 ++StructuredIndex;
685 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000686 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000687 } else if (ElemType->isScalarType()) {
John McCall5decec92011-02-21 07:57:55 +0000688 return CheckScalarType(Entity, IList, ElemType, Index,
689 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000690 } else if (ElemType->isReferenceType()) {
John McCall5decec92011-02-21 07:57:55 +0000691 return CheckReferenceType(Entity, IList, ElemType, Index,
692 StructuredList, StructuredIndex);
693 }
Anders Carlsson03068aa2009-08-27 17:18:13 +0000694
John McCall5decec92011-02-21 07:57:55 +0000695 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
696 // arrayType can be incomplete if we're initializing a flexible
697 // array member. There's nothing we can do with the completed
698 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000699
John McCall5decec92011-02-21 07:57:55 +0000700 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
701 CheckStringInit(Str, ElemType, arrayType, SemaRef);
702 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregord14247a2009-01-30 22:09:00 +0000703 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000704 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000705 }
John McCall5decec92011-02-21 07:57:55 +0000706
707 // Fall through for subaggregate initialization.
708
709 } else if (SemaRef.getLangOptions().CPlusPlus) {
710 // C++ [dcl.init.aggr]p12:
711 // All implicit type conversions (clause 4) are considered when
712 // initializing the aggregate member with an ini- tializer from
713 // an initializer-list. If the initializer can initialize a
714 // member, the member is initialized. [...]
715
716 // FIXME: Better EqualLoc?
717 InitializationKind Kind =
718 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
719 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
720
721 if (Seq) {
722 ExprResult Result =
723 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
724 if (Result.isInvalid())
725 hadError = true;
726
727 UpdateStructuredListElement(StructuredList, StructuredIndex,
728 Result.takeAs<Expr>());
729 ++Index;
730 return;
731 }
732
733 // Fall through for subaggregate initialization
734 } else {
735 // C99 6.7.8p13:
736 //
737 // The initializer for a structure or union object that has
738 // automatic storage duration shall be either an initializer
739 // list as described below, or a single expression that has
740 // compatible structure or union type. In the latter case, the
741 // initial value of the object, including unnamed members, is
742 // that of the expression.
John Wiegley01296292011-04-08 18:41:53 +0000743 ExprResult ExprRes = SemaRef.Owned(expr);
John McCall5decec92011-02-21 07:57:55 +0000744 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
John Wiegley01296292011-04-08 18:41:53 +0000745 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes)
John McCall5decec92011-02-21 07:57:55 +0000746 == Sema::Compatible) {
John Wiegley01296292011-04-08 18:41:53 +0000747 if (ExprRes.isInvalid())
748 hadError = true;
749 else {
750 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
751 if (ExprRes.isInvalid())
752 hadError = true;
753 }
754 UpdateStructuredListElement(StructuredList, StructuredIndex,
755 ExprRes.takeAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +0000756 ++Index;
757 return;
758 }
John Wiegley01296292011-04-08 18:41:53 +0000759 ExprRes.release();
John McCall5decec92011-02-21 07:57:55 +0000760 // Fall through for subaggregate initialization
761 }
762
763 // C++ [dcl.init.aggr]p12:
764 //
765 // [...] Otherwise, if the member is itself a non-empty
766 // subaggregate, brace elision is assumed and the initializer is
767 // considered for the initialization of the first member of
768 // the subaggregate.
769 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
770 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
771 StructuredIndex);
772 ++StructuredIndex;
773 } else {
774 // We cannot initialize this element, so let
775 // PerformCopyInitialization produce the appropriate diagnostic.
776 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
777 SemaRef.Owned(expr));
778 hadError = true;
779 ++Index;
780 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +0000781 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000782}
783
Anders Carlsson6cabf312010-01-23 23:23:01 +0000784void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000785 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000786 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000787 InitListExpr *StructuredList,
788 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +0000789 if (Index >= IList->getNumInits()) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000790 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000791 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000792 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000793 ++Index;
794 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000795 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000796 }
John McCall643169b2010-11-11 00:46:36 +0000797
798 Expr *expr = IList->getInit(Index);
799 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
800 SemaRef.Diag(SubIList->getLocStart(),
801 diag::warn_many_braces_around_scalar_init)
802 << SubIList->getSourceRange();
803
804 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
805 StructuredIndex);
806 return;
807 } else if (isa<DesignatedInitExpr>(expr)) {
808 SemaRef.Diag(expr->getSourceRange().getBegin(),
809 diag::err_designator_for_scalar_init)
810 << DeclType << expr->getSourceRange();
811 hadError = true;
812 ++Index;
813 ++StructuredIndex;
814 return;
815 }
816
817 ExprResult Result =
818 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
819 SemaRef.Owned(expr));
820
821 Expr *ResultExpr = 0;
822
823 if (Result.isInvalid())
824 hadError = true; // types weren't compatible.
825 else {
826 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000827
John McCall643169b2010-11-11 00:46:36 +0000828 if (ResultExpr != expr) {
829 // The type was promoted, update initializer list.
830 IList->setInit(Index, ResultExpr);
831 }
832 }
833 if (hadError)
834 ++StructuredIndex;
835 else
836 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
837 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000838}
839
Anders Carlsson6cabf312010-01-23 23:23:01 +0000840void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
841 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000842 unsigned &Index,
843 InitListExpr *StructuredList,
844 unsigned &StructuredIndex) {
845 if (Index < IList->getNumInits()) {
846 Expr *expr = IList->getInit(Index);
847 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000848 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000849 << DeclType << IList->getSourceRange();
850 hadError = true;
851 ++Index;
852 ++StructuredIndex;
853 return;
Mike Stump11289f42009-09-09 15:08:12 +0000854 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000855
John McCalldadc5752010-08-24 06:29:42 +0000856 ExprResult Result =
Anders Carlssona91be642010-01-29 02:47:33 +0000857 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
858 SemaRef.Owned(expr));
859
860 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000861 hadError = true;
Anders Carlssona91be642010-01-29 02:47:33 +0000862
863 expr = Result.takeAs<Expr>();
864 IList->setInit(Index, expr);
865
Douglas Gregord14247a2009-01-30 22:09:00 +0000866 if (hadError)
867 ++StructuredIndex;
868 else
869 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
870 ++Index;
871 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000872 // FIXME: It would be wonderful if we could point at the actual member. In
873 // general, it would be useful to pass location information down the stack,
874 // so that we know the location (or decl) of the "current object" being
875 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000876 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000877 diag::err_init_reference_member_uninitialized)
878 << DeclType
879 << IList->getSourceRange();
880 hadError = true;
881 ++Index;
882 ++StructuredIndex;
883 return;
884 }
885}
886
Anders Carlsson6cabf312010-01-23 23:23:01 +0000887void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000888 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000889 unsigned &Index,
890 InitListExpr *StructuredList,
891 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +0000892 if (Index >= IList->getNumInits())
893 return;
Mike Stump11289f42009-09-09 15:08:12 +0000894
John McCall6a16b2f2010-10-30 00:11:39 +0000895 const VectorType *VT = DeclType->getAs<VectorType>();
896 unsigned maxElements = VT->getNumElements();
897 unsigned numEltsInit = 0;
898 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +0000899
John McCall6a16b2f2010-10-30 00:11:39 +0000900 if (!SemaRef.getLangOptions().OpenCL) {
901 // If the initializing element is a vector, try to copy-initialize
902 // instead of breaking it apart (which is doomed to failure anyway).
903 Expr *Init = IList->getInit(Index);
904 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
905 ExprResult Result =
906 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
907 SemaRef.Owned(Init));
908
909 Expr *ResultExpr = 0;
910 if (Result.isInvalid())
911 hadError = true; // types weren't compatible.
912 else {
913 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000914
John McCall6a16b2f2010-10-30 00:11:39 +0000915 if (ResultExpr != Init) {
916 // The type was promoted, update initializer list.
917 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +0000918 }
919 }
John McCall6a16b2f2010-10-30 00:11:39 +0000920 if (hadError)
921 ++StructuredIndex;
922 else
923 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
924 ++Index;
925 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000926 }
Mike Stump11289f42009-09-09 15:08:12 +0000927
John McCall6a16b2f2010-10-30 00:11:39 +0000928 InitializedEntity ElementEntity =
929 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000930
John McCall6a16b2f2010-10-30 00:11:39 +0000931 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
932 // Don't attempt to go past the end of the init list
933 if (Index >= IList->getNumInits())
934 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000935
John McCall6a16b2f2010-10-30 00:11:39 +0000936 ElementEntity.setElementIndex(Index);
937 CheckSubElementType(ElementEntity, IList, elementType, Index,
938 StructuredList, StructuredIndex);
939 }
940 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000941 }
John McCall6a16b2f2010-10-30 00:11:39 +0000942
943 InitializedEntity ElementEntity =
944 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000945
John McCall6a16b2f2010-10-30 00:11:39 +0000946 // OpenCL initializers allows vectors to be constructed from vectors.
947 for (unsigned i = 0; i < maxElements; ++i) {
948 // Don't attempt to go past the end of the init list
949 if (Index >= IList->getNumInits())
950 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000951
John McCall6a16b2f2010-10-30 00:11:39 +0000952 ElementEntity.setElementIndex(Index);
953
954 QualType IType = IList->getInit(Index)->getType();
955 if (!IType->isVectorType()) {
956 CheckSubElementType(ElementEntity, IList, elementType, Index,
957 StructuredList, StructuredIndex);
958 ++numEltsInit;
959 } else {
960 QualType VecType;
961 const VectorType *IVT = IType->getAs<VectorType>();
962 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000963
John McCall6a16b2f2010-10-30 00:11:39 +0000964 if (IType->isExtVectorType())
965 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
966 else
967 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +0000968 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +0000969 CheckSubElementType(ElementEntity, IList, VecType, Index,
970 StructuredList, StructuredIndex);
971 numEltsInit += numIElts;
972 }
973 }
974
975 // OpenCL requires all elements to be initialized.
976 if (numEltsInit != maxElements)
977 if (SemaRef.getLangOptions().OpenCL)
978 SemaRef.Diag(IList->getSourceRange().getBegin(),
979 diag::err_vector_incorrect_num_initializers)
980 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000981}
982
Anders Carlsson6cabf312010-01-23 23:23:01 +0000983void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000984 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000985 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000986 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000987 unsigned &Index,
988 InitListExpr *StructuredList,
989 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +0000990 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
991
Steve Narofff8ecff22008-05-01 22:18:59 +0000992 // Check for the special-case of initializing an array with a string.
993 if (Index < IList->getNumInits()) {
John McCall66884dd2011-02-21 07:22:22 +0000994 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000995 SemaRef.Context)) {
John McCall5decec92011-02-21 07:57:55 +0000996 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000997 // We place the string literal directly into the resulting
998 // initializer list. This is the only place where the structure
999 // of the structured initializer list doesn't match exactly,
1000 // because doing so would involve allocating one character
1001 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +00001002 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +00001003 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001004 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001005 return;
1006 }
1007 }
John McCall66884dd2011-02-21 07:22:22 +00001008 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001009 // Check for VLAs; in standard C it would be possible to check this
1010 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1011 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +00001012 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +00001013 diag::err_variable_object_no_init)
1014 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001015 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001016 ++Index;
1017 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001018 return;
1019 }
1020
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001021 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001022 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1023 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001024 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001025 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001026 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001027 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001028 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001029 maxElementsKnown = true;
1030 }
1031
John McCall66884dd2011-02-21 07:22:22 +00001032 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001033 while (Index < IList->getNumInits()) {
1034 Expr *Init = IList->getInit(Index);
1035 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001036 // If we're not the subobject that matches up with the '{' for
1037 // the designator, we shouldn't be handling the
1038 // designator. Return immediately.
1039 if (!SubobjectIsDesignatorContext)
1040 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001041
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001042 // Handle this designated initializer. elementIndex will be
1043 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001044 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001045 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001046 StructuredList, StructuredIndex, true,
1047 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001048 hadError = true;
1049 continue;
1050 }
1051
Douglas Gregor033d1252009-01-23 16:54:12 +00001052 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001053 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001054 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001055 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001056 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001057
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001058 // If the array is of incomplete type, keep track of the number of
1059 // elements in the initializer.
1060 if (!maxElementsKnown && elementIndex > maxElements)
1061 maxElements = elementIndex;
1062
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001063 continue;
1064 }
1065
1066 // If we know the maximum number of elements, and we've already
1067 // hit it, stop consuming elements in the initializer list.
1068 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001069 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001070
Anders Carlsson6cabf312010-01-23 23:23:01 +00001071 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001072 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001073 Entity);
1074 // Check this element.
1075 CheckSubElementType(ElementEntity, IList, elementType, Index,
1076 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001077 ++elementIndex;
1078
1079 // If the array is of incomplete type, keep track of the number of
1080 // elements in the initializer.
1081 if (!maxElementsKnown && elementIndex > maxElements)
1082 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001083 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001084 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001085 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001086 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001087 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001088 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001089 // Sizing an array implicitly to zero is not allowed by ISO C,
1090 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001091 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001092 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001093 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001094
Mike Stump11289f42009-09-09 15:08:12 +00001095 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001096 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001097 }
1098}
1099
Anders Carlsson6cabf312010-01-23 23:23:01 +00001100void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001101 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001102 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001103 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001104 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001105 unsigned &Index,
1106 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001107 unsigned &StructuredIndex,
1108 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001109 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001110
Eli Friedman23a9e312008-05-19 19:16:24 +00001111 // If the record is invalid, some of it's members are invalid. To avoid
1112 // confusion, we forgo checking the intializer for the entire record.
1113 if (structDecl->isInvalidDecl()) {
1114 hadError = true;
1115 return;
Mike Stump11289f42009-09-09 15:08:12 +00001116 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001117
1118 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1119 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001120 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001121 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001122 Field != FieldEnd; ++Field) {
1123 if (Field->getDeclName()) {
1124 StructuredList->setInitializedFieldInUnion(*Field);
1125 break;
1126 }
1127 }
1128 return;
1129 }
1130
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001131 // If structDecl is a forward declaration, this loop won't do
1132 // anything except look at designated initializers; That's okay,
1133 // because an error should get printed out elsewhere. It might be
1134 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001135 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001136 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001137 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001138 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001139 while (Index < IList->getNumInits()) {
1140 Expr *Init = IList->getInit(Index);
1141
1142 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001143 // If we're not the subobject that matches up with the '{' for
1144 // the designator, we shouldn't be handling the
1145 // designator. Return immediately.
1146 if (!SubobjectIsDesignatorContext)
1147 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001148
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001149 // Handle this designated initializer. Field will be updated to
1150 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001151 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001152 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001153 StructuredList, StructuredIndex,
1154 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001155 hadError = true;
1156
Douglas Gregora9add4e2009-02-12 19:00:39 +00001157 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001158
1159 // Disable check for missing fields when designators are used.
1160 // This matches gcc behaviour.
1161 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001162 continue;
1163 }
1164
1165 if (Field == FieldEnd) {
1166 // We've run out of fields. We're done.
1167 break;
1168 }
1169
Douglas Gregora9add4e2009-02-12 19:00:39 +00001170 // We've already initialized a member of a union. We're done.
1171 if (InitializedSomething && DeclType->isUnionType())
1172 break;
1173
Douglas Gregor91f84212008-12-11 16:49:14 +00001174 // If we've hit the flexible array member at the end, we're done.
1175 if (Field->getType()->isIncompleteArrayType())
1176 break;
1177
Douglas Gregor51695702009-01-29 16:53:55 +00001178 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001179 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001180 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001181 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001182 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001183
Anders Carlsson6cabf312010-01-23 23:23:01 +00001184 InitializedEntity MemberEntity =
1185 InitializedEntity::InitializeMember(*Field, &Entity);
1186 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1187 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001188 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001189
1190 if (DeclType->isUnionType()) {
1191 // Initialize the first field within the union.
1192 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001193 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001194
1195 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001196 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001197
John McCalle40b58e2010-03-11 19:32:38 +00001198 // Emit warnings for missing struct field initializers.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001199 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCalle40b58e2010-03-11 19:32:38 +00001200 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1201 // It is possible we have one or more unnamed bitfields remaining.
1202 // Find first (if any) named field and emit warning.
1203 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1204 it != end; ++it) {
1205 if (!it->isUnnamedBitfield()) {
1206 SemaRef.Diag(IList->getSourceRange().getEnd(),
1207 diag::warn_missing_field_initializers) << it->getName();
1208 break;
1209 }
1210 }
1211 }
1212
Mike Stump11289f42009-09-09 15:08:12 +00001213 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001214 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001215 return;
1216
1217 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001218 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001219 (!isa<InitListExpr>(IList->getInit(Index)) ||
1220 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001221 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001222 diag::err_flexible_array_init_nonempty)
1223 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001224 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001225 << *Field;
1226 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001227 ++Index;
1228 return;
1229 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001230 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001231 diag::ext_flexible_array_init)
1232 << IList->getInit(Index)->getSourceRange().getBegin();
1233 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1234 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001235 }
1236
Anders Carlsson6cabf312010-01-23 23:23:01 +00001237 InitializedEntity MemberEntity =
1238 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001239
Anders Carlsson6cabf312010-01-23 23:23:01 +00001240 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001241 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001242 StructuredList, StructuredIndex);
1243 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001244 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001245 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001246}
Steve Narofff8ecff22008-05-01 22:18:59 +00001247
Douglas Gregord5846a12009-04-15 06:41:24 +00001248/// \brief Expand a field designator that refers to a member of an
1249/// anonymous struct or union into a series of field designators that
1250/// refers to the field within the appropriate subobject.
1251///
Douglas Gregord5846a12009-04-15 06:41:24 +00001252static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001253 DesignatedInitExpr *DIE,
1254 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001255 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001256 typedef DesignatedInitExpr::Designator Designator;
1257
Douglas Gregord5846a12009-04-15 06:41:24 +00001258 // Build the replacement designators.
1259 llvm::SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001260 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1261 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1262 if (PI + 1 == PE)
Mike Stump11289f42009-09-09 15:08:12 +00001263 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001264 DIE->getDesignator(DesigIdx)->getDotLoc(),
1265 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1266 else
1267 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1268 SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001269 assert(isa<FieldDecl>(*PI));
1270 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001271 }
1272
1273 // Expand the current designator into the set of replacement
1274 // designators, so we have a full subobject path down to where the
1275 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001276 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001277 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001278}
Mike Stump11289f42009-09-09 15:08:12 +00001279
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001280/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001281/// corresponds to FieldName.
1282static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1283 IdentifierInfo *FieldName) {
1284 assert(AnonField->isAnonymousStructOrUnion());
1285 Decl *NextDecl = AnonField->getNextDeclInContext();
1286 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1287 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1288 return IF;
1289 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001290 }
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001291 return 0;
Douglas Gregord5846a12009-04-15 06:41:24 +00001292}
1293
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001294/// @brief Check the well-formedness of a C99 designated initializer.
1295///
1296/// Determines whether the designated initializer @p DIE, which
1297/// resides at the given @p Index within the initializer list @p
1298/// IList, is well-formed for a current object of type @p DeclType
1299/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001300/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001301/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001302///
1303/// @param IList The initializer list in which this designated
1304/// initializer occurs.
1305///
Douglas Gregora5324162009-04-15 04:56:10 +00001306/// @param DIE The designated initializer expression.
1307///
1308/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001309///
1310/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1311/// into which the designation in @p DIE should refer.
1312///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001313/// @param NextField If non-NULL and the first designator in @p DIE is
1314/// a field, this will be set to the field declaration corresponding
1315/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001316///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001317/// @param NextElementIndex If non-NULL and the first designator in @p
1318/// DIE is an array designator or GNU array-range designator, this
1319/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001320///
1321/// @param Index Index into @p IList where the designated initializer
1322/// @p DIE occurs.
1323///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001324/// @param StructuredList The initializer list expression that
1325/// describes all of the subobject initializers in the order they'll
1326/// actually be initialized.
1327///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001328/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001329bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001330InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001331 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001332 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001333 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001334 QualType &CurrentObjectType,
1335 RecordDecl::field_iterator *NextField,
1336 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001337 unsigned &Index,
1338 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001339 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001340 bool FinishSubobjectInit,
1341 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001342 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001343 // Check the actual initialization for the designated object type.
1344 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001345
1346 // Temporarily remove the designator expression from the
1347 // initializer list that the child calls see, so that we don't try
1348 // to re-process the designator.
1349 unsigned OldIndex = Index;
1350 IList->setInit(OldIndex, DIE->getInit());
1351
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001352 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001353 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001354
1355 // Restore the designated initializer expression in the syntactic
1356 // form of the initializer list.
1357 if (IList->getInit(OldIndex) != DIE->getInit())
1358 DIE->setInit(IList->getInit(OldIndex));
1359 IList->setInit(OldIndex, DIE);
1360
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001361 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001362 }
1363
Douglas Gregora5324162009-04-15 04:56:10 +00001364 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001365 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001366 "Need a non-designated initializer list to start from");
1367
Douglas Gregora5324162009-04-15 04:56:10 +00001368 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001369 // Determine the structural initializer list that corresponds to the
1370 // current subobject.
1371 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001372 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001373 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001374 SourceRange(D->getStartLocation(),
1375 DIE->getSourceRange().getEnd()));
1376 assert(StructuredList && "Expected a structured initializer list");
1377
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001378 if (D->isFieldDesignator()) {
1379 // C99 6.7.8p7:
1380 //
1381 // If a designator has the form
1382 //
1383 // . identifier
1384 //
1385 // then the current object (defined below) shall have
1386 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001387 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001388 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001389 if (!RT) {
1390 SourceLocation Loc = D->getDotLoc();
1391 if (Loc.isInvalid())
1392 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001393 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1394 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001395 ++Index;
1396 return true;
1397 }
1398
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001399 // Note: we perform a linear search of the fields here, despite
1400 // the fact that we have a faster lookup method, because we always
1401 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001402 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001403 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001404 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001405 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001406 Field = RT->getDecl()->field_begin(),
1407 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001408 for (; Field != FieldEnd; ++Field) {
1409 if (Field->isUnnamedBitfield())
1410 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001411
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001412 // If we find a field representing an anonymous field, look in the
1413 // IndirectFieldDecl that follow for the designated initializer.
1414 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1415 if (IndirectFieldDecl *IF =
1416 FindIndirectFieldDesignator(*Field, FieldName)) {
1417 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1418 D = DIE->getDesignator(DesigIdx);
1419 break;
1420 }
1421 }
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001422 if (KnownField && KnownField == *Field)
1423 break;
1424 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001425 break;
1426
1427 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001428 }
1429
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001430 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001431 // There was no normal field in the struct with the designated
1432 // name. Perform another lookup for this name, which may find
1433 // something that we can't designate (e.g., a member function),
1434 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001435 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001436 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001437 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001438 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001439 // Name lookup didn't find anything. Determine whether this
1440 // was a typo for another field name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001441 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001442 Sema::LookupMemberName);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001443 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl(), false,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001444 Sema::CTC_NoKeywords) &&
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001445 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
Sebastian Redl50c68252010-08-31 00:36:30 +00001446 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001447 ->Equals(RT->getDecl())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001448 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001449 diag::err_field_designator_unknown_suggest)
1450 << FieldName << CurrentObjectType << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001451 << FixItHint::CreateReplacement(D->getFieldLoc(),
1452 R.getLookupName().getAsString());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001453 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregor6da83622010-01-07 00:17:44 +00001454 diag::note_previous_decl)
1455 << ReplacementField->getDeclName();
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001456 } else {
1457 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1458 << FieldName << CurrentObjectType;
1459 ++Index;
1460 return true;
1461 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001462 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001463
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001464 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001465 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001466 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001467 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001468 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001469 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001470 ++Index;
1471 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001472 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001473
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001474 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001475 // The replacement field comes from typo correction; find it
1476 // in the list of fields.
1477 FieldIndex = 0;
1478 Field = RT->getDecl()->field_begin();
1479 for (; Field != FieldEnd; ++Field) {
1480 if (Field->isUnnamedBitfield())
1481 continue;
1482
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001483 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001484 Field->getIdentifier() == ReplacementField->getIdentifier())
1485 break;
1486
1487 ++FieldIndex;
1488 }
1489 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001490 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001491
1492 // All of the fields of a union are located at the same place in
1493 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001494 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001495 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001496 StructuredList->setInitializedFieldInUnion(*Field);
1497 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001498
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001499 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001500 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001501
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001502 // Make sure that our non-designated initializer list has space
1503 // for a subobject corresponding to this field.
1504 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001505 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001506
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001507 // This designator names a flexible array member.
1508 if (Field->getType()->isIncompleteArrayType()) {
1509 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001510 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001511 // We can't designate an object within the flexible array
1512 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001513 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001514 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001515 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001516 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001517 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001518 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001519 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001520 << *Field;
1521 Invalid = true;
1522 }
1523
Chris Lattner001b29c2010-10-10 17:49:49 +00001524 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1525 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001526 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001527 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001528 diag::err_flexible_array_init_needs_braces)
1529 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001530 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001531 << *Field;
1532 Invalid = true;
1533 }
1534
1535 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001536 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001537 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001538 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001539 diag::err_flexible_array_init_nonempty)
1540 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001541 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001542 << *Field;
1543 Invalid = true;
1544 }
1545
1546 if (Invalid) {
1547 ++Index;
1548 return true;
1549 }
1550
1551 // Initialize the array.
1552 bool prevHadError = hadError;
1553 unsigned newStructuredIndex = FieldIndex;
1554 unsigned OldIndex = Index;
1555 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001556
1557 InitializedEntity MemberEntity =
1558 InitializedEntity::InitializeMember(*Field, &Entity);
1559 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001560 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001561
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001562 IList->setInit(OldIndex, DIE);
1563 if (hadError && !prevHadError) {
1564 ++Field;
1565 ++FieldIndex;
1566 if (NextField)
1567 *NextField = Field;
1568 StructuredIndex = FieldIndex;
1569 return true;
1570 }
1571 } else {
1572 // Recurse to check later designated subobjects.
1573 QualType FieldType = (*Field)->getType();
1574 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001575
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001576 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001577 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001578 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1579 FieldType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001580 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001581 true, false))
1582 return true;
1583 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001584
1585 // Find the position of the next field to be initialized in this
1586 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001587 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001588 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001589
1590 // If this the first designator, our caller will continue checking
1591 // the rest of this struct/class/union subobject.
1592 if (IsFirstDesignator) {
1593 if (NextField)
1594 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001595 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001596 return false;
1597 }
1598
Douglas Gregor17bd0942009-01-28 23:36:17 +00001599 if (!FinishSubobjectInit)
1600 return false;
1601
Douglas Gregord5846a12009-04-15 06:41:24 +00001602 // We've already initialized something in the union; we're done.
1603 if (RT->getDecl()->isUnion())
1604 return hadError;
1605
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001606 // Check the remaining fields within this class/struct/union subobject.
1607 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001608
Anders Carlsson6cabf312010-01-23 23:23:01 +00001609 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001610 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001611 return hadError && !prevHadError;
1612 }
1613
1614 // C99 6.7.8p6:
1615 //
1616 // If a designator has the form
1617 //
1618 // [ constant-expression ]
1619 //
1620 // then the current object (defined below) shall have array
1621 // type and the expression shall be an integer constant
1622 // expression. If the array is of unknown size, any
1623 // nonnegative value is valid.
1624 //
1625 // Additionally, cope with the GNU extension that permits
1626 // designators of the form
1627 //
1628 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001629 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001630 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001631 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001632 << CurrentObjectType;
1633 ++Index;
1634 return true;
1635 }
1636
1637 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001638 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1639 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001640 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001641 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001642 DesignatedEndIndex = DesignatedStartIndex;
1643 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001644 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001645
Mike Stump11289f42009-09-09 15:08:12 +00001646 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001647 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001648 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001649 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001650 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001651
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00001652 // Codegen can't handle evaluating array range designators that have side
1653 // effects, because we replicate the AST value for each initialized element.
1654 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1655 // elements with something that has a side effect, so codegen can emit an
1656 // "error unsupported" error instead of miscompiling the app.
1657 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
1658 DIE->getInit()->HasSideEffects(SemaRef.Context))
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001659 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001660 }
1661
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001662 if (isa<ConstantArrayType>(AT)) {
1663 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001664 DesignatedStartIndex
1665 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001666 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00001667 DesignatedEndIndex
1668 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001669 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1670 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001671 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001672 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001673 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001674 << IndexExpr->getSourceRange();
1675 ++Index;
1676 return true;
1677 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001678 } else {
1679 // Make sure the bit-widths and signedness match.
1680 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001681 DesignatedEndIndex
1682 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001683 else if (DesignatedStartIndex.getBitWidth() <
1684 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001685 DesignatedStartIndex
1686 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001687 DesignatedStartIndex.setIsUnsigned(true);
1688 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001689 }
Mike Stump11289f42009-09-09 15:08:12 +00001690
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001691 // Make sure that our non-designated initializer list has space
1692 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001693 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001694 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001695 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001696
Douglas Gregor17bd0942009-01-28 23:36:17 +00001697 // Repeatedly perform subobject initializations in the range
1698 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001699
Douglas Gregor17bd0942009-01-28 23:36:17 +00001700 // Move to the next designator
1701 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1702 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001703
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001704 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001705 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001706
Douglas Gregor17bd0942009-01-28 23:36:17 +00001707 while (DesignatedStartIndex <= DesignatedEndIndex) {
1708 // Recurse to check later designated subobjects.
1709 QualType ElementType = AT->getElementType();
1710 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001711
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001712 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001713 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1714 ElementType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001715 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001716 (DesignatedStartIndex == DesignatedEndIndex),
1717 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001718 return true;
1719
1720 // Move to the next index in the array that we'll be initializing.
1721 ++DesignatedStartIndex;
1722 ElementIndex = DesignatedStartIndex.getZExtValue();
1723 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001724
1725 // If this the first designator, our caller will continue checking
1726 // the rest of this array subobject.
1727 if (IsFirstDesignator) {
1728 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001729 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001730 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001731 return false;
1732 }
Mike Stump11289f42009-09-09 15:08:12 +00001733
Douglas Gregor17bd0942009-01-28 23:36:17 +00001734 if (!FinishSubobjectInit)
1735 return false;
1736
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001737 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001738 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001739 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001740 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001741 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001742 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001743}
1744
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001745// Get the structured initializer list for a subobject of type
1746// @p CurrentObjectType.
1747InitListExpr *
1748InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1749 QualType CurrentObjectType,
1750 InitListExpr *StructuredList,
1751 unsigned StructuredIndex,
1752 SourceRange InitRange) {
1753 Expr *ExistingInit = 0;
1754 if (!StructuredList)
1755 ExistingInit = SyntacticToSemantic[IList];
1756 else if (StructuredIndex < StructuredList->getNumInits())
1757 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001758
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001759 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1760 return Result;
1761
1762 if (ExistingInit) {
1763 // We are creating an initializer list that initializes the
1764 // subobjects of the current object, but there was already an
1765 // initialization that completely initialized the current
1766 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001767 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001768 // struct X { int a, b; };
1769 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001770 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001771 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1772 // designated initializer re-initializes the whole
1773 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001774 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001775 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001776 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001777 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001778 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001779 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001780 << ExistingInit->getSourceRange();
1781 }
1782
Mike Stump11289f42009-09-09 15:08:12 +00001783 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00001784 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1785 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00001786 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00001787
Douglas Gregora8a089b2010-07-13 18:40:04 +00001788 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001789
Douglas Gregor6d00c992009-03-20 23:58:33 +00001790 // Pre-allocate storage for the structured initializer list.
1791 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001792 unsigned NumInits = 0;
1793 if (!StructuredList)
1794 NumInits = IList->getNumInits();
1795 else if (Index < IList->getNumInits()) {
1796 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1797 NumInits = SubList->getNumInits();
1798 }
1799
Mike Stump11289f42009-09-09 15:08:12 +00001800 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001801 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1802 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1803 NumElements = CAType->getSize().getZExtValue();
1804 // Simple heuristic so that we don't allocate a very large
1805 // initializer with many empty entries at the end.
Douglas Gregor221c9a52009-03-21 18:13:52 +00001806 if (NumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001807 NumElements = 0;
1808 }
John McCall9dd450b2009-09-21 23:43:11 +00001809 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001810 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001811 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001812 RecordDecl *RDecl = RType->getDecl();
1813 if (RDecl->isUnion())
1814 NumElements = 1;
1815 else
Mike Stump11289f42009-09-09 15:08:12 +00001816 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001817 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001818 }
1819
Douglas Gregor221c9a52009-03-21 18:13:52 +00001820 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001821 NumElements = IList->getNumInits();
1822
Ted Kremenekac034612010-04-13 23:39:13 +00001823 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00001824
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001825 // Link this new initializer list into the structured initializer
1826 // lists.
1827 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00001828 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001829 else {
1830 Result->setSyntacticForm(IList);
1831 SyntacticToSemantic[IList] = Result;
1832 }
1833
1834 return Result;
1835}
1836
1837/// Update the initializer at index @p StructuredIndex within the
1838/// structured initializer list to the value @p expr.
1839void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1840 unsigned &StructuredIndex,
1841 Expr *expr) {
1842 // No structured initializer list to update
1843 if (!StructuredList)
1844 return;
1845
Ted Kremenekac034612010-04-13 23:39:13 +00001846 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1847 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001848 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001849 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001850 diag::warn_initializer_overrides)
1851 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001852 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001853 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001854 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001855 << PrevInit->getSourceRange();
1856 }
Mike Stump11289f42009-09-09 15:08:12 +00001857
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001858 ++StructuredIndex;
1859}
1860
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001861/// Check that the given Index expression is a valid array designator
1862/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001863/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001864/// and produces a reasonable diagnostic if there is a
1865/// failure. Returns true if there was an error, false otherwise. If
1866/// everything went okay, Value will receive the value of the constant
1867/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001868static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001869CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001870 SourceLocation Loc = Index->getSourceRange().getBegin();
1871
1872 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001873 if (S.VerifyIntegerConstantExpression(Index, &Value))
1874 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001875
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001876 if (Value.isSigned() && Value.isNegative())
1877 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001878 << Value.toString(10) << Index->getSourceRange();
1879
Douglas Gregor51650d32009-01-23 21:04:18 +00001880 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001881 return false;
1882}
1883
John McCalldadc5752010-08-24 06:29:42 +00001884ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00001885 SourceLocation Loc,
1886 bool GNUSyntax,
1887 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001888 typedef DesignatedInitExpr::Designator ASTDesignator;
1889
1890 bool Invalid = false;
1891 llvm::SmallVector<ASTDesignator, 32> Designators;
1892 llvm::SmallVector<Expr *, 32> InitExpressions;
1893
1894 // Build designators and check array designator expressions.
1895 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1896 const Designator &D = Desig.getDesignator(Idx);
1897 switch (D.getKind()) {
1898 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001899 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001900 D.getFieldLoc()));
1901 break;
1902
1903 case Designator::ArrayDesignator: {
1904 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1905 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001906 if (!Index->isTypeDependent() &&
1907 !Index->isValueDependent() &&
1908 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001909 Invalid = true;
1910 else {
1911 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001912 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001913 D.getRBracketLoc()));
1914 InitExpressions.push_back(Index);
1915 }
1916 break;
1917 }
1918
1919 case Designator::ArrayRangeDesignator: {
1920 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1921 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1922 llvm::APSInt StartValue;
1923 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001924 bool StartDependent = StartIndex->isTypeDependent() ||
1925 StartIndex->isValueDependent();
1926 bool EndDependent = EndIndex->isTypeDependent() ||
1927 EndIndex->isValueDependent();
1928 if ((!StartDependent &&
1929 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1930 (!EndDependent &&
1931 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001932 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001933 else {
1934 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001935 if (StartDependent || EndDependent) {
1936 // Nothing to compute.
1937 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001938 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00001939 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001940 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00001941
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001942 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001943 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001944 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001945 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1946 Invalid = true;
1947 } else {
1948 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001949 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001950 D.getEllipsisLoc(),
1951 D.getRBracketLoc()));
1952 InitExpressions.push_back(StartIndex);
1953 InitExpressions.push_back(EndIndex);
1954 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001955 }
1956 break;
1957 }
1958 }
1959 }
1960
1961 if (Invalid || Init.isInvalid())
1962 return ExprError();
1963
1964 // Clear out the expressions within the designation.
1965 Desig.ClearExprs(*this);
1966
1967 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001968 = DesignatedInitExpr::Create(Context,
1969 Designators.data(), Designators.size(),
1970 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001971 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001972
Douglas Gregorc124e592011-01-16 16:13:16 +00001973 if (getLangOptions().CPlusPlus)
1974 Diag(DIE->getLocStart(), diag::ext_designated_init)
1975 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001976
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001977 return Owned(DIE);
1978}
Douglas Gregor85df8d82009-01-29 00:45:39 +00001979
Douglas Gregor723796a2009-12-16 06:35:08 +00001980bool Sema::CheckInitList(const InitializedEntity &Entity,
1981 InitListExpr *&InitList, QualType &DeclType) {
1982 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00001983 if (!CheckInitList.HadError())
1984 InitList = CheckInitList.getFullyStructuredList();
1985
1986 return CheckInitList.HadError();
1987}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00001988
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001989//===----------------------------------------------------------------------===//
1990// Initialization entity
1991//===----------------------------------------------------------------------===//
1992
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001993InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00001994 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001995 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00001996{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001997 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1998 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001999 Type = AT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002000 } else {
2001 Kind = EK_VectorElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002002 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002003 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002004}
2005
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002006InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002007 CXXBaseSpecifier *Base,
2008 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002009{
2010 InitializedEntity Result;
2011 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002012 Result.Base = reinterpret_cast<uintptr_t>(Base);
2013 if (IsInheritedVirtualBase)
2014 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002015
Douglas Gregor1b303932009-12-22 15:35:07 +00002016 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002017 return Result;
2018}
2019
Douglas Gregor85dabae2009-12-16 01:38:02 +00002020DeclarationName InitializedEntity::getName() const {
2021 switch (getKind()) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00002022 case EK_Parameter:
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002023 if (!VariableOrMember)
2024 return DeclarationName();
2025 // Fall through
2026
2027 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002028 case EK_Member:
2029 return VariableOrMember->getDeclName();
2030
2031 case EK_Result:
2032 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002033 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002034 case EK_Temporary:
2035 case EK_Base:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002036 case EK_Delegation:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002037 case EK_ArrayElement:
2038 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002039 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002040 return DeclarationName();
2041 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002042
Douglas Gregor85dabae2009-12-16 01:38:02 +00002043 // Silence GCC warning
2044 return DeclarationName();
2045}
2046
Douglas Gregora4b592a2009-12-19 03:01:41 +00002047DeclaratorDecl *InitializedEntity::getDecl() const {
2048 switch (getKind()) {
2049 case EK_Variable:
2050 case EK_Parameter:
2051 case EK_Member:
2052 return VariableOrMember;
2053
2054 case EK_Result:
2055 case EK_Exception:
2056 case EK_New:
2057 case EK_Temporary:
2058 case EK_Base:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002059 case EK_Delegation:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002060 case EK_ArrayElement:
2061 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002062 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002063 return 0;
2064 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002065
Douglas Gregora4b592a2009-12-19 03:01:41 +00002066 // Silence GCC warning
2067 return 0;
2068}
2069
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002070bool InitializedEntity::allowsNRVO() const {
2071 switch (getKind()) {
2072 case EK_Result:
2073 case EK_Exception:
2074 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002075
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002076 case EK_Variable:
2077 case EK_Parameter:
2078 case EK_Member:
2079 case EK_New:
2080 case EK_Temporary:
2081 case EK_Base:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002082 case EK_Delegation:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002083 case EK_ArrayElement:
2084 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002085 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002086 break;
2087 }
2088
2089 return false;
2090}
2091
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002092//===----------------------------------------------------------------------===//
2093// Initialization sequence
2094//===----------------------------------------------------------------------===//
2095
2096void InitializationSequence::Step::Destroy() {
2097 switch (Kind) {
2098 case SK_ResolveAddressOfOverloadedFunction:
2099 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002100 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002101 case SK_CastDerivedToBaseLValue:
2102 case SK_BindReference:
2103 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002104 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002105 case SK_UserConversion:
2106 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002107 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002108 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002109 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002110 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002111 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002112 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002113 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002114 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002115 case SK_ArrayInit:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002116 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002117
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002118 case SK_ConversionSequence:
2119 delete ICS;
2120 }
2121}
2122
Douglas Gregor838fcc32010-03-26 20:14:36 +00002123bool InitializationSequence::isDirectReferenceBinding() const {
2124 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2125}
2126
2127bool InitializationSequence::isAmbiguous() const {
2128 if (getKind() != FailedSequence)
2129 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002130
Douglas Gregor838fcc32010-03-26 20:14:36 +00002131 switch (getFailureKind()) {
2132 case FK_TooManyInitsForReference:
2133 case FK_ArrayNeedsInitList:
2134 case FK_ArrayNeedsInitListOrStringLiteral:
2135 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2136 case FK_NonConstLValueReferenceBindingToTemporary:
2137 case FK_NonConstLValueReferenceBindingToUnrelated:
2138 case FK_RValueReferenceBindingToLValue:
2139 case FK_ReferenceInitDropsQualifiers:
2140 case FK_ReferenceInitFailed:
2141 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002142 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002143 case FK_TooManyInitsForScalar:
2144 case FK_ReferenceBindingToInitList:
2145 case FK_InitListBadDestinationType:
2146 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002147 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002148 case FK_ArrayTypeMismatch:
2149 case FK_NonConstantArrayInit:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002150 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002151
Douglas Gregor838fcc32010-03-26 20:14:36 +00002152 case FK_ReferenceInitOverloadFailed:
2153 case FK_UserConversionOverloadFailed:
2154 case FK_ConstructorOverloadFailed:
2155 return FailedOverloadResult == OR_Ambiguous;
2156 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002157
Douglas Gregor838fcc32010-03-26 20:14:36 +00002158 return false;
2159}
2160
Douglas Gregorb33eed02010-04-16 22:09:46 +00002161bool InitializationSequence::isConstructorInitialization() const {
2162 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2163}
2164
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002165void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall16df1e52010-03-30 21:47:33 +00002166 FunctionDecl *Function,
2167 DeclAccessPair Found) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002168 Step S;
2169 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2170 S.Type = Function->getType();
John McCalla0296f72010-03-19 07:35:19 +00002171 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002172 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002173 Steps.push_back(S);
2174}
2175
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002176void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002177 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002178 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002179 switch (VK) {
2180 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2181 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2182 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002183 default: llvm_unreachable("No such category");
2184 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002185 S.Type = BaseType;
2186 Steps.push_back(S);
2187}
2188
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002189void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002190 bool BindingTemporary) {
2191 Step S;
2192 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2193 S.Type = T;
2194 Steps.push_back(S);
2195}
2196
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002197void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2198 Step S;
2199 S.Kind = SK_ExtraneousCopyToTemporary;
2200 S.Type = T;
2201 Steps.push_back(S);
2202}
2203
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002204void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002205 DeclAccessPair FoundDecl,
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002206 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002207 Step S;
2208 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002209 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002210 S.Function.Function = Function;
2211 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002212 Steps.push_back(S);
2213}
2214
2215void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002216 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002217 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002218 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002219 switch (VK) {
2220 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002221 S.Kind = SK_QualificationConversionRValue;
2222 break;
John McCall2536c6d2010-08-25 10:28:54 +00002223 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002224 S.Kind = SK_QualificationConversionXValue;
2225 break;
John McCall2536c6d2010-08-25 10:28:54 +00002226 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002227 S.Kind = SK_QualificationConversionLValue;
2228 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002229 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002230 S.Type = Ty;
2231 Steps.push_back(S);
2232}
2233
2234void InitializationSequence::AddConversionSequenceStep(
2235 const ImplicitConversionSequence &ICS,
2236 QualType T) {
2237 Step S;
2238 S.Kind = SK_ConversionSequence;
2239 S.Type = T;
2240 S.ICS = new ImplicitConversionSequence(ICS);
2241 Steps.push_back(S);
2242}
2243
Douglas Gregor51e77d52009-12-10 17:56:55 +00002244void InitializationSequence::AddListInitializationStep(QualType T) {
2245 Step S;
2246 S.Kind = SK_ListInitialization;
2247 S.Type = T;
2248 Steps.push_back(S);
2249}
2250
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002251void
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002252InitializationSequence::AddConstructorInitializationStep(
2253 CXXConstructorDecl *Constructor,
John McCall760af172010-02-01 03:16:54 +00002254 AccessSpecifier Access,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002255 QualType T) {
2256 Step S;
2257 S.Kind = SK_ConstructorInitialization;
2258 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002259 S.Function.Function = Constructor;
2260 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002261 Steps.push_back(S);
2262}
2263
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002264void InitializationSequence::AddZeroInitializationStep(QualType T) {
2265 Step S;
2266 S.Kind = SK_ZeroInitialization;
2267 S.Type = T;
2268 Steps.push_back(S);
2269}
2270
Douglas Gregore1314a62009-12-18 05:02:21 +00002271void InitializationSequence::AddCAssignmentStep(QualType T) {
2272 Step S;
2273 S.Kind = SK_CAssignment;
2274 S.Type = T;
2275 Steps.push_back(S);
2276}
2277
Eli Friedman78275202009-12-19 08:11:05 +00002278void InitializationSequence::AddStringInitStep(QualType T) {
2279 Step S;
2280 S.Kind = SK_StringInit;
2281 S.Type = T;
2282 Steps.push_back(S);
2283}
2284
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002285void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2286 Step S;
2287 S.Kind = SK_ObjCObjectConversion;
2288 S.Type = T;
2289 Steps.push_back(S);
2290}
2291
Douglas Gregore2f943b2011-02-22 18:29:51 +00002292void InitializationSequence::AddArrayInitStep(QualType T) {
2293 Step S;
2294 S.Kind = SK_ArrayInit;
2295 S.Type = T;
2296 Steps.push_back(S);
2297}
2298
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002299void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002300 OverloadingResult Result) {
2301 SequenceKind = FailedSequence;
2302 this->Failure = Failure;
2303 this->FailedOverloadResult = Result;
2304}
2305
2306//===----------------------------------------------------------------------===//
2307// Attempt initialization
2308//===----------------------------------------------------------------------===//
2309
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002310/// \brief Attempt list initialization (C++0x [dcl.init.list])
2311static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002312 const InitializedEntity &Entity,
2313 const InitializationKind &Kind,
2314 InitListExpr *InitList,
2315 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00002316 // FIXME: We only perform rudimentary checking of list
2317 // initializations at this point, then assume that any list
2318 // initialization of an array, aggregate, or scalar will be
Sebastian Redld559a542010-06-30 16:41:54 +00002319 // well-formed. When we actually "perform" list initialization, we'll
Douglas Gregor51e77d52009-12-10 17:56:55 +00002320 // do all of the necessary checking. C++0x initializer lists will
2321 // force us to perform more checking here.
2322 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2323
Douglas Gregor1b303932009-12-22 15:35:07 +00002324 QualType DestType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00002325
2326 // C++ [dcl.init]p13:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002327 // If T is a scalar type, then a declaration of the form
Douglas Gregor51e77d52009-12-10 17:56:55 +00002328 //
2329 // T x = { a };
2330 //
2331 // is equivalent to
2332 //
2333 // T x = a;
2334 if (DestType->isScalarType()) {
2335 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2336 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2337 return;
2338 }
2339
2340 // Assume scalar initialization from a single value works.
2341 } else if (DestType->isAggregateType()) {
2342 // Assume aggregate initialization works.
2343 } else if (DestType->isVectorType()) {
2344 // Assume vector initialization works.
2345 } else if (DestType->isReferenceType()) {
2346 // FIXME: C++0x defines behavior for this.
2347 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2348 return;
2349 } else if (DestType->isRecordType()) {
2350 // FIXME: C++0x defines behavior for this
2351 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2352 }
2353
2354 // Add a general "list initialization" step.
2355 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002356}
2357
2358/// \brief Try a reference initialization that involves calling a conversion
2359/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002360static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2361 const InitializedEntity &Entity,
2362 const InitializationKind &Kind,
2363 Expr *Initializer,
2364 bool AllowRValues,
2365 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002366 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002367 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2368 QualType T1 = cv1T1.getUnqualifiedType();
2369 QualType cv2T2 = Initializer->getType();
2370 QualType T2 = cv2T2.getUnqualifiedType();
2371
2372 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002373 bool ObjCConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002374 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002375 T1, T2, DerivedToBase,
2376 ObjCConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002377 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002378 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002379 (void)ObjCConversion;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002380
2381 // Build the candidate set directly in the initialization sequence
2382 // structure, so that it will persist if we fail.
2383 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2384 CandidateSet.clear();
2385
2386 // Determine whether we are allowed to call explicit constructors or
2387 // explicit conversion operators.
2388 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002389
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002390 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002391 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2392 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002393 // The type we're converting to is a class type. Enumerate its constructors
2394 // to see if there is a suitable conversion.
2395 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00002396
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002397 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002398 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002399 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002400 NamedDecl *D = *Con;
2401 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2402
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002403 // Find the constructor (which may be a template).
2404 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002405 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002406 if (ConstructorTmpl)
2407 Constructor = cast<CXXConstructorDecl>(
2408 ConstructorTmpl->getTemplatedDecl());
2409 else
John McCalla0296f72010-03-19 07:35:19 +00002410 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002411
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002412 if (!Constructor->isInvalidDecl() &&
2413 Constructor->isConvertingConstructor(AllowExplicit)) {
2414 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002415 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002416 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002417 &Initializer, 1, CandidateSet,
2418 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002419 else
John McCalla0296f72010-03-19 07:35:19 +00002420 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002421 &Initializer, 1, CandidateSet,
2422 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002423 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002424 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002425 }
John McCall3696dcb2010-08-17 07:23:57 +00002426 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2427 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002428
Douglas Gregor496e8b342010-05-07 19:42:26 +00002429 const RecordType *T2RecordType = 0;
2430 if ((T2RecordType = T2->getAs<RecordType>()) &&
2431 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002432 // The type we're converting from is a class type, enumerate its conversion
2433 // functions.
2434 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2435
John McCallad371252010-01-20 00:46:10 +00002436 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002437 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002438 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2439 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002440 NamedDecl *D = *I;
2441 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2442 if (isa<UsingShadowDecl>(D))
2443 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002444
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002445 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2446 CXXConversionDecl *Conv;
2447 if (ConvTemplate)
2448 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2449 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002450 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002451
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002452 // If the conversion function doesn't return a reference type,
2453 // it can't be considered for this conversion unless we're allowed to
2454 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002455 // FIXME: Do we need to make sure that we only consider conversion
2456 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002457 // break recursion.
2458 if ((AllowExplicit || !Conv->isExplicit()) &&
2459 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2460 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002461 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002462 ActingDC, Initializer,
Douglas Gregord412fe52011-01-21 00:27:08 +00002463 DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002464 else
John McCalla0296f72010-03-19 07:35:19 +00002465 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregord412fe52011-01-21 00:27:08 +00002466 Initializer, DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002467 }
2468 }
2469 }
John McCall3696dcb2010-08-17 07:23:57 +00002470 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2471 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002472
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002473 SourceLocation DeclLoc = Initializer->getLocStart();
2474
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002475 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002476 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002477 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00002478 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002479 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002480
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002481 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002482
Chandler Carruth30141632011-02-25 19:41:05 +00002483 // This is the overload that will actually be used for the initialization, so
2484 // mark it as used.
2485 S.MarkDeclarationReferenced(DeclLoc, Function);
2486
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002487 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002488 if (isa<CXXConversionDecl>(Function))
2489 T2 = Function->getResultType();
2490 else
2491 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002492
2493 // Add the user-defined conversion step.
John McCalla0296f72010-03-19 07:35:19 +00002494 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002495 T2.getNonLValueExprType(S.Context));
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002496
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002497 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002498 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00002499 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002500 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00002501 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002502 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00002503 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002504
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002505 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002506 bool NewObjCConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002507 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002508 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002509 T2.getNonLValueExprType(S.Context),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002510 NewDerivedToBase, NewObjCConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00002511 if (NewRefRelationship == Sema::Ref_Incompatible) {
2512 // If the type we've converted to is not reference-related to the
2513 // type we're looking for, then there is another conversion step
2514 // we need to perform to produce a temporary of the right type
2515 // that we'll be binding to.
2516 ImplicitConversionSequence ICS;
2517 ICS.setStandard();
2518 ICS.Standard = Best->FinalConversion;
2519 T2 = ICS.Standard.getToType(2);
2520 Sequence.AddConversionSequenceStep(ICS, T2);
2521 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002522 Sequence.AddDerivedToBaseCastStep(
2523 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002524 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00002525 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002526 else if (NewObjCConversion)
2527 Sequence.AddObjCObjectConversionStep(
2528 S.Context.getQualifiedType(T1,
2529 T2.getNonReferenceType().getQualifiers()));
2530
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002531 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00002532 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002533
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002534 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2535 return OR_Success;
2536}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002537
2538/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2539static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002540 const InitializedEntity &Entity,
2541 const InitializationKind &Kind,
2542 Expr *Initializer,
2543 InitializationSequence &Sequence) {
2544 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
Sebastian Redld92badf2010-06-30 18:13:39 +00002545
Douglas Gregor1b303932009-12-22 15:35:07 +00002546 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002547 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002548 Qualifiers T1Quals;
2549 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002550 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002551 Qualifiers T2Quals;
2552 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002553 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redld92badf2010-06-30 18:13:39 +00002554
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002555 // If the initializer is the address of an overloaded function, try
2556 // to resolve the overloaded function. If all goes well, T2 is the
2557 // type of the resulting function.
2558 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall16df1e52010-03-30 21:47:33 +00002559 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002560 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregorbcd62532010-11-08 15:20:28 +00002561 T1,
2562 false,
2563 Found)) {
2564 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2565 cv2T2 = Fn->getType();
2566 T2 = cv2T2.getUnqualifiedType();
2567 } else if (!T1->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002568 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2569 return;
2570 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002571 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002572
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002573 // Compute some basic properties of the types and the initializer.
2574 bool isLValueRef = DestType->isLValueReferenceType();
2575 bool isRValueRef = !isLValueRef;
2576 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002577 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002578 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002579 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002580 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
2581 ObjCConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00002582
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002583 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002584 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002585 // "cv2 T2" as follows:
2586 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002587 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002588 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00002589 // Note the analogous bullet points for rvlaue refs to functions. Because
2590 // there are no function rvalues in C++, rvalue refs to functions are treated
2591 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002592 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00002593 bool T1Function = T1->isFunctionType();
2594 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002595 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002596 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002597 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002598 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002599 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002600 // reference-compatible with "cv2 T2," or
2601 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002602 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002603 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002604 // can occur. However, we do pay attention to whether it is a bit-field
2605 // to decide whether we're actually binding to a temporary created from
2606 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002607 if (DerivedToBase)
2608 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002609 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00002610 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002611 else if (ObjCConversion)
2612 Sequence.AddObjCObjectConversionStep(
2613 S.Context.getQualifiedType(T1, T2Quals));
2614
Chandler Carruth04bdce62010-01-12 20:32:25 +00002615 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00002616 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002617 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00002618 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002619 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002620 return;
2621 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002622
2623 // - has a class type (i.e., T2 is a class type), where T1 is not
2624 // reference-related to T2, and can be implicitly converted to an
2625 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2626 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002627 // applicable conversion functions (13.3.1.6) and choosing the best
2628 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00002629 // If we have an rvalue ref to function type here, the rhs must be
2630 // an rvalue.
2631 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2632 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002633 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002634 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00002635 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002636 Sequence);
2637 if (ConvOvlResult == OR_Success)
2638 return;
John McCall0d1da222010-01-12 00:44:57 +00002639 if (ConvOvlResult != OR_No_Viable_Function) {
2640 Sequence.SetOverloadFailure(
2641 InitializationSequence::FK_ReferenceInitOverloadFailed,
2642 ConvOvlResult);
2643 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002644 }
2645 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002646
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002647 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002648 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00002649 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002650 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00002651 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2652 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2653 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002654 Sequence.SetOverloadFailure(
2655 InitializationSequence::FK_ReferenceInitOverloadFailed,
2656 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002657 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002658 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002659 ? (RefRelationship == Sema::Ref_Related
2660 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2661 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2662 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00002663
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002664 return;
2665 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002666
Douglas Gregor92e460e2011-01-20 16:44:54 +00002667 // - If the initializer expression
2668 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
2669 // "cv1 T1" is reference-compatible with "cv2 T2"
2670 // Note: functions are handled below.
2671 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00002672 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002673 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002674 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00002675 (InitCategory.isXValue() ||
2676 (InitCategory.isPRValue() && T2->isRecordType()) ||
2677 (InitCategory.isPRValue() && T2->isArrayType()))) {
2678 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
2679 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002680 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2681 // compiler the freedom to perform a copy here or bind to the
2682 // object, while C++0x requires that we bind directly to the
2683 // object. Hence, we always bind to the object without making an
2684 // extra copy. However, in C++03 requires that we check for the
2685 // presence of a suitable copy constructor:
2686 //
2687 // The constructor that would be used to make the copy shall
2688 // be callable whether or not the copy is actually done.
Francois Pichet687aaf02010-12-31 10:43:42 +00002689 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().Microsoft)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002690 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002691 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002692
Douglas Gregor92e460e2011-01-20 16:44:54 +00002693 if (DerivedToBase)
2694 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
2695 ValueKind);
2696 else if (ObjCConversion)
2697 Sequence.AddObjCObjectConversionStep(
2698 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002699
Douglas Gregor92e460e2011-01-20 16:44:54 +00002700 if (T1Quals != T2Quals)
2701 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002702 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregor92e460e2011-01-20 16:44:54 +00002703 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002704 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00002705 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002706
2707 // - has a class type (i.e., T2 is a class type), where T1 is not
2708 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00002709 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
2710 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregor92e460e2011-01-20 16:44:54 +00002711 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002712 if (RefRelationship == Sema::Ref_Incompatible) {
2713 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2714 Kind, Initializer,
2715 /*AllowRValues=*/true,
2716 Sequence);
2717 if (ConvOvlResult)
2718 Sequence.SetOverloadFailure(
2719 InitializationSequence::FK_ReferenceInitOverloadFailed,
2720 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002721
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002722 return;
2723 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002724
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002725 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2726 return;
2727 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002728
2729 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002730 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002731 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002732 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00002733
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002734 // Determine whether we are allowed to call explicit constructors or
2735 // explicit conversion operators.
2736 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00002737
2738 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2739
2740 if (S.TryImplicitConversion(Sequence, TempEntity, Initializer,
2741 /*SuppressUserConversions*/ false,
2742 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00002743 /*FIXME:InOverloadResolution=*/false,
2744 /*CStyle=*/Kind.isCStyleOrFunctionalCast())) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002745 // FIXME: Use the conversion function set stored in ICS to turn
2746 // this into an overloading ambiguity diagnostic. However, we need
2747 // to keep that set as an OverloadCandidateSet rather than as some
2748 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002749 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2750 Sequence.SetOverloadFailure(
2751 InitializationSequence::FK_ReferenceInitOverloadFailed,
2752 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00002753 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2754 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00002755 else
2756 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002757 return;
2758 }
2759
2760 // [...] If T1 is reference-related to T2, cv1 must be the
2761 // same cv-qualification as, or greater cv-qualification
2762 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002763 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2764 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002765 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00002766 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002767 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2768 return;
2769 }
2770
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002771 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002772 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002773 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002774 InitCategory.isLValue()) {
2775 Sequence.SetFailed(
2776 InitializationSequence::FK_RValueReferenceBindingToLValue);
2777 return;
2778 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002779
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002780 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2781 return;
2782}
2783
2784/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002785/// (C++ [dcl.init.string], C99 6.7.8).
2786static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002787 const InitializedEntity &Entity,
2788 const InitializationKind &Kind,
2789 Expr *Initializer,
2790 InitializationSequence &Sequence) {
Eli Friedman78275202009-12-19 08:11:05 +00002791 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregor1b303932009-12-22 15:35:07 +00002792 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002793}
2794
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002795/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2796/// enumerates the constructors of the initialized entity and performs overload
2797/// resolution to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002798static void TryConstructorInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002799 const InitializedEntity &Entity,
2800 const InitializationKind &Kind,
2801 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002802 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002803 InitializationSequence &Sequence) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002804 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002805
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002806 // Build the candidate set directly in the initialization sequence
2807 // structure, so that it will persist if we fail.
2808 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2809 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002810
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002811 // Determine whether we are allowed to call explicit constructors or
2812 // explicit conversion operators.
2813 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2814 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002815 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregord9848152010-04-26 14:36:57 +00002816
2817 // The type we're constructing needs to be complete.
2818 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002819 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregord9848152010-04-26 14:36:57 +00002820 return;
2821 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002822
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002823 // The type we're converting to is a class type. Enumerate its constructors
2824 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002825 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002826 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002827 CXXRecordDecl *DestRecordDecl
2828 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002829
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002830 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002831 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002832 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002833 NamedDecl *D = *Con;
2834 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00002835 bool SuppressUserConversions = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002836
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002837 // Find the constructor (which may be a template).
2838 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002839 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002840 if (ConstructorTmpl)
2841 Constructor = cast<CXXConstructorDecl>(
2842 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorc779e992010-04-24 20:54:38 +00002843 else {
John McCalla0296f72010-03-19 07:35:19 +00002844 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorc779e992010-04-24 20:54:38 +00002845
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002846 // If we're performing copy initialization using a copy constructor, we
Douglas Gregorc779e992010-04-24 20:54:38 +00002847 // suppress user-defined conversions on the arguments.
2848 // FIXME: Move constructors?
2849 if (Kind.getKind() == InitializationKind::IK_Copy &&
2850 Constructor->isCopyConstructor())
2851 SuppressUserConversions = true;
2852 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002853
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002854 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002855 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002856 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002857 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002858 /*ExplicitArgs*/ 0,
Douglas Gregorc779e992010-04-24 20:54:38 +00002859 Args, NumArgs, CandidateSet,
2860 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002861 else
John McCalla0296f72010-03-19 07:35:19 +00002862 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregorc779e992010-04-24 20:54:38 +00002863 Args, NumArgs, CandidateSet,
2864 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002865 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002866 }
2867
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002868 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002869
2870 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002871 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002872 if (OverloadingResult Result
John McCall5c32be02010-08-24 20:38:10 +00002873 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002874 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002875 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002876 Result);
2877 return;
2878 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002879
2880 // C++0x [dcl.init]p6:
2881 // If a program calls for the default initialization of an object
2882 // of a const-qualified type T, T shall be a class type with a
2883 // user-provided default constructor.
2884 if (Kind.getKind() == InitializationKind::IK_Default &&
2885 Entity.getType().isConstQualified() &&
2886 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2887 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2888 return;
2889 }
2890
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002891 // Add the constructor initialization step. Any cv-qualification conversion is
2892 // subsumed by the initialization.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002893 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002894 cast<CXXConstructorDecl>(Best->Function),
John McCalla0296f72010-03-19 07:35:19 +00002895 Best->FoundDecl.getAccess(),
Douglas Gregore1314a62009-12-18 05:02:21 +00002896 DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002897}
2898
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002899/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002900static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002901 const InitializedEntity &Entity,
2902 const InitializationKind &Kind,
2903 InitializationSequence &Sequence) {
2904 // C++ [dcl.init]p5:
2905 //
2906 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00002907 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002908
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002909 // -- if T is an array type, then each element is value-initialized;
2910 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2911 T = AT->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002912
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002913 if (const RecordType *RT = T->getAs<RecordType>()) {
2914 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2915 // -- if T is a class type (clause 9) with a user-declared
2916 // constructor (12.1), then the default constructor for T is
2917 // called (and the initialization is ill-formed if T has no
2918 // accessible default constructor);
2919 //
2920 // FIXME: we really want to refer to a single subobject of the array,
2921 // but Entity doesn't have a way to capture that (yet).
2922 if (ClassDecl->hasUserDeclaredConstructor())
2923 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002924
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002925 // -- if T is a (possibly cv-qualified) non-union class type
2926 // without a user-provided constructor, then the object is
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002927 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002928 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00002929 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00002930 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002931 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002932 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002933 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002934 }
2935 }
2936
Douglas Gregor1b303932009-12-22 15:35:07 +00002937 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002938 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2939}
2940
Douglas Gregor85dabae2009-12-16 01:38:02 +00002941/// \brief Attempt default initialization (C++ [dcl.init]p6).
2942static void TryDefaultInitialization(Sema &S,
2943 const InitializedEntity &Entity,
2944 const InitializationKind &Kind,
2945 InitializationSequence &Sequence) {
2946 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002947
Douglas Gregor85dabae2009-12-16 01:38:02 +00002948 // C++ [dcl.init]p6:
2949 // To default-initialize an object of type T means:
2950 // - if T is an array type, each element is default-initialized;
Douglas Gregor1b303932009-12-22 15:35:07 +00002951 QualType DestType = Entity.getType();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002952 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2953 DestType = Array->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002954
Douglas Gregor85dabae2009-12-16 01:38:02 +00002955 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2956 // constructor for T is called (and the initialization is ill-formed if
2957 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00002958 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00002959 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
2960 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00002961 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002962
Douglas Gregor85dabae2009-12-16 01:38:02 +00002963 // - otherwise, no initialization is performed.
2964 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002965
Douglas Gregor85dabae2009-12-16 01:38:02 +00002966 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002967 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00002968 // default constructor.
Douglas Gregore6565622010-02-09 07:26:29 +00002969 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor85dabae2009-12-16 01:38:02 +00002970 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2971}
2972
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002973/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2974/// which enumerates all conversion functions and performs overload resolution
2975/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002976static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002977 const InitializedEntity &Entity,
2978 const InitializationKind &Kind,
2979 Expr *Initializer,
2980 InitializationSequence &Sequence) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002981 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002982
Douglas Gregor1b303932009-12-22 15:35:07 +00002983 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002984 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2985 QualType SourceType = Initializer->getType();
2986 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2987 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002988
Douglas Gregor540c3b02009-12-14 17:27:33 +00002989 // Build the candidate set directly in the initialization sequence
2990 // structure, so that it will persist if we fail.
2991 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2992 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002993
Douglas Gregor540c3b02009-12-14 17:27:33 +00002994 // Determine whether we are allowed to call explicit constructors or
2995 // explicit conversion operators.
2996 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002997
Douglas Gregor540c3b02009-12-14 17:27:33 +00002998 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2999 // The type we're converting to is a class type. Enumerate its constructors
3000 // to see if there is a suitable conversion.
3001 CXXRecordDecl *DestRecordDecl
3002 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003003
Douglas Gregord9848152010-04-26 14:36:57 +00003004 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003005 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00003006 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003007 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00003008 Con != ConEnd; ++Con) {
3009 NamedDecl *D = *Con;
3010 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003011
Douglas Gregord9848152010-04-26 14:36:57 +00003012 // Find the constructor (which may be a template).
3013 CXXConstructorDecl *Constructor = 0;
3014 FunctionTemplateDecl *ConstructorTmpl
3015 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003016 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00003017 Constructor = cast<CXXConstructorDecl>(
3018 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00003019 else
Douglas Gregord9848152010-04-26 14:36:57 +00003020 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003021
Douglas Gregord9848152010-04-26 14:36:57 +00003022 if (!Constructor->isInvalidDecl() &&
3023 Constructor->isConvertingConstructor(AllowExplicit)) {
3024 if (ConstructorTmpl)
3025 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3026 /*ExplicitArgs*/ 0,
3027 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003028 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003029 else
3030 S.AddOverloadCandidate(Constructor, FoundDecl,
3031 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003032 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003033 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003034 }
Douglas Gregord9848152010-04-26 14:36:57 +00003035 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003036 }
Eli Friedman78275202009-12-19 08:11:05 +00003037
3038 SourceLocation DeclLoc = Initializer->getLocStart();
3039
Douglas Gregor540c3b02009-12-14 17:27:33 +00003040 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3041 // The type we're converting from is a class type, enumerate its conversion
3042 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00003043
Eli Friedman4afe9a32009-12-20 22:12:03 +00003044 // We can only enumerate the conversion functions for a complete type; if
3045 // the type isn't complete, simply skip this step.
3046 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3047 CXXRecordDecl *SourceRecordDecl
3048 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003049
John McCallad371252010-01-20 00:46:10 +00003050 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00003051 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003052 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003053 E = Conversions->end();
Eli Friedman4afe9a32009-12-20 22:12:03 +00003054 I != E; ++I) {
3055 NamedDecl *D = *I;
3056 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3057 if (isa<UsingShadowDecl>(D))
3058 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003059
Eli Friedman4afe9a32009-12-20 22:12:03 +00003060 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3061 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003062 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003063 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003064 else
John McCallda4458e2010-03-31 01:36:47 +00003065 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003066
Eli Friedman4afe9a32009-12-20 22:12:03 +00003067 if (AllowExplicit || !Conv->isExplicit()) {
3068 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003069 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003070 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003071 CandidateSet);
3072 else
John McCalla0296f72010-03-19 07:35:19 +00003073 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003074 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003075 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003076 }
3077 }
3078 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003079
3080 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003081 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003082 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003083 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003084 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003085 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00003086 Result);
3087 return;
3088 }
John McCall0d1da222010-01-12 00:44:57 +00003089
Douglas Gregor540c3b02009-12-14 17:27:33 +00003090 FunctionDecl *Function = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00003091 S.MarkDeclarationReferenced(DeclLoc, Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003092
Douglas Gregor540c3b02009-12-14 17:27:33 +00003093 if (isa<CXXConstructorDecl>(Function)) {
3094 // Add the user-defined conversion step. Any cv-qualification conversion is
3095 // subsumed by the initialization.
John McCalla0296f72010-03-19 07:35:19 +00003096 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003097 return;
3098 }
3099
3100 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003101 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003102 if (ConvType->getAs<RecordType>()) {
3103 // If we're converting to a class type, there may be an copy if
3104 // the resulting temporary object (possible to create an object of
3105 // a base class type). That copy is not a separate conversion, so
3106 // we just make a note of the actual destination type (possibly a
3107 // base class of the type returned by the conversion function) and
3108 // let the user-defined conversion step handle the conversion.
3109 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3110 return;
3111 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003112
Douglas Gregor5ab11652010-04-17 22:01:05 +00003113 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003114
Douglas Gregor5ab11652010-04-17 22:01:05 +00003115 // If the conversion following the call to the conversion function
3116 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003117 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3118 Best->FinalConversion.Third) {
3119 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003120 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003121 ICS.Standard = Best->FinalConversion;
3122 Sequence.AddConversionSequenceStep(ICS, DestType);
3123 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003124}
3125
Douglas Gregore2f943b2011-02-22 18:29:51 +00003126/// \brief Determine whether we have compatible array types for the
3127/// purposes of GNU by-copy array initialization.
3128static bool hasCompatibleArrayTypes(ASTContext &Context,
3129 const ArrayType *Dest,
3130 const ArrayType *Source) {
3131 // If the source and destination array types are equivalent, we're
3132 // done.
3133 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3134 return true;
3135
3136 // Make sure that the element types are the same.
3137 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3138 return false;
3139
3140 // The only mismatch we allow is when the destination is an
3141 // incomplete array type and the source is a constant array type.
3142 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3143}
3144
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003145InitializationSequence::InitializationSequence(Sema &S,
3146 const InitializedEntity &Entity,
3147 const InitializationKind &Kind,
3148 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003149 unsigned NumArgs)
3150 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003151 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003152
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003153 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003154 // The semantics of initializers are as follows. The destination type is
3155 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003156 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003157 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003158 // parenthesized list of expressions.
Douglas Gregor1b303932009-12-22 15:35:07 +00003159 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003160
3161 if (DestType->isDependentType() ||
3162 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3163 SequenceKind = DependentSequence;
3164 return;
3165 }
3166
John McCalled75c092010-12-07 22:54:16 +00003167 for (unsigned I = 0; I != NumArgs; ++I)
John Wiegley01296292011-04-08 18:41:53 +00003168 if (Args[I]->getObjectKind() == OK_ObjCProperty) {
3169 ExprResult Result = S.ConvertPropertyForRValue(Args[I]);
3170 if (Result.isInvalid()) {
3171 SetFailed(FK_ConversionFromPropertyFailed);
3172 return;
3173 }
3174 Args[I] = Result.take();
3175 }
John McCalled75c092010-12-07 22:54:16 +00003176
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003177 QualType SourceType;
3178 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003179 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003180 Initializer = Args[0];
3181 if (!isa<InitListExpr>(Initializer))
3182 SourceType = Initializer->getType();
3183 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003184
3185 // - If the initializer is a braced-init-list, the object is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003186 // list-initialized (8.5.4).
3187 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3188 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00003189 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003190 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003191
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003192 // - If the destination type is a reference type, see 8.5.3.
3193 if (DestType->isReferenceType()) {
3194 // C++0x [dcl.init.ref]p1:
3195 // A variable declared to be a T& or T&&, that is, "reference to type T"
3196 // (8.3.2), shall be initialized by an object, or function, of type T or
3197 // by an object that can be converted into a T.
3198 // (Therefore, multiple arguments are not permitted.)
3199 if (NumArgs != 1)
3200 SetFailed(FK_TooManyInitsForReference);
3201 else
3202 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3203 return;
3204 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003205
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003206 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003207 if (Kind.getKind() == InitializationKind::IK_Value ||
3208 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003209 TryValueInitialization(S, Entity, Kind, *this);
3210 return;
3211 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003212
Douglas Gregor85dabae2009-12-16 01:38:02 +00003213 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00003214 if (Kind.getKind() == InitializationKind::IK_Default) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003215 TryDefaultInitialization(S, Entity, Kind, *this);
3216 return;
3217 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003218
John McCall66884dd2011-02-21 07:22:22 +00003219 // - If the destination type is an array of characters, an array of
3220 // char16_t, an array of char32_t, or an array of wchar_t, and the
3221 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003222 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003223 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00003224 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3225 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
John McCall66884dd2011-02-21 07:22:22 +00003226 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3227 return;
3228 }
3229
Douglas Gregore2f943b2011-02-22 18:29:51 +00003230 // Note: as an GNU C extension, we allow initialization of an
3231 // array from a compound literal that creates an array of the same
3232 // type, so long as the initializer has no side effects.
3233 if (!S.getLangOptions().CPlusPlus && Initializer &&
3234 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3235 Initializer->getType()->isArrayType()) {
3236 const ArrayType *SourceAT
3237 = Context.getAsArrayType(Initializer->getType());
3238 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
3239 SetFailed(FK_ArrayTypeMismatch);
3240 else if (Initializer->HasSideEffects(S.Context))
3241 SetFailed(FK_NonConstantArrayInit);
3242 else {
3243 setSequenceKind(ArrayInit);
3244 AddArrayInitStep(DestType);
3245 }
3246 } else if (DestAT->getElementType()->isAnyCharacterType())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003247 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3248 else
3249 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003250
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003251 return;
3252 }
Eli Friedman78275202009-12-19 08:11:05 +00003253
3254 // Handle initialization in C
3255 if (!S.getLangOptions().CPlusPlus) {
3256 setSequenceKind(CAssignment);
3257 AddCAssignmentStep(DestType);
3258 return;
3259 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003260
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003261 // - If the destination type is a (possibly cv-qualified) class type:
3262 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003263 // - If the initialization is direct-initialization, or if it is
3264 // copy-initialization where the cv-unqualified version of the
3265 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003266 // class of the destination, constructors are considered. [...]
3267 if (Kind.getKind() == InitializationKind::IK_Direct ||
3268 (Kind.getKind() == InitializationKind::IK_Copy &&
3269 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3270 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003271 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregor1b303932009-12-22 15:35:07 +00003272 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003273 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003274 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003275 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003276 // used) to a derived class thereof are enumerated as described in
3277 // 13.3.1.4, and the best one is chosen through overload resolution
3278 // (13.3).
3279 else
3280 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3281 return;
3282 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003283
Douglas Gregor85dabae2009-12-16 01:38:02 +00003284 if (NumArgs > 1) {
3285 SetFailed(FK_TooManyInitsForScalar);
3286 return;
3287 }
3288 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003289
3290 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003291 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003292 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003293 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3294 return;
3295 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003296
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003297 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00003298 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003299 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003300 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003301 // destination type; no user-defined conversions are considered.
John McCallec6f4e92010-06-04 02:29:22 +00003302 if (S.TryImplicitConversion(*this, Entity, Initializer,
3303 /*SuppressUserConversions*/ true,
3304 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00003305 /*InOverloadResolution*/ false,
3306 /*CStyle=*/Kind.isCStyleOrFunctionalCast()))
Douglas Gregore81f58e2010-11-08 03:40:48 +00003307 {
Douglas Gregorb491ed32011-02-19 21:32:49 +00003308 DeclAccessPair dap;
3309 if (Initializer->getType() == Context.OverloadTy &&
3310 !S.ResolveAddressOfOverloadedFunction(Initializer
3311 , DestType, false, dap))
Douglas Gregore81f58e2010-11-08 03:40:48 +00003312 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3313 else
3314 SetFailed(InitializationSequence::FK_ConversionFailed);
3315 }
John McCallec6f4e92010-06-04 02:29:22 +00003316 else
3317 setSequenceKind(StandardConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003318}
3319
3320InitializationSequence::~InitializationSequence() {
3321 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3322 StepEnd = Steps.end();
3323 Step != StepEnd; ++Step)
3324 Step->Destroy();
3325}
3326
3327//===----------------------------------------------------------------------===//
3328// Perform initialization
3329//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003330static Sema::AssignmentAction
Douglas Gregore1314a62009-12-18 05:02:21 +00003331getAssignmentAction(const InitializedEntity &Entity) {
3332 switch(Entity.getKind()) {
3333 case InitializedEntity::EK_Variable:
3334 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003335 case InitializedEntity::EK_Exception:
3336 case InitializedEntity::EK_Base:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003337 case InitializedEntity::EK_Delegation:
Douglas Gregore1314a62009-12-18 05:02:21 +00003338 return Sema::AA_Initializing;
3339
3340 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003341 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00003342 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3343 return Sema::AA_Sending;
3344
Douglas Gregore1314a62009-12-18 05:02:21 +00003345 return Sema::AA_Passing;
3346
3347 case InitializedEntity::EK_Result:
3348 return Sema::AA_Returning;
3349
Douglas Gregore1314a62009-12-18 05:02:21 +00003350 case InitializedEntity::EK_Temporary:
3351 // FIXME: Can we tell apart casting vs. converting?
3352 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003353
Douglas Gregore1314a62009-12-18 05:02:21 +00003354 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003355 case InitializedEntity::EK_ArrayElement:
3356 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003357 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003358 return Sema::AA_Initializing;
3359 }
3360
3361 return Sema::AA_Converting;
3362}
3363
Douglas Gregor95562572010-04-24 23:45:46 +00003364/// \brief Whether we should binding a created object as a temporary when
3365/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003366static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003367 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00003368 case InitializedEntity::EK_ArrayElement:
3369 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003370 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003371 case InitializedEntity::EK_New:
3372 case InitializedEntity::EK_Variable:
3373 case InitializedEntity::EK_Base:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003374 case InitializedEntity::EK_Delegation:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003375 case InitializedEntity::EK_VectorElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00003376 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003377 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003378 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003379
Douglas Gregore1314a62009-12-18 05:02:21 +00003380 case InitializedEntity::EK_Parameter:
3381 case InitializedEntity::EK_Temporary:
3382 return true;
3383 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003384
Douglas Gregore1314a62009-12-18 05:02:21 +00003385 llvm_unreachable("missed an InitializedEntity kind?");
3386}
3387
Douglas Gregor95562572010-04-24 23:45:46 +00003388/// \brief Whether the given entity, when initialized with an object
3389/// created for that initialization, requires destruction.
3390static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3391 switch (Entity.getKind()) {
3392 case InitializedEntity::EK_Member:
3393 case InitializedEntity::EK_Result:
3394 case InitializedEntity::EK_New:
3395 case InitializedEntity::EK_Base:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003396 case InitializedEntity::EK_Delegation:
Douglas Gregor95562572010-04-24 23:45:46 +00003397 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003398 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00003399 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003400
Douglas Gregor95562572010-04-24 23:45:46 +00003401 case InitializedEntity::EK_Variable:
3402 case InitializedEntity::EK_Parameter:
3403 case InitializedEntity::EK_Temporary:
3404 case InitializedEntity::EK_ArrayElement:
3405 case InitializedEntity::EK_Exception:
3406 return true;
3407 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003408
3409 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00003410}
3411
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003412/// \brief Make a (potentially elidable) temporary copy of the object
3413/// provided by the given initializer by calling the appropriate copy
3414/// constructor.
3415///
3416/// \param S The Sema object used for type-checking.
3417///
Abramo Bagnara92141d22011-01-27 19:55:10 +00003418/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003419/// the type of the initializer expression or a superclass thereof.
3420///
3421/// \param Enter The entity being initialized.
3422///
3423/// \param CurInit The initializer expression.
3424///
3425/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3426/// is permitted in C++03 (but not C++0x) when binding a reference to
3427/// an rvalue.
3428///
3429/// \returns An expression that copies the initializer expression into
3430/// a temporary object, or an error expression if a copy could not be
3431/// created.
John McCalldadc5752010-08-24 06:29:42 +00003432static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00003433 QualType T,
3434 const InitializedEntity &Entity,
3435 ExprResult CurInit,
3436 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003437 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00003438 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003439 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003440 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003441 Class = cast<CXXRecordDecl>(Record->getDecl());
3442 if (!Class)
3443 return move(CurInit);
3444
Douglas Gregor5d369002011-01-21 18:05:27 +00003445 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003446 // When certain criteria are met, an implementation is allowed to
3447 // omit the copy/move construction of a class object, even if the
3448 // copy/move constructor and/or destructor for the object have
3449 // side effects. [...]
3450 // - when a temporary class object that has not been bound to a
3451 // reference (12.2) would be copied/moved to a class object
3452 // with the same cv-unqualified type, the copy/move operation
3453 // can be omitted by constructing the temporary object
3454 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003455 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003456 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003457 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003458 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003459 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00003460 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003461 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003462 switch (Entity.getKind()) {
3463 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003464 Loc = Entity.getReturnLoc();
3465 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003466
Douglas Gregore1314a62009-12-18 05:02:21 +00003467 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003468 Loc = Entity.getThrowLoc();
3469 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003470
Douglas Gregore1314a62009-12-18 05:02:21 +00003471 case InitializedEntity::EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003472 Loc = Entity.getDecl()->getLocation();
3473 break;
3474
Anders Carlsson0bd52402010-01-24 00:19:41 +00003475 case InitializedEntity::EK_ArrayElement:
3476 case InitializedEntity::EK_Member:
Douglas Gregore1314a62009-12-18 05:02:21 +00003477 case InitializedEntity::EK_Parameter:
Douglas Gregore1314a62009-12-18 05:02:21 +00003478 case InitializedEntity::EK_Temporary:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003479 case InitializedEntity::EK_New:
Douglas Gregore1314a62009-12-18 05:02:21 +00003480 case InitializedEntity::EK_Base:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003481 case InitializedEntity::EK_Delegation:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003482 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003483 case InitializedEntity::EK_BlockElement:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003484 Loc = CurInitExpr->getLocStart();
3485 break;
Douglas Gregore1314a62009-12-18 05:02:21 +00003486 }
Douglas Gregord5c231e2010-04-24 21:09:25 +00003487
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003488 // Make sure that the type we are copying is complete.
Douglas Gregord5c231e2010-04-24 21:09:25 +00003489 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3490 return move(CurInit);
3491
Douglas Gregorf282a762011-01-21 19:38:21 +00003492 // Perform overload resolution using the class's copy/move constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00003493 DeclContext::lookup_iterator Con, ConEnd;
John McCallbc077cf2010-02-08 23:07:23 +00003494 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor52b72822010-07-02 23:12:18 +00003495 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003496 Con != ConEnd; ++Con) {
Douglas Gregorf282a762011-01-21 19:38:21 +00003497 // Only consider copy/move constructors and constructor templates. Per
Douglas Gregorcbd07102010-11-12 03:34:06 +00003498 // C++0x [dcl.init]p16, second bullet to class types, this
3499 // initialization is direct-initialization.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003500 CXXConstructorDecl *Constructor = 0;
3501
3502 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
Douglas Gregorf282a762011-01-21 19:38:21 +00003503 // Handle copy/moveconstructors, only.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003504 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregorf282a762011-01-21 19:38:21 +00003505 !Constructor->isCopyOrMoveConstructor() ||
Douglas Gregorcbd07102010-11-12 03:34:06 +00003506 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003507 continue;
3508
3509 DeclAccessPair FoundDecl
3510 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3511 S.AddOverloadCandidate(Constructor, FoundDecl,
3512 &CurInitExpr, 1, CandidateSet);
3513 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003514 }
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003515
3516 // Handle constructor templates.
3517 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
3518 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregore1314a62009-12-18 05:02:21 +00003519 continue;
John McCalla0296f72010-03-19 07:35:19 +00003520
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003521 Constructor = cast<CXXConstructorDecl>(
3522 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorcbd07102010-11-12 03:34:06 +00003523 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003524 continue;
3525
3526 // FIXME: Do we need to limit this to copy-constructor-like
3527 // candidates?
John McCalla0296f72010-03-19 07:35:19 +00003528 DeclAccessPair FoundDecl
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003529 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
3530 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
3531 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003532 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003533
Douglas Gregore1314a62009-12-18 05:02:21 +00003534 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00003535 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003536 case OR_Success:
3537 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003538
Douglas Gregore1314a62009-12-18 05:02:21 +00003539 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003540 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3541 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3542 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003543 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003544 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003545 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003546 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00003547 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003548 return move(CurInit);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003549
Douglas Gregore1314a62009-12-18 05:02:21 +00003550 case OR_Ambiguous:
3551 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003552 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003553 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003554 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00003555 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003556
Douglas Gregore1314a62009-12-18 05:02:21 +00003557 case OR_Deleted:
3558 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003559 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003560 << CurInitExpr->getSourceRange();
3561 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3562 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00003563 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003564 }
3565
Douglas Gregor5ab11652010-04-17 22:01:05 +00003566 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00003567 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003568 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003569
Anders Carlssona01874b2010-04-21 18:47:17 +00003570 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003571 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003572
3573 if (IsExtraneousCopy) {
3574 // If this is a totally extraneous copy for C++03 reference
3575 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00003576 // expression. We don't generate an (elided) copy operation here
3577 // because doing so would require us to pass down a flag to avoid
3578 // infinite recursion, where each step adds another extraneous,
3579 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003580
Douglas Gregor30b52772010-04-18 07:57:34 +00003581 // Instantiate the default arguments of any extra parameters in
3582 // the selected copy constructor, as if we were going to create a
3583 // proper call to the copy constructor.
3584 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3585 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3586 if (S.RequireCompleteType(Loc, Parm->getType(),
3587 S.PDiag(diag::err_call_incomplete_argument)))
3588 break;
3589
3590 // Build the default argument expression; we don't actually care
3591 // if this succeeds or not, because this routine will complain
3592 // if there was a problem.
3593 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3594 }
3595
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003596 return S.Owned(CurInitExpr);
3597 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003598
Chandler Carruth30141632011-02-25 19:41:05 +00003599 S.MarkDeclarationReferenced(Loc, Constructor);
3600
Douglas Gregor5ab11652010-04-17 22:01:05 +00003601 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003602 // constructor call (we might have derived-to-base conversions, or
3603 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00003604 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00003605 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003606 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003607
Douglas Gregord0ace022010-04-25 00:55:24 +00003608 // Actually perform the constructor call.
3609 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00003610 move_arg(ConstructorArgs),
3611 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00003612 CXXConstructExpr::CK_Complete,
3613 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003614
Douglas Gregord0ace022010-04-25 00:55:24 +00003615 // If we're supposed to bind temporaries, do so.
3616 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3617 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3618 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003619}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003620
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003621void InitializationSequence::PrintInitLocationNote(Sema &S,
3622 const InitializedEntity &Entity) {
3623 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3624 if (Entity.getDecl()->getLocation().isInvalid())
3625 return;
3626
3627 if (Entity.getDecl()->getDeclName())
3628 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3629 << Entity.getDecl()->getDeclName();
3630 else
3631 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3632 }
3633}
3634
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003635ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003636InitializationSequence::Perform(Sema &S,
3637 const InitializedEntity &Entity,
3638 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00003639 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003640 QualType *ResultType) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003641 if (SequenceKind == FailedSequence) {
3642 unsigned NumArgs = Args.size();
3643 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00003644 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003645 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003646
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003647 if (SequenceKind == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003648 // If the declaration is a non-dependent, incomplete array type
3649 // that has an initializer, then its type will be completed once
3650 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00003651 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00003652 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003653 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003654 if (const IncompleteArrayType *ArrayT
3655 = S.Context.getAsIncompleteArrayType(DeclType)) {
3656 // FIXME: We don't currently have the ability to accurately
3657 // compute the length of an initializer list without
3658 // performing full type-checking of the initializer list
3659 // (since we have to determine where braces are implicitly
3660 // introduced and such). So, we fall back to making the array
3661 // type a dependently-sized array type with no specified
3662 // bound.
3663 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3664 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00003665
Douglas Gregor51e77d52009-12-10 17:56:55 +00003666 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00003667 if (DeclaratorDecl *DD = Entity.getDecl()) {
3668 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3669 TypeLoc TL = TInfo->getTypeLoc();
3670 if (IncompleteArrayTypeLoc *ArrayLoc
3671 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3672 Brackets = ArrayLoc->getBracketsRange();
3673 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00003674 }
3675
3676 *ResultType
3677 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3678 /*NumElts=*/0,
3679 ArrayT->getSizeModifier(),
3680 ArrayT->getIndexTypeCVRQualifiers(),
3681 Brackets);
3682 }
3683
3684 }
3685 }
3686
Eli Friedmana553d4a2009-12-22 02:35:53 +00003687 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
John McCalldadc5752010-08-24 06:29:42 +00003688 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003689
Douglas Gregor0ab7af62010-02-05 07:56:11 +00003690 if (Args.size() == 0)
3691 return S.Owned((Expr *)0);
3692
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003693 unsigned NumArgs = Args.size();
3694 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3695 SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003696 (Expr **)Args.release(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003697 NumArgs,
3698 SourceLocation()));
3699 }
3700
Douglas Gregor85dabae2009-12-16 01:38:02 +00003701 if (SequenceKind == NoInitialization)
3702 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003703
Douglas Gregor1b303932009-12-22 15:35:07 +00003704 QualType DestType = Entity.getType().getNonReferenceType();
3705 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00003706 // the same as Entity.getDecl()->getType() in cases involving type merging,
3707 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003708 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003709 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00003710 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003711
John McCalldadc5752010-08-24 06:29:42 +00003712 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003713
Douglas Gregor85dabae2009-12-16 01:38:02 +00003714 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003715
3716 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00003717 // grab the only argument out the Args and place it into the "current"
3718 // initializer.
3719 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003720 case SK_ResolveAddressOfOverloadedFunction:
3721 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003722 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003723 case SK_CastDerivedToBaseLValue:
3724 case SK_BindReference:
3725 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003726 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00003727 case SK_UserConversion:
3728 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003729 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003730 case SK_QualificationConversionRValue:
3731 case SK_ConversionSequence:
3732 case SK_ListInitialization:
3733 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003734 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003735 case SK_ObjCObjectConversion:
3736 case SK_ArrayInit: {
Douglas Gregore1314a62009-12-18 05:02:21 +00003737 assert(Args.size() == 1);
John Wiegley01296292011-04-08 18:41:53 +00003738 CurInit = Args.get()[0];
3739 if (!CurInit.get()) return ExprError();
John McCall34376a62010-12-04 03:47:34 +00003740
3741 // Read from a property when initializing something with it.
John Wiegley01296292011-04-08 18:41:53 +00003742 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
3743 CurInit = S.ConvertPropertyForRValue(CurInit.take());
3744 if (CurInit.isInvalid())
3745 return ExprError();
3746 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003747 break;
John McCall34376a62010-12-04 03:47:34 +00003748 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003749
Douglas Gregore1314a62009-12-18 05:02:21 +00003750 case SK_ConstructorInitialization:
3751 case SK_ZeroInitialization:
3752 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003753 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003754
3755 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003756 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003757 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003758 for (step_iterator Step = step_begin(), StepEnd = step_end();
3759 Step != StepEnd; ++Step) {
3760 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003761 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003762
John Wiegley01296292011-04-08 18:41:53 +00003763 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003764
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003765 switch (Step->Kind) {
3766 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003767 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003768 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00003769 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00003770 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00003771 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00003772 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00003773 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003774 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003775
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003776 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003777 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003778 case SK_CastDerivedToBaseLValue: {
3779 // We have a derived-to-base cast that produces either an rvalue or an
3780 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003781
John McCallcf142162010-08-07 06:22:56 +00003782 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00003783
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003784 // Casts to inaccessible base classes are allowed with C-style casts.
3785 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3786 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00003787 CurInit.get()->getLocStart(),
3788 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00003789 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00003790 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003791
Douglas Gregor88d292c2010-05-13 16:44:06 +00003792 if (S.BasePathInvolvesVirtualBase(BasePath)) {
3793 QualType T = SourceType;
3794 if (const PointerType *Pointer = T->getAs<PointerType>())
3795 T = Pointer->getPointeeType();
3796 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00003797 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00003798 cast<CXXRecordDecl>(RecordTy->getDecl()));
3799 }
3800
John McCall2536c6d2010-08-25 10:28:54 +00003801 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003802 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003803 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003804 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003805 VK_XValue :
3806 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00003807 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3808 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00003809 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00003810 CurInit.get(),
3811 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003812 break;
3813 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003814
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003815 case SK_BindReference:
John Wiegley01296292011-04-08 18:41:53 +00003816 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003817 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3818 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00003819 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003820 << BitField->getDeclName()
John Wiegley01296292011-04-08 18:41:53 +00003821 << CurInit.get()->getSourceRange();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003822 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00003823 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003824 }
Anders Carlssona91be642010-01-29 02:47:33 +00003825
John Wiegley01296292011-04-08 18:41:53 +00003826 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00003827 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003828 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3829 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00003830 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003831 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00003832 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003833 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003834
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003835 // Reference binding does not have any corresponding ASTs.
3836
3837 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00003838 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00003839 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003840
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003841 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003842
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003843 case SK_BindReferenceToTemporary:
Anders Carlsson3b227bd2010-02-03 16:38:03 +00003844 // Reference binding does not have any corresponding ASTs.
3845
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003846 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00003847 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00003848 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003849
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003850 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003851
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003852 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003853 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003854 /*IsExtraneousCopy=*/true);
3855 break;
3856
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003857 case SK_UserConversion: {
3858 // We have a user-defined conversion that invokes either a constructor
3859 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00003860 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00003861 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00003862 FunctionDecl *Fn = Step->Function.Function;
3863 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor95562572010-04-24 23:45:46 +00003864 bool CreatedObject = false;
Douglas Gregor031296e2010-03-25 00:20:38 +00003865 bool IsLvalue = false;
John McCall760af172010-02-01 03:16:54 +00003866 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003867 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00003868 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley01296292011-04-08 18:41:53 +00003869 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003870 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00003871
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003872 // Determine the arguments required to actually perform the constructor
3873 // call.
John Wiegley01296292011-04-08 18:41:53 +00003874 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003875 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00003876 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003877 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003878 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003879
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003880 // Build the an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003881 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00003882 move_arg(ConstructorArgs),
3883 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00003884 CXXConstructExpr::CK_Complete,
3885 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003886 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003887 return ExprError();
John McCall760af172010-02-01 03:16:54 +00003888
Anders Carlssona01874b2010-04-21 18:47:17 +00003889 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00003890 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00003891 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003892
John McCalle3027922010-08-25 11:45:40 +00003893 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00003894 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3895 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3896 S.IsDerivedFrom(SourceType, Class))
3897 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003898
Douglas Gregor95562572010-04-24 23:45:46 +00003899 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003900 } else {
3901 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00003902 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregor031296e2010-03-25 00:20:38 +00003903 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John Wiegley01296292011-04-08 18:41:53 +00003904 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00003905 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00003906 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003907
3908 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003909 // derived-to-base conversion? I believe the answer is "no", because
3910 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00003911 ExprResult CurInitExprRes =
3912 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
3913 FoundFn, Conversion);
3914 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003915 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00003916 CurInit = move(CurInitExprRes);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003917
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003918 // Build the actual call to the conversion function.
John Wiegley01296292011-04-08 18:41:53 +00003919 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003920 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00003921 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003922
John McCalle3027922010-08-25 11:45:40 +00003923 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003924
Douglas Gregor95562572010-04-24 23:45:46 +00003925 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003926 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003927
3928 bool RequiresCopy = !IsCopy &&
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003929 getKind() != InitializationSequence::ReferenceBinding;
3930 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00003931 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00003932 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00003933 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00003934 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003935 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00003936 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00003937 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00003938 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley01296292011-04-08 18:41:53 +00003939 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
3940 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00003941 }
3942 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003943
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003944 // FIXME: xvalues
John McCallcf142162010-08-07 06:22:56 +00003945 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00003946 CurInit.get()->getType(),
3947 CastKind, CurInit.get(), 0,
John McCall2536c6d2010-08-25 10:28:54 +00003948 IsLvalue ? VK_LValue : VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003949
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003950 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003951 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
3952 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003953
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003954 break;
3955 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003956
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003957 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003958 case SK_QualificationConversionXValue:
3959 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003960 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00003961 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003962 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003963 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003964 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003965 VK_XValue :
3966 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00003967 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003968 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003969 }
3970
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003971 case SK_ConversionSequence: {
John Wiegley01296292011-04-08 18:41:53 +00003972 ExprResult CurInitExprRes =
3973 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
3974 getAssignmentAction(Entity),
3975 Kind.isCStyleOrFunctionalCast());
3976 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003977 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00003978 CurInit = move(CurInitExprRes);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003979 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003980 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003981
Douglas Gregor51e77d52009-12-10 17:56:55 +00003982 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00003983 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Douglas Gregor51e77d52009-12-10 17:56:55 +00003984 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00003985 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallfaf5fb42010-08-26 23:41:50 +00003986 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003987
3988 CurInit.release();
3989 CurInit = S.Owned(InitList);
3990 break;
3991 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003992
3993 case SK_ConstructorInitialization: {
Douglas Gregorb33eed02010-04-16 22:09:46 +00003994 unsigned NumArgs = Args.size();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003995 CXXConstructorDecl *Constructor
John McCalla0296f72010-03-19 07:35:19 +00003996 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003997
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003998 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00003999 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanianda2da9c2010-07-21 18:40:47 +00004000 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4001 ? Kind.getEqualLoc()
4002 : Kind.getLocation();
Chandler Carruthc9262402010-08-23 07:55:51 +00004003
4004 if (Kind.getKind() == InitializationKind::IK_Default) {
4005 // Force even a trivial, implicit default constructor to be
4006 // semantically checked. We do this explicitly because we don't build
4007 // the definition for completely trivial constructors.
4008 CXXRecordDecl *ClassDecl = Constructor->getParent();
4009 assert(ClassDecl && "No parent class for constructor.");
4010 if (Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
4011 ClassDecl->hasTrivialConstructor() && !Constructor->isUsed(false))
4012 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4013 }
4014
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004015 // Determine the arguments required to actually perform the constructor
4016 // call.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004017 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004018 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004019 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004020
4021
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004022 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregorb33eed02010-04-16 22:09:46 +00004023 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004024 (Kind.getKind() == InitializationKind::IK_Direct ||
4025 Kind.getKind() == InitializationKind::IK_Value)) {
4026 // An explicitly-constructed temporary, e.g., X(1, 2).
4027 unsigned NumExprs = ConstructorArgs.size();
4028 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian3fd2a552010-07-21 18:31:47 +00004029 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00004030 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004031
Douglas Gregor2b88c112010-09-08 00:15:04 +00004032 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4033 if (!TSInfo)
4034 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004035
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004036 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4037 Constructor,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004038 TSInfo,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004039 Exprs,
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004040 NumExprs,
Chandler Carruth01718152010-10-25 08:47:36 +00004041 Kind.getParenRange(),
Douglas Gregor199db362010-04-27 20:36:09 +00004042 ConstructorInitRequiresZeroInit));
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004043 } else {
4044 CXXConstructExpr::ConstructionKind ConstructKind =
4045 CXXConstructExpr::CK_Complete;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004046
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004047 if (Entity.getKind() == InitializedEntity::EK_Base) {
4048 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004049 CXXConstructExpr::CK_VirtualBase :
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004050 CXXConstructExpr::CK_NonVirtualBase;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004051 }
4052
Chandler Carruth01718152010-10-25 08:47:36 +00004053 // Only get the parenthesis range if it is a direct construction.
4054 SourceRange parenRange =
4055 Kind.getKind() == InitializationKind::IK_Direct ?
4056 Kind.getParenRange() : SourceRange();
4057
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004058 // If the entity allows NRVO, mark the construction as elidable
4059 // unconditionally.
4060 if (Entity.allowsNRVO())
4061 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4062 Constructor, /*Elidable=*/true,
4063 move_arg(ConstructorArgs),
4064 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004065 ConstructKind,
4066 parenRange);
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004067 else
4068 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004069 Constructor,
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004070 move_arg(ConstructorArgs),
4071 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004072 ConstructKind,
4073 parenRange);
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004074 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004075 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004076 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004077
4078 // Only check access if all of that succeeded.
Anders Carlssona01874b2010-04-21 18:47:17 +00004079 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004080 Step->Function.FoundDecl.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004081 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004082
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004083 if (shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00004084 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004085
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004086 break;
4087 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004088
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004089 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004090 step_iterator NextStep = Step;
4091 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004092 if (NextStep != StepEnd &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004093 NextStep->Kind == SK_ConstructorInitialization) {
4094 // The need for zero-initialization is recorded directly into
4095 // the call to the object's constructor within the next step.
4096 ConstructorInitRequiresZeroInit = true;
4097 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4098 S.getLangOptions().CPlusPlus &&
4099 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00004100 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4101 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004102 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004103 Kind.getRange().getBegin());
4104
4105 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4106 TSInfo->getType().getNonLValueExprType(S.Context),
4107 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004108 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004109 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004110 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004111 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004112 break;
4113 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004114
4115 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00004116 QualType SourceType = CurInit.get()->getType();
4117 ExprResult Result = move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004118 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00004119 S.CheckSingleAssignmentConstraints(Step->Type, Result);
4120 if (Result.isInvalid())
4121 return ExprError();
4122 CurInit = move(Result);
Douglas Gregor96596c92009-12-22 07:24:36 +00004123
4124 // If this is a call, allow conversion to a transparent union.
John Wiegley01296292011-04-08 18:41:53 +00004125 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregor96596c92009-12-22 07:24:36 +00004126 if (ConvTy != Sema::Compatible &&
4127 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley01296292011-04-08 18:41:53 +00004128 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00004129 == Sema::Compatible)
4130 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00004131 if (CurInitExprRes.isInvalid())
4132 return ExprError();
4133 CurInit = move(CurInitExprRes);
Douglas Gregor96596c92009-12-22 07:24:36 +00004134
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004135 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00004136 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4137 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00004138 CurInit.get(),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004139 getAssignmentAction(Entity),
4140 &Complained)) {
4141 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004142 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004143 } else if (Complained)
4144 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00004145 break;
4146 }
Eli Friedman78275202009-12-19 08:11:05 +00004147
4148 case SK_StringInit: {
4149 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00004150 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00004151 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00004152 break;
4153 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004154
4155 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00004156 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004157 CK_ObjCObjectLValueCast,
John Wiegley01296292011-04-08 18:41:53 +00004158 S.CastCategory(CurInit.get()));
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004159 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004160
4161 case SK_ArrayInit:
4162 // Okay: we checked everything before creating this step. Note that
4163 // this is a GNU extension.
4164 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00004165 << Step->Type << CurInit.get()->getType()
4166 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00004167
4168 // If the destination type is an incomplete array type, update the
4169 // type accordingly.
4170 if (ResultType) {
4171 if (const IncompleteArrayType *IncompleteDest
4172 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4173 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00004174 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00004175 *ResultType = S.Context.getConstantArrayType(
4176 IncompleteDest->getElementType(),
4177 ConstantSource->getSize(),
4178 ArrayType::Normal, 0);
4179 }
4180 }
4181 }
4182
4183 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004184 }
4185 }
John McCall1f425642010-11-11 03:21:53 +00004186
4187 // Diagnose non-fatal problems with the completed initialization.
4188 if (Entity.getKind() == InitializedEntity::EK_Member &&
4189 cast<FieldDecl>(Entity.getDecl())->isBitField())
4190 S.CheckBitFieldInitialization(Kind.getLocation(),
4191 cast<FieldDecl>(Entity.getDecl()),
4192 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004193
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004194 return move(CurInit);
4195}
4196
4197//===----------------------------------------------------------------------===//
4198// Diagnose initialization failures
4199//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004200bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004201 const InitializedEntity &Entity,
4202 const InitializationKind &Kind,
4203 Expr **Args, unsigned NumArgs) {
4204 if (SequenceKind != FailedSequence)
4205 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004206
Douglas Gregor1b303932009-12-22 15:35:07 +00004207 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004208 switch (Failure) {
4209 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004210 // FIXME: Customize for the initialized entity?
4211 if (NumArgs == 0)
4212 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4213 << DestType.getNonReferenceType();
4214 else // FIXME: diagnostic below could be better!
4215 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4216 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004217 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004218
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004219 case FK_ArrayNeedsInitList:
4220 case FK_ArrayNeedsInitListOrStringLiteral:
4221 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4222 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4223 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004224
Douglas Gregore2f943b2011-02-22 18:29:51 +00004225 case FK_ArrayTypeMismatch:
4226 case FK_NonConstantArrayInit:
4227 S.Diag(Kind.getLocation(),
4228 (Failure == FK_ArrayTypeMismatch
4229 ? diag::err_array_init_different_type
4230 : diag::err_array_init_non_constant_array))
4231 << DestType.getNonReferenceType()
4232 << Args[0]->getType()
4233 << Args[0]->getSourceRange();
4234 break;
4235
John McCall16df1e52010-03-30 21:47:33 +00004236 case FK_AddressOfOverloadFailed: {
4237 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004238 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004239 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00004240 true,
4241 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004242 break;
John McCall16df1e52010-03-30 21:47:33 +00004243 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004244
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004245 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00004246 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004247 switch (FailedOverloadResult) {
4248 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00004249 if (Failure == FK_UserConversionOverloadFailed)
4250 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4251 << Args[0]->getType() << DestType
4252 << Args[0]->getSourceRange();
4253 else
4254 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4255 << DestType << Args[0]->getType()
4256 << Args[0]->getSourceRange();
4257
John McCall5c32be02010-08-24 20:38:10 +00004258 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004259 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004260
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004261 case OR_No_Viable_Function:
4262 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4263 << Args[0]->getType() << DestType.getNonReferenceType()
4264 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004265 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004266 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004267
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004268 case OR_Deleted: {
4269 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4270 << Args[0]->getType() << DestType.getNonReferenceType()
4271 << Args[0]->getSourceRange();
4272 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004273 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00004274 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4275 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004276 if (Ovl == OR_Deleted) {
4277 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4278 << Best->Function->isDeleted();
4279 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004280 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004281 }
4282 break;
4283 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004284
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004285 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004286 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004287 break;
4288 }
4289 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004290
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004291 case FK_NonConstLValueReferenceBindingToTemporary:
4292 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004293 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004294 Failure == FK_NonConstLValueReferenceBindingToTemporary
4295 ? diag::err_lvalue_reference_bind_to_temporary
4296 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00004297 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004298 << DestType.getNonReferenceType()
4299 << Args[0]->getType()
4300 << Args[0]->getSourceRange();
4301 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004302
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004303 case FK_RValueReferenceBindingToLValue:
4304 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00004305 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004306 << Args[0]->getSourceRange();
4307 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004308
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004309 case FK_ReferenceInitDropsQualifiers:
4310 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4311 << DestType.getNonReferenceType()
4312 << Args[0]->getType()
4313 << Args[0]->getSourceRange();
4314 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004315
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004316 case FK_ReferenceInitFailed:
4317 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4318 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00004319 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004320 << Args[0]->getType()
4321 << Args[0]->getSourceRange();
4322 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004323
Douglas Gregorb491ed32011-02-19 21:32:49 +00004324 case FK_ConversionFailed: {
4325 QualType FromType = Args[0]->getType();
Douglas Gregore1314a62009-12-18 05:02:21 +00004326 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4327 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004328 << DestType
John McCall086a4642010-11-24 05:12:34 +00004329 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00004330 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004331 << Args[0]->getSourceRange();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004332 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00004333 }
John Wiegley01296292011-04-08 18:41:53 +00004334
4335 case FK_ConversionFromPropertyFailed:
4336 // No-op. This error has already been reported.
4337 break;
4338
Douglas Gregor51e77d52009-12-10 17:56:55 +00004339 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004340 SourceRange R;
4341
4342 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00004343 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004344 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004345 else
Douglas Gregor8ec51732010-09-08 21:40:08 +00004346 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004347
Douglas Gregor8ec51732010-09-08 21:40:08 +00004348 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4349 if (Kind.isCStyleOrFunctionalCast())
4350 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4351 << R;
4352 else
4353 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4354 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00004355 break;
4356 }
4357
4358 case FK_ReferenceBindingToInitList:
4359 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4360 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4361 break;
4362
4363 case FK_InitListBadDestinationType:
4364 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4365 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4366 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004367
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004368 case FK_ConstructorOverloadFailed: {
4369 SourceRange ArgsRange;
4370 if (NumArgs)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004371 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004372 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004373
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004374 // FIXME: Using "DestType" for the entity we're printing is probably
4375 // bad.
4376 switch (FailedOverloadResult) {
4377 case OR_Ambiguous:
4378 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4379 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004380 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4381 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004382 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004383
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004384 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004385 if (Kind.getKind() == InitializationKind::IK_Default &&
4386 (Entity.getKind() == InitializedEntity::EK_Base ||
4387 Entity.getKind() == InitializedEntity::EK_Member) &&
4388 isa<CXXConstructorDecl>(S.CurContext)) {
4389 // This is implicit default initialization of a member or
4390 // base within a constructor. If no viable function was
4391 // found, notify the user that she needs to explicitly
4392 // initialize this base/member.
4393 CXXConstructorDecl *Constructor
4394 = cast<CXXConstructorDecl>(S.CurContext);
4395 if (Entity.getKind() == InitializedEntity::EK_Base) {
4396 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4397 << Constructor->isImplicit()
4398 << S.Context.getTypeDeclType(Constructor->getParent())
4399 << /*base=*/0
4400 << Entity.getType();
4401
4402 RecordDecl *BaseDecl
4403 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4404 ->getDecl();
4405 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4406 << S.Context.getTagDeclType(BaseDecl);
4407 } else {
4408 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4409 << Constructor->isImplicit()
4410 << S.Context.getTypeDeclType(Constructor->getParent())
4411 << /*member=*/1
4412 << Entity.getName();
4413 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4414
4415 if (const RecordType *Record
4416 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004417 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004418 diag::note_previous_decl)
4419 << S.Context.getTagDeclType(Record->getDecl());
4420 }
4421 break;
4422 }
4423
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004424 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4425 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004426 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004427 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004428
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004429 case OR_Deleted: {
4430 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4431 << true << DestType << ArgsRange;
4432 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004433 OverloadingResult Ovl
4434 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004435 if (Ovl == OR_Deleted) {
4436 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4437 << Best->Function->isDeleted();
4438 } else {
4439 llvm_unreachable("Inconsistent overload resolution?");
4440 }
4441 break;
4442 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004443
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004444 case OR_Success:
4445 llvm_unreachable("Conversion did not fail!");
4446 break;
4447 }
4448 break;
4449 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004450
Douglas Gregor85dabae2009-12-16 01:38:02 +00004451 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004452 if (Entity.getKind() == InitializedEntity::EK_Member &&
4453 isa<CXXConstructorDecl>(S.CurContext)) {
4454 // This is implicit default-initialization of a const member in
4455 // a constructor. Complain that it needs to be explicitly
4456 // initialized.
4457 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4458 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4459 << Constructor->isImplicit()
4460 << S.Context.getTypeDeclType(Constructor->getParent())
4461 << /*const=*/1
4462 << Entity.getName();
4463 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4464 << Entity.getName();
4465 } else {
4466 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4467 << DestType << (bool)DestType->getAs<RecordType>();
4468 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004469 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004470
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004471 case FK_Incomplete:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004472 S.RequireCompleteType(Kind.getLocation(), DestType,
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004473 diag::err_init_incomplete_type);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004474 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004475 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004476
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004477 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004478 return true;
4479}
Douglas Gregore1314a62009-12-18 05:02:21 +00004480
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004481void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4482 switch (SequenceKind) {
4483 case FailedSequence: {
4484 OS << "Failed sequence: ";
4485 switch (Failure) {
4486 case FK_TooManyInitsForReference:
4487 OS << "too many initializers for reference";
4488 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004489
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004490 case FK_ArrayNeedsInitList:
4491 OS << "array requires initializer list";
4492 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004493
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004494 case FK_ArrayNeedsInitListOrStringLiteral:
4495 OS << "array requires initializer list or string literal";
4496 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004497
Douglas Gregore2f943b2011-02-22 18:29:51 +00004498 case FK_ArrayTypeMismatch:
4499 OS << "array type mismatch";
4500 break;
4501
4502 case FK_NonConstantArrayInit:
4503 OS << "non-constant array initializer";
4504 break;
4505
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004506 case FK_AddressOfOverloadFailed:
4507 OS << "address of overloaded function failed";
4508 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004509
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004510 case FK_ReferenceInitOverloadFailed:
4511 OS << "overload resolution for reference initialization failed";
4512 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004513
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004514 case FK_NonConstLValueReferenceBindingToTemporary:
4515 OS << "non-const lvalue reference bound to temporary";
4516 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004517
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004518 case FK_NonConstLValueReferenceBindingToUnrelated:
4519 OS << "non-const lvalue reference bound to unrelated type";
4520 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004521
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004522 case FK_RValueReferenceBindingToLValue:
4523 OS << "rvalue reference bound to an lvalue";
4524 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004525
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004526 case FK_ReferenceInitDropsQualifiers:
4527 OS << "reference initialization drops qualifiers";
4528 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004529
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004530 case FK_ReferenceInitFailed:
4531 OS << "reference initialization failed";
4532 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004533
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004534 case FK_ConversionFailed:
4535 OS << "conversion failed";
4536 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004537
John Wiegley01296292011-04-08 18:41:53 +00004538 case FK_ConversionFromPropertyFailed:
4539 OS << "conversion from property failed";
4540 break;
4541
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004542 case FK_TooManyInitsForScalar:
4543 OS << "too many initializers for scalar";
4544 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004545
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004546 case FK_ReferenceBindingToInitList:
4547 OS << "referencing binding to initializer list";
4548 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004549
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004550 case FK_InitListBadDestinationType:
4551 OS << "initializer list for non-aggregate, non-scalar type";
4552 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004553
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004554 case FK_UserConversionOverloadFailed:
4555 OS << "overloading failed for user-defined conversion";
4556 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004557
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004558 case FK_ConstructorOverloadFailed:
4559 OS << "constructor overloading failed";
4560 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004561
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004562 case FK_DefaultInitOfConst:
4563 OS << "default initialization of a const variable";
4564 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004565
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004566 case FK_Incomplete:
4567 OS << "initialization of incomplete type";
4568 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004569 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004570 OS << '\n';
4571 return;
4572 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004573
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004574 case DependentSequence:
4575 OS << "Dependent sequence: ";
4576 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004577
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004578 case UserDefinedConversion:
4579 OS << "User-defined conversion sequence: ";
4580 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004581
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004582 case ConstructorInitialization:
4583 OS << "Constructor initialization sequence: ";
4584 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004585
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004586 case ReferenceBinding:
4587 OS << "Reference binding: ";
4588 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004589
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004590 case ListInitialization:
4591 OS << "List initialization: ";
4592 break;
4593
4594 case ZeroInitialization:
4595 OS << "Zero initialization\n";
4596 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004597
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004598 case NoInitialization:
4599 OS << "No initialization\n";
4600 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004601
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004602 case StandardConversion:
4603 OS << "Standard conversion: ";
4604 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004605
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004606 case CAssignment:
4607 OS << "C assignment: ";
4608 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004609
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004610 case StringInit:
4611 OS << "String initialization: ";
4612 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004613
4614 case ArrayInit:
4615 OS << "Array initialization: ";
4616 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004617 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004618
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004619 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4620 if (S != step_begin()) {
4621 OS << " -> ";
4622 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004623
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004624 switch (S->Kind) {
4625 case SK_ResolveAddressOfOverloadedFunction:
4626 OS << "resolve address of overloaded function";
4627 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004628
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004629 case SK_CastDerivedToBaseRValue:
4630 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4631 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004632
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004633 case SK_CastDerivedToBaseXValue:
4634 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
4635 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004636
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004637 case SK_CastDerivedToBaseLValue:
4638 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4639 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004640
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004641 case SK_BindReference:
4642 OS << "bind reference to lvalue";
4643 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004644
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004645 case SK_BindReferenceToTemporary:
4646 OS << "bind reference to a temporary";
4647 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004648
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004649 case SK_ExtraneousCopyToTemporary:
4650 OS << "extraneous C++03 copy to temporary";
4651 break;
4652
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004653 case SK_UserConversion:
Benjamin Kramerb11416d2010-04-17 09:33:03 +00004654 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004655 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004656
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004657 case SK_QualificationConversionRValue:
4658 OS << "qualification conversion (rvalue)";
4659
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004660 case SK_QualificationConversionXValue:
4661 OS << "qualification conversion (xvalue)";
4662
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004663 case SK_QualificationConversionLValue:
4664 OS << "qualification conversion (lvalue)";
4665 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004666
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004667 case SK_ConversionSequence:
4668 OS << "implicit conversion sequence (";
4669 S->ICS->DebugPrint(); // FIXME: use OS
4670 OS << ")";
4671 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004672
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004673 case SK_ListInitialization:
4674 OS << "list initialization";
4675 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004676
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004677 case SK_ConstructorInitialization:
4678 OS << "constructor initialization";
4679 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004680
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004681 case SK_ZeroInitialization:
4682 OS << "zero initialization";
4683 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004684
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004685 case SK_CAssignment:
4686 OS << "C assignment";
4687 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004688
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004689 case SK_StringInit:
4690 OS << "string initialization";
4691 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004692
4693 case SK_ObjCObjectConversion:
4694 OS << "Objective-C object conversion";
4695 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004696
4697 case SK_ArrayInit:
4698 OS << "array initialization";
4699 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004700 }
4701 }
4702}
4703
4704void InitializationSequence::dump() const {
4705 dump(llvm::errs());
4706}
4707
Douglas Gregore1314a62009-12-18 05:02:21 +00004708//===----------------------------------------------------------------------===//
4709// Initialization helper functions
4710//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004711ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00004712Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4713 SourceLocation EqualLoc,
John McCalldadc5752010-08-24 06:29:42 +00004714 ExprResult Init) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004715 if (Init.isInvalid())
4716 return ExprError();
4717
John McCall1f425642010-11-11 03:21:53 +00004718 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00004719 assert(InitE && "No initialization expression?");
4720
4721 if (EqualLoc.isInvalid())
4722 EqualLoc = InitE->getLocStart();
4723
4724 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4725 EqualLoc);
4726 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4727 Init.release();
John McCallfaf5fb42010-08-26 23:41:50 +00004728 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregore1314a62009-12-18 05:02:21 +00004729}