1 //===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // 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.
14 //===----------------------------------------------------------------------===//
16 #include "clang/Sema/Designator.h"
17 #include "clang/Sema/Initialization.h"
18 #include "clang/Sema/Lookup.h"
19 #include "clang/Sema/SemaInternal.h"
20 #include "clang/Lex/Preprocessor.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "llvm/Support/ErrorHandling.h"
28 using namespace clang
;
30 //===----------------------------------------------------------------------===//
31 // Sema Initialization Checking
32 //===----------------------------------------------------------------------===//
34 static Expr
*IsStringInit(Expr
*Init
, QualType DeclType
, ASTContext
&Context
) {
35 const ArrayType
*AT
= Context
.getAsArrayType(DeclType
);
38 if (!isa
<ConstantArrayType
>(AT
) && !isa
<IncompleteArrayType
>(AT
))
41 // See if this is a string literal or @encode.
42 Init
= Init
->IgnoreParens();
44 // Handle @encode, which is a narrow string.
45 if (isa
<ObjCEncodeExpr
>(Init
) && AT
->getElementType()->isCharType())
48 // Otherwise we can only handle string literals.
49 StringLiteral
*SL
= dyn_cast
<StringLiteral
>(Init
);
50 if (SL
== 0) return 0;
52 QualType ElemTy
= Context
.getCanonicalType(AT
->getElementType());
53 // char array can be initialized with a narrow string.
54 // Only allow char x[] = "foo"; not char x[] = L"foo";
56 return ElemTy
->isCharType() ? Init
: 0;
58 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
59 // correction from DR343): "An array with element type compatible with a
60 // qualified or unqualified version of wchar_t may be initialized by a wide
61 // string literal, optionally enclosed in braces."
62 if (Context
.typesAreCompatible(Context
.getWCharType(),
63 ElemTy
.getUnqualifiedType()))
69 static void CheckStringInit(Expr
*Str
, QualType
&DeclT
, Sema
&S
) {
70 // Get the length of the string as parsed.
72 cast
<ConstantArrayType
>(Str
->getType())->getSize().getZExtValue();
75 const ArrayType
*AT
= S
.Context
.getAsArrayType(DeclT
);
76 if (const IncompleteArrayType
*IAT
= dyn_cast
<IncompleteArrayType
>(AT
)) {
77 // C99 6.7.8p14. We have an array of character type with unknown size
78 // being initialized to a string literal.
79 llvm::APSInt
ConstVal(32);
81 // Return a new array type (C99 6.7.8p22).
82 DeclT
= S
.Context
.getConstantArrayType(IAT
->getElementType(),
84 ArrayType::Normal
, 0);
88 const ConstantArrayType
*CAT
= cast
<ConstantArrayType
>(AT
);
90 // C99 6.7.8p14. We have an array of character type with known size. However,
91 // the size may be smaller or larger than the string we are initializing.
92 // FIXME: Avoid truncation for 64-bit length strings.
93 if (StrLength
-1 > CAT
->getSize().getZExtValue())
94 S
.Diag(Str
->getSourceRange().getBegin(),
95 diag::warn_initializer_string_for_char_array_too_long
)
96 << Str
->getSourceRange();
98 // Set the type to the actual size that we are initializing. If we have
100 // char x[1] = "foo";
101 // then this will set the string literal's type to char[1].
105 //===----------------------------------------------------------------------===//
106 // Semantic checking for initializer lists.
107 //===----------------------------------------------------------------------===//
109 /// @brief Semantic checking for initializer lists.
111 /// The InitListChecker class contains a set of routines that each
112 /// handle the initialization of a certain kind of entity, e.g.,
113 /// arrays, vectors, struct/union types, scalars, etc. The
114 /// InitListChecker itself performs a recursive walk of the subobject
115 /// structure of the type to be initialized, while stepping through
116 /// the initializer list one element at a time. The IList and Index
117 /// parameters to each of the Check* routines contain the active
118 /// (syntactic) initializer list and the index into that initializer
119 /// list that represents the current initializer. Each routine is
120 /// responsible for moving that Index forward as it consumes elements.
122 /// Each Check* routine also has a StructuredList/StructuredIndex
123 /// arguments, which contains the current "structured" (semantic)
124 /// initializer list and the index into that initializer list where we
125 /// are copying initializers as we map them over to the semantic
126 /// list. Once we have completed our recursive walk of the subobject
127 /// structure, we will have constructed a full semantic initializer
130 /// C99 designators cause changes in the initializer list traversal,
131 /// because they make the initialization "jump" into a specific
132 /// subobject and then continue the initialization from that
133 /// point. CheckDesignatedInitializer() recursively steps into the
134 /// designated subobject and manages backing out the recursion to
135 /// initialize the subobjects after the one designated.
137 class InitListChecker
{
140 std::map
<InitListExpr
*, InitListExpr
*> SyntacticToSemantic
;
141 InitListExpr
*FullyStructuredList
;
143 void CheckImplicitInitList(const InitializedEntity
&Entity
,
144 InitListExpr
*ParentIList
, QualType T
,
145 unsigned &Index
, InitListExpr
*StructuredList
,
146 unsigned &StructuredIndex
,
147 bool TopLevelObject
= false);
148 void CheckExplicitInitList(const InitializedEntity
&Entity
,
149 InitListExpr
*IList
, QualType
&T
,
150 unsigned &Index
, InitListExpr
*StructuredList
,
151 unsigned &StructuredIndex
,
152 bool TopLevelObject
= false);
153 void CheckListElementTypes(const InitializedEntity
&Entity
,
154 InitListExpr
*IList
, QualType
&DeclType
,
155 bool SubobjectIsDesignatorContext
,
157 InitListExpr
*StructuredList
,
158 unsigned &StructuredIndex
,
159 bool TopLevelObject
= false);
160 void CheckSubElementType(const InitializedEntity
&Entity
,
161 InitListExpr
*IList
, QualType ElemType
,
163 InitListExpr
*StructuredList
,
164 unsigned &StructuredIndex
);
165 void CheckScalarType(const InitializedEntity
&Entity
,
166 InitListExpr
*IList
, QualType DeclType
,
168 InitListExpr
*StructuredList
,
169 unsigned &StructuredIndex
);
170 void CheckReferenceType(const InitializedEntity
&Entity
,
171 InitListExpr
*IList
, QualType DeclType
,
173 InitListExpr
*StructuredList
,
174 unsigned &StructuredIndex
);
175 void CheckVectorType(const InitializedEntity
&Entity
,
176 InitListExpr
*IList
, QualType DeclType
, unsigned &Index
,
177 InitListExpr
*StructuredList
,
178 unsigned &StructuredIndex
);
179 void CheckStructUnionTypes(const InitializedEntity
&Entity
,
180 InitListExpr
*IList
, QualType DeclType
,
181 RecordDecl::field_iterator Field
,
182 bool SubobjectIsDesignatorContext
, unsigned &Index
,
183 InitListExpr
*StructuredList
,
184 unsigned &StructuredIndex
,
185 bool TopLevelObject
= false);
186 void CheckArrayType(const InitializedEntity
&Entity
,
187 InitListExpr
*IList
, QualType
&DeclType
,
188 llvm::APSInt elementIndex
,
189 bool SubobjectIsDesignatorContext
, unsigned &Index
,
190 InitListExpr
*StructuredList
,
191 unsigned &StructuredIndex
);
192 bool CheckDesignatedInitializer(const InitializedEntity
&Entity
,
193 InitListExpr
*IList
, DesignatedInitExpr
*DIE
,
195 QualType
&CurrentObjectType
,
196 RecordDecl::field_iterator
*NextField
,
197 llvm::APSInt
*NextElementIndex
,
199 InitListExpr
*StructuredList
,
200 unsigned &StructuredIndex
,
201 bool FinishSubobjectInit
,
202 bool TopLevelObject
);
203 InitListExpr
*getStructuredSubobjectInit(InitListExpr
*IList
, unsigned Index
,
204 QualType CurrentObjectType
,
205 InitListExpr
*StructuredList
,
206 unsigned StructuredIndex
,
207 SourceRange InitRange
);
208 void UpdateStructuredListElement(InitListExpr
*StructuredList
,
209 unsigned &StructuredIndex
,
211 int numArrayElements(QualType DeclType
);
212 int numStructUnionElements(QualType DeclType
);
214 void FillInValueInitForField(unsigned Init
, FieldDecl
*Field
,
215 const InitializedEntity
&ParentEntity
,
216 InitListExpr
*ILE
, bool &RequiresSecondPass
);
217 void FillInValueInitializations(const InitializedEntity
&Entity
,
218 InitListExpr
*ILE
, bool &RequiresSecondPass
);
220 InitListChecker(Sema
&S
, const InitializedEntity
&Entity
,
221 InitListExpr
*IL
, QualType
&T
);
222 bool HadError() { return hadError
; }
224 // @brief Retrieves the fully-structured initializer list used for
225 // semantic analysis and code generation.
226 InitListExpr
*getFullyStructuredList() const { return FullyStructuredList
; }
228 } // end anonymous namespace
230 void InitListChecker::FillInValueInitForField(unsigned Init
, FieldDecl
*Field
,
231 const InitializedEntity
&ParentEntity
,
233 bool &RequiresSecondPass
) {
234 SourceLocation Loc
= ILE
->getSourceRange().getBegin();
235 unsigned NumInits
= ILE
->getNumInits();
236 InitializedEntity MemberEntity
237 = InitializedEntity::InitializeMember(Field
, &ParentEntity
);
238 if (Init
>= NumInits
|| !ILE
->getInit(Init
)) {
239 // FIXME: We probably don't need to handle references
240 // specially here, since value-initialization of references is
241 // handled in InitializationSequence.
242 if (Field
->getType()->isReferenceType()) {
243 // C++ [dcl.init.aggr]p9:
244 // If an incomplete or empty initializer-list leaves a
245 // member of reference type uninitialized, the program is
247 SemaRef
.Diag(Loc
, diag::err_init_reference_member_uninitialized
)
249 << ILE
->getSyntacticForm()->getSourceRange();
250 SemaRef
.Diag(Field
->getLocation(),
251 diag::note_uninit_reference_member
);
256 InitializationKind Kind
= InitializationKind::CreateValue(Loc
, Loc
, Loc
,
258 InitializationSequence
InitSeq(SemaRef
, MemberEntity
, Kind
, 0, 0);
260 InitSeq
.Diagnose(SemaRef
, MemberEntity
, Kind
, 0, 0);
265 ExprResult MemberInit
266 = InitSeq
.Perform(SemaRef
, MemberEntity
, Kind
, MultiExprArg());
267 if (MemberInit
.isInvalid()) {
274 } else if (Init
< NumInits
) {
275 ILE
->setInit(Init
, MemberInit
.takeAs
<Expr
>());
276 } else if (InitSeq
.getKind()
277 == InitializationSequence::ConstructorInitialization
) {
278 // Value-initialization requires a constructor call, so
279 // extend the initializer list to include the constructor
280 // call and make a note that we'll need to take another pass
281 // through the initializer list.
282 ILE
->updateInit(SemaRef
.Context
, Init
, MemberInit
.takeAs
<Expr
>());
283 RequiresSecondPass
= true;
285 } else if (InitListExpr
*InnerILE
286 = dyn_cast
<InitListExpr
>(ILE
->getInit(Init
)))
287 FillInValueInitializations(MemberEntity
, InnerILE
,
291 /// Recursively replaces NULL values within the given initializer list
292 /// with expressions that perform value-initialization of the
293 /// appropriate type.
295 InitListChecker::FillInValueInitializations(const InitializedEntity
&Entity
,
297 bool &RequiresSecondPass
) {
298 assert((ILE
->getType() != SemaRef
.Context
.VoidTy
) &&
299 "Should not have void type");
300 SourceLocation Loc
= ILE
->getSourceRange().getBegin();
301 if (ILE
->getSyntacticForm())
302 Loc
= ILE
->getSyntacticForm()->getSourceRange().getBegin();
304 if (const RecordType
*RType
= ILE
->getType()->getAs
<RecordType
>()) {
305 if (RType
->getDecl()->isUnion() &&
306 ILE
->getInitializedFieldInUnion())
307 FillInValueInitForField(0, ILE
->getInitializedFieldInUnion(),
308 Entity
, ILE
, RequiresSecondPass
);
311 for (RecordDecl::field_iterator
312 Field
= RType
->getDecl()->field_begin(),
313 FieldEnd
= RType
->getDecl()->field_end();
314 Field
!= FieldEnd
; ++Field
) {
315 if (Field
->isUnnamedBitfield())
321 FillInValueInitForField(Init
, *Field
, Entity
, ILE
, RequiresSecondPass
);
327 // Only look at the first initialization of a union.
328 if (RType
->getDecl()->isUnion())
336 QualType ElementType
;
338 InitializedEntity ElementEntity
= Entity
;
339 unsigned NumInits
= ILE
->getNumInits();
340 unsigned NumElements
= NumInits
;
341 if (const ArrayType
*AType
= SemaRef
.Context
.getAsArrayType(ILE
->getType())) {
342 ElementType
= AType
->getElementType();
343 if (const ConstantArrayType
*CAType
= dyn_cast
<ConstantArrayType
>(AType
))
344 NumElements
= CAType
->getSize().getZExtValue();
345 ElementEntity
= InitializedEntity::InitializeElement(SemaRef
.Context
,
347 } else if (const VectorType
*VType
= ILE
->getType()->getAs
<VectorType
>()) {
348 ElementType
= VType
->getElementType();
349 NumElements
= VType
->getNumElements();
350 ElementEntity
= InitializedEntity::InitializeElement(SemaRef
.Context
,
353 ElementType
= ILE
->getType();
356 for (unsigned Init
= 0; Init
!= NumElements
; ++Init
) {
360 if (ElementEntity
.getKind() == InitializedEntity::EK_ArrayElement
||
361 ElementEntity
.getKind() == InitializedEntity::EK_VectorElement
)
362 ElementEntity
.setElementIndex(Init
);
364 if (Init
>= NumInits
|| !ILE
->getInit(Init
)) {
365 InitializationKind Kind
= InitializationKind::CreateValue(Loc
, Loc
, Loc
,
367 InitializationSequence
InitSeq(SemaRef
, ElementEntity
, Kind
, 0, 0);
369 InitSeq
.Diagnose(SemaRef
, ElementEntity
, Kind
, 0, 0);
374 ExprResult ElementInit
375 = InitSeq
.Perform(SemaRef
, ElementEntity
, Kind
, MultiExprArg());
376 if (ElementInit
.isInvalid()) {
383 } else if (Init
< NumInits
) {
384 ILE
->setInit(Init
, ElementInit
.takeAs
<Expr
>());
385 } else if (InitSeq
.getKind()
386 == InitializationSequence::ConstructorInitialization
) {
387 // Value-initialization requires a constructor call, so
388 // extend the initializer list to include the constructor
389 // call and make a note that we'll need to take another pass
390 // through the initializer list.
391 ILE
->updateInit(SemaRef
.Context
, Init
, ElementInit
.takeAs
<Expr
>());
392 RequiresSecondPass
= true;
394 } else if (InitListExpr
*InnerILE
395 = dyn_cast
<InitListExpr
>(ILE
->getInit(Init
)))
396 FillInValueInitializations(ElementEntity
, InnerILE
, RequiresSecondPass
);
401 InitListChecker::InitListChecker(Sema
&S
, const InitializedEntity
&Entity
,
402 InitListExpr
*IL
, QualType
&T
)
406 unsigned newIndex
= 0;
407 unsigned newStructuredIndex
= 0;
409 = getStructuredSubobjectInit(IL
, newIndex
, T
, 0, 0, IL
->getSourceRange());
410 CheckExplicitInitList(Entity
, IL
, T
, newIndex
,
411 FullyStructuredList
, newStructuredIndex
,
412 /*TopLevelObject=*/true);
415 bool RequiresSecondPass
= false;
416 FillInValueInitializations(Entity
, FullyStructuredList
, RequiresSecondPass
);
417 if (RequiresSecondPass
&& !hadError
)
418 FillInValueInitializations(Entity
, FullyStructuredList
,
423 int InitListChecker::numArrayElements(QualType DeclType
) {
424 // FIXME: use a proper constant
425 int maxElements
= 0x7FFFFFFF;
426 if (const ConstantArrayType
*CAT
=
427 SemaRef
.Context
.getAsConstantArrayType(DeclType
)) {
428 maxElements
= static_cast<int>(CAT
->getSize().getZExtValue());
433 int InitListChecker::numStructUnionElements(QualType DeclType
) {
434 RecordDecl
*structDecl
= DeclType
->getAs
<RecordType
>()->getDecl();
435 int InitializableMembers
= 0;
436 for (RecordDecl::field_iterator
437 Field
= structDecl
->field_begin(),
438 FieldEnd
= structDecl
->field_end();
439 Field
!= FieldEnd
; ++Field
) {
440 if ((*Field
)->getIdentifier() || !(*Field
)->isBitField())
441 ++InitializableMembers
;
443 if (structDecl
->isUnion())
444 return std::min(InitializableMembers
, 1);
445 return InitializableMembers
- structDecl
->hasFlexibleArrayMember();
448 void InitListChecker::CheckImplicitInitList(const InitializedEntity
&Entity
,
449 InitListExpr
*ParentIList
,
450 QualType T
, unsigned &Index
,
451 InitListExpr
*StructuredList
,
452 unsigned &StructuredIndex
,
453 bool TopLevelObject
) {
456 if (T
->isArrayType())
457 maxElements
= numArrayElements(T
);
458 else if (T
->isRecordType())
459 maxElements
= numStructUnionElements(T
);
460 else if (T
->isVectorType())
461 maxElements
= T
->getAs
<VectorType
>()->getNumElements();
463 assert(0 && "CheckImplicitInitList(): Illegal type");
465 if (maxElements
== 0) {
466 SemaRef
.Diag(ParentIList
->getInit(Index
)->getLocStart(),
467 diag::err_implicit_empty_initializer
);
473 // Build a structured initializer list corresponding to this subobject.
474 InitListExpr
*StructuredSubobjectInitList
475 = getStructuredSubobjectInit(ParentIList
, Index
, T
, StructuredList
,
477 SourceRange(ParentIList
->getInit(Index
)->getSourceRange().getBegin(),
478 ParentIList
->getSourceRange().getEnd()));
479 unsigned StructuredSubobjectInitIndex
= 0;
481 // Check the element types and build the structural subobject.
482 unsigned StartIndex
= Index
;
483 CheckListElementTypes(Entity
, ParentIList
, T
,
484 /*SubobjectIsDesignatorContext=*/false, Index
,
485 StructuredSubobjectInitList
,
486 StructuredSubobjectInitIndex
,
488 unsigned EndIndex
= (Index
== StartIndex
? StartIndex
: Index
- 1);
489 StructuredSubobjectInitList
->setType(T
);
491 // Update the structured sub-object initializer so that it's ending
492 // range corresponds with the end of the last initializer it used.
493 if (EndIndex
< ParentIList
->getNumInits()) {
494 SourceLocation EndLoc
495 = ParentIList
->getInit(EndIndex
)->getSourceRange().getEnd();
496 StructuredSubobjectInitList
->setRBraceLoc(EndLoc
);
499 // Warn about missing braces.
500 if (T
->isArrayType() || T
->isRecordType()) {
501 SemaRef
.Diag(StructuredSubobjectInitList
->getLocStart(),
502 diag::warn_missing_braces
)
503 << StructuredSubobjectInitList
->getSourceRange()
504 << FixItHint::CreateInsertion(StructuredSubobjectInitList
->getLocStart(),
506 << FixItHint::CreateInsertion(SemaRef
.PP
.getLocForEndOfToken(
507 StructuredSubobjectInitList
->getLocEnd()),
512 void InitListChecker::CheckExplicitInitList(const InitializedEntity
&Entity
,
513 InitListExpr
*IList
, QualType
&T
,
515 InitListExpr
*StructuredList
,
516 unsigned &StructuredIndex
,
517 bool TopLevelObject
) {
518 assert(IList
->isExplicit() && "Illegal Implicit InitListExpr");
519 SyntacticToSemantic
[IList
] = StructuredList
;
520 StructuredList
->setSyntacticForm(IList
);
521 CheckListElementTypes(Entity
, IList
, T
, /*SubobjectIsDesignatorContext=*/true,
522 Index
, StructuredList
, StructuredIndex
, TopLevelObject
);
523 QualType ExprTy
= T
.getNonLValueExprType(SemaRef
.Context
);
524 IList
->setType(ExprTy
);
525 StructuredList
->setType(ExprTy
);
529 if (Index
< IList
->getNumInits()) {
530 // We have leftover initializers
531 if (StructuredIndex
== 1 &&
532 IsStringInit(StructuredList
->getInit(0), T
, SemaRef
.Context
)) {
533 unsigned DK
= diag::warn_excess_initializers_in_char_array_initializer
;
534 if (SemaRef
.getLangOptions().CPlusPlus
) {
535 DK
= diag::err_excess_initializers_in_char_array_initializer
;
539 SemaRef
.Diag(IList
->getInit(Index
)->getLocStart(), DK
)
540 << IList
->getInit(Index
)->getSourceRange();
541 } else if (!T
->isIncompleteType()) {
542 // Don't complain for incomplete types, since we'll get an error
544 QualType CurrentObjectType
= StructuredList
->getType();
546 CurrentObjectType
->isArrayType()? 0 :
547 CurrentObjectType
->isVectorType()? 1 :
548 CurrentObjectType
->isScalarType()? 2 :
549 CurrentObjectType
->isUnionType()? 3 :
552 unsigned DK
= diag::warn_excess_initializers
;
553 if (SemaRef
.getLangOptions().CPlusPlus
) {
554 DK
= diag::err_excess_initializers
;
557 if (SemaRef
.getLangOptions().OpenCL
&& initKind
== 1) {
558 DK
= diag::err_excess_initializers
;
562 SemaRef
.Diag(IList
->getInit(Index
)->getLocStart(), DK
)
563 << initKind
<< IList
->getInit(Index
)->getSourceRange();
567 if (T
->isScalarType() && !TopLevelObject
)
568 SemaRef
.Diag(IList
->getLocStart(), diag::warn_braces_around_scalar_init
)
569 << IList
->getSourceRange()
570 << FixItHint::CreateRemoval(IList
->getLocStart())
571 << FixItHint::CreateRemoval(IList
->getLocEnd());
574 void InitListChecker::CheckListElementTypes(const InitializedEntity
&Entity
,
577 bool SubobjectIsDesignatorContext
,
579 InitListExpr
*StructuredList
,
580 unsigned &StructuredIndex
,
581 bool TopLevelObject
) {
582 if (DeclType
->isScalarType()) {
583 CheckScalarType(Entity
, IList
, DeclType
, Index
,
584 StructuredList
, StructuredIndex
);
585 } else if (DeclType
->isVectorType()) {
586 CheckVectorType(Entity
, IList
, DeclType
, Index
,
587 StructuredList
, StructuredIndex
);
588 } else if (DeclType
->isAggregateType()) {
589 if (DeclType
->isRecordType()) {
590 RecordDecl
*RD
= DeclType
->getAs
<RecordType
>()->getDecl();
591 CheckStructUnionTypes(Entity
, IList
, DeclType
, RD
->field_begin(),
592 SubobjectIsDesignatorContext
, Index
,
593 StructuredList
, StructuredIndex
,
595 } else if (DeclType
->isArrayType()) {
597 SemaRef
.Context
.getTypeSize(SemaRef
.Context
.getSizeType()),
599 CheckArrayType(Entity
, IList
, DeclType
, Zero
,
600 SubobjectIsDesignatorContext
, Index
,
601 StructuredList
, StructuredIndex
);
603 assert(0 && "Aggregate that isn't a structure or array?!");
604 } else if (DeclType
->isVoidType() || DeclType
->isFunctionType()) {
605 // This type is invalid, issue a diagnostic.
607 SemaRef
.Diag(IList
->getLocStart(), diag::err_illegal_initializer_type
)
610 } else if (DeclType
->isRecordType()) {
611 // C++ [dcl.init]p14:
612 // [...] If the class is an aggregate (8.5.1), and the initializer
613 // is a brace-enclosed list, see 8.5.1.
615 // Note: 8.5.1 is handled below; here, we diagnose the case where
616 // we have an initializer list and a destination type that is not
618 // FIXME: In C++0x, this is yet another form of initialization.
619 SemaRef
.Diag(IList
->getLocStart(), diag::err_init_non_aggr_init_list
)
620 << DeclType
<< IList
->getSourceRange();
622 } else if (DeclType
->isReferenceType()) {
623 CheckReferenceType(Entity
, IList
, DeclType
, Index
,
624 StructuredList
, StructuredIndex
);
625 } else if (DeclType
->isObjCObjectType()) {
626 SemaRef
.Diag(IList
->getLocStart(), diag::err_init_objc_class
)
630 SemaRef
.Diag(IList
->getLocStart(), diag::err_illegal_initializer_type
)
636 void InitListChecker::CheckSubElementType(const InitializedEntity
&Entity
,
640 InitListExpr
*StructuredList
,
641 unsigned &StructuredIndex
) {
642 Expr
*expr
= IList
->getInit(Index
);
643 if (InitListExpr
*SubInitList
= dyn_cast
<InitListExpr
>(expr
)) {
644 unsigned newIndex
= 0;
645 unsigned newStructuredIndex
= 0;
646 InitListExpr
*newStructuredList
647 = getStructuredSubobjectInit(IList
, Index
, ElemType
,
648 StructuredList
, StructuredIndex
,
649 SubInitList
->getSourceRange());
650 CheckExplicitInitList(Entity
, SubInitList
, ElemType
, newIndex
,
651 newStructuredList
, newStructuredIndex
);
654 } else if (Expr
*Str
= IsStringInit(expr
, ElemType
, SemaRef
.Context
)) {
655 CheckStringInit(Str
, ElemType
, SemaRef
);
656 UpdateStructuredListElement(StructuredList
, StructuredIndex
, Str
);
658 } else if (ElemType
->isScalarType()) {
659 CheckScalarType(Entity
, IList
, ElemType
, Index
,
660 StructuredList
, StructuredIndex
);
661 } else if (ElemType
->isReferenceType()) {
662 CheckReferenceType(Entity
, IList
, ElemType
, Index
,
663 StructuredList
, StructuredIndex
);
665 if (SemaRef
.getLangOptions().CPlusPlus
) {
666 // C++ [dcl.init.aggr]p12:
667 // All implicit type conversions (clause 4) are considered when
668 // initializing the aggregate member with an ini- tializer from
669 // an initializer-list. If the initializer can initialize a
670 // member, the member is initialized. [...]
672 // FIXME: Better EqualLoc?
673 InitializationKind Kind
=
674 InitializationKind::CreateCopy(expr
->getLocStart(), SourceLocation());
675 InitializationSequence
Seq(SemaRef
, Entity
, Kind
, &expr
, 1);
679 Seq
.Perform(SemaRef
, Entity
, Kind
, MultiExprArg(&expr
, 1));
680 if (Result
.isInvalid())
683 UpdateStructuredListElement(StructuredList
, StructuredIndex
,
684 Result
.takeAs
<Expr
>());
689 // Fall through for subaggregate initialization
693 // The initializer for a structure or union object that has
694 // automatic storage duration shall be either an initializer
695 // list as described below, or a single expression that has
696 // compatible structure or union type. In the latter case, the
697 // initial value of the object, including unnamed members, is
698 // that of the expression.
699 if ((ElemType
->isRecordType() || ElemType
->isVectorType()) &&
700 SemaRef
.CheckSingleAssignmentConstraints(ElemType
, expr
)
701 == Sema::Compatible
) {
702 SemaRef
.DefaultFunctionArrayLvalueConversion(expr
);
703 UpdateStructuredListElement(StructuredList
, StructuredIndex
, expr
);
708 // Fall through for subaggregate initialization
711 // C++ [dcl.init.aggr]p12:
713 // [...] Otherwise, if the member is itself a non-empty
714 // subaggregate, brace elision is assumed and the initializer is
715 // considered for the initialization of the first member of
717 if (ElemType
->isAggregateType() || ElemType
->isVectorType()) {
718 CheckImplicitInitList(Entity
, IList
, ElemType
, Index
, StructuredList
,
722 // We cannot initialize this element, so let
723 // PerformCopyInitialization produce the appropriate diagnostic.
724 SemaRef
.PerformCopyInitialization(Entity
, SourceLocation(),
725 SemaRef
.Owned(expr
));
733 void InitListChecker::CheckScalarType(const InitializedEntity
&Entity
,
734 InitListExpr
*IList
, QualType DeclType
,
736 InitListExpr
*StructuredList
,
737 unsigned &StructuredIndex
) {
738 if (Index
>= IList
->getNumInits()) {
739 SemaRef
.Diag(IList
->getLocStart(), diag::err_empty_scalar_initializer
)
740 << IList
->getSourceRange();
747 Expr
*expr
= IList
->getInit(Index
);
748 if (InitListExpr
*SubIList
= dyn_cast
<InitListExpr
>(expr
)) {
749 SemaRef
.Diag(SubIList
->getLocStart(),
750 diag::warn_many_braces_around_scalar_init
)
751 << SubIList
->getSourceRange();
753 CheckScalarType(Entity
, SubIList
, DeclType
, Index
, StructuredList
,
756 } else if (isa
<DesignatedInitExpr
>(expr
)) {
757 SemaRef
.Diag(expr
->getSourceRange().getBegin(),
758 diag::err_designator_for_scalar_init
)
759 << DeclType
<< expr
->getSourceRange();
767 SemaRef
.PerformCopyInitialization(Entity
, expr
->getLocStart(),
768 SemaRef
.Owned(expr
));
770 Expr
*ResultExpr
= 0;
772 if (Result
.isInvalid())
773 hadError
= true; // types weren't compatible.
775 ResultExpr
= Result
.takeAs
<Expr
>();
777 if (ResultExpr
!= expr
) {
778 // The type was promoted, update initializer list.
779 IList
->setInit(Index
, ResultExpr
);
785 UpdateStructuredListElement(StructuredList
, StructuredIndex
, ResultExpr
);
789 void InitListChecker::CheckReferenceType(const InitializedEntity
&Entity
,
790 InitListExpr
*IList
, QualType DeclType
,
792 InitListExpr
*StructuredList
,
793 unsigned &StructuredIndex
) {
794 if (Index
< IList
->getNumInits()) {
795 Expr
*expr
= IList
->getInit(Index
);
796 if (isa
<InitListExpr
>(expr
)) {
797 SemaRef
.Diag(IList
->getLocStart(), diag::err_init_non_aggr_init_list
)
798 << DeclType
<< IList
->getSourceRange();
806 SemaRef
.PerformCopyInitialization(Entity
, expr
->getLocStart(),
807 SemaRef
.Owned(expr
));
809 if (Result
.isInvalid())
812 expr
= Result
.takeAs
<Expr
>();
813 IList
->setInit(Index
, expr
);
818 UpdateStructuredListElement(StructuredList
, StructuredIndex
, expr
);
821 // FIXME: It would be wonderful if we could point at the actual member. In
822 // general, it would be useful to pass location information down the stack,
823 // so that we know the location (or decl) of the "current object" being
825 SemaRef
.Diag(IList
->getLocStart(),
826 diag::err_init_reference_member_uninitialized
)
828 << IList
->getSourceRange();
836 void InitListChecker::CheckVectorType(const InitializedEntity
&Entity
,
837 InitListExpr
*IList
, QualType DeclType
,
839 InitListExpr
*StructuredList
,
840 unsigned &StructuredIndex
) {
841 if (Index
>= IList
->getNumInits())
844 const VectorType
*VT
= DeclType
->getAs
<VectorType
>();
845 unsigned maxElements
= VT
->getNumElements();
846 unsigned numEltsInit
= 0;
847 QualType elementType
= VT
->getElementType();
849 if (!SemaRef
.getLangOptions().OpenCL
) {
850 // If the initializing element is a vector, try to copy-initialize
851 // instead of breaking it apart (which is doomed to failure anyway).
852 Expr
*Init
= IList
->getInit(Index
);
853 if (!isa
<InitListExpr
>(Init
) && Init
->getType()->isVectorType()) {
855 SemaRef
.PerformCopyInitialization(Entity
, Init
->getLocStart(),
856 SemaRef
.Owned(Init
));
858 Expr
*ResultExpr
= 0;
859 if (Result
.isInvalid())
860 hadError
= true; // types weren't compatible.
862 ResultExpr
= Result
.takeAs
<Expr
>();
864 if (ResultExpr
!= Init
) {
865 // The type was promoted, update initializer list.
866 IList
->setInit(Index
, ResultExpr
);
872 UpdateStructuredListElement(StructuredList
, StructuredIndex
, ResultExpr
);
877 InitializedEntity ElementEntity
=
878 InitializedEntity::InitializeElement(SemaRef
.Context
, 0, Entity
);
880 for (unsigned i
= 0; i
< maxElements
; ++i
, ++numEltsInit
) {
881 // Don't attempt to go past the end of the init list
882 if (Index
>= IList
->getNumInits())
885 ElementEntity
.setElementIndex(Index
);
886 CheckSubElementType(ElementEntity
, IList
, elementType
, Index
,
887 StructuredList
, StructuredIndex
);
892 InitializedEntity ElementEntity
=
893 InitializedEntity::InitializeElement(SemaRef
.Context
, 0, Entity
);
895 // OpenCL initializers allows vectors to be constructed from vectors.
896 for (unsigned i
= 0; i
< maxElements
; ++i
) {
897 // Don't attempt to go past the end of the init list
898 if (Index
>= IList
->getNumInits())
901 ElementEntity
.setElementIndex(Index
);
903 QualType IType
= IList
->getInit(Index
)->getType();
904 if (!IType
->isVectorType()) {
905 CheckSubElementType(ElementEntity
, IList
, elementType
, Index
,
906 StructuredList
, StructuredIndex
);
910 const VectorType
*IVT
= IType
->getAs
<VectorType
>();
911 unsigned numIElts
= IVT
->getNumElements();
913 if (IType
->isExtVectorType())
914 VecType
= SemaRef
.Context
.getExtVectorType(elementType
, numIElts
);
916 VecType
= SemaRef
.Context
.getVectorType(elementType
, numIElts
,
917 IVT
->getVectorKind());
918 CheckSubElementType(ElementEntity
, IList
, VecType
, Index
,
919 StructuredList
, StructuredIndex
);
920 numEltsInit
+= numIElts
;
924 // OpenCL requires all elements to be initialized.
925 if (numEltsInit
!= maxElements
)
926 if (SemaRef
.getLangOptions().OpenCL
)
927 SemaRef
.Diag(IList
->getSourceRange().getBegin(),
928 diag::err_vector_incorrect_num_initializers
)
929 << (numEltsInit
< maxElements
) << maxElements
<< numEltsInit
;
932 void InitListChecker::CheckArrayType(const InitializedEntity
&Entity
,
933 InitListExpr
*IList
, QualType
&DeclType
,
934 llvm::APSInt elementIndex
,
935 bool SubobjectIsDesignatorContext
,
937 InitListExpr
*StructuredList
,
938 unsigned &StructuredIndex
) {
939 // Check for the special-case of initializing an array with a string.
940 if (Index
< IList
->getNumInits()) {
941 if (Expr
*Str
= IsStringInit(IList
->getInit(Index
), DeclType
,
943 CheckStringInit(Str
, DeclType
, SemaRef
);
944 // We place the string literal directly into the resulting
945 // initializer list. This is the only place where the structure
946 // of the structured initializer list doesn't match exactly,
947 // because doing so would involve allocating one character
948 // constant for each string.
949 UpdateStructuredListElement(StructuredList
, StructuredIndex
, Str
);
950 StructuredList
->resizeInits(SemaRef
.Context
, StructuredIndex
);
955 if (const VariableArrayType
*VAT
=
956 SemaRef
.Context
.getAsVariableArrayType(DeclType
)) {
957 // Check for VLAs; in standard C it would be possible to check this
958 // earlier, but I don't know where clang accepts VLAs (gcc accepts
959 // them in all sorts of strange places).
960 SemaRef
.Diag(VAT
->getSizeExpr()->getLocStart(),
961 diag::err_variable_object_no_init
)
962 << VAT
->getSizeExpr()->getSourceRange();
969 // We might know the maximum number of elements in advance.
970 llvm::APSInt
maxElements(elementIndex
.getBitWidth(),
971 elementIndex
.isUnsigned());
972 bool maxElementsKnown
= false;
973 if (const ConstantArrayType
*CAT
=
974 SemaRef
.Context
.getAsConstantArrayType(DeclType
)) {
975 maxElements
= CAT
->getSize();
976 elementIndex
= elementIndex
.extOrTrunc(maxElements
.getBitWidth());
977 elementIndex
.setIsUnsigned(maxElements
.isUnsigned());
978 maxElementsKnown
= true;
981 QualType elementType
= SemaRef
.Context
.getAsArrayType(DeclType
)
983 while (Index
< IList
->getNumInits()) {
984 Expr
*Init
= IList
->getInit(Index
);
985 if (DesignatedInitExpr
*DIE
= dyn_cast
<DesignatedInitExpr
>(Init
)) {
986 // If we're not the subobject that matches up with the '{' for
987 // the designator, we shouldn't be handling the
988 // designator. Return immediately.
989 if (!SubobjectIsDesignatorContext
)
992 // Handle this designated initializer. elementIndex will be
993 // updated to be the next array element we'll initialize.
994 if (CheckDesignatedInitializer(Entity
, IList
, DIE
, 0,
995 DeclType
, 0, &elementIndex
, Index
,
996 StructuredList
, StructuredIndex
, true,
1002 if (elementIndex
.getBitWidth() > maxElements
.getBitWidth())
1003 maxElements
= maxElements
.extend(elementIndex
.getBitWidth());
1004 else if (elementIndex
.getBitWidth() < maxElements
.getBitWidth())
1005 elementIndex
= elementIndex
.extend(maxElements
.getBitWidth());
1006 elementIndex
.setIsUnsigned(maxElements
.isUnsigned());
1008 // If the array is of incomplete type, keep track of the number of
1009 // elements in the initializer.
1010 if (!maxElementsKnown
&& elementIndex
> maxElements
)
1011 maxElements
= elementIndex
;
1016 // If we know the maximum number of elements, and we've already
1017 // hit it, stop consuming elements in the initializer list.
1018 if (maxElementsKnown
&& elementIndex
== maxElements
)
1021 InitializedEntity ElementEntity
=
1022 InitializedEntity::InitializeElement(SemaRef
.Context
, StructuredIndex
,
1024 // Check this element.
1025 CheckSubElementType(ElementEntity
, IList
, elementType
, Index
,
1026 StructuredList
, StructuredIndex
);
1029 // If the array is of incomplete type, keep track of the number of
1030 // elements in the initializer.
1031 if (!maxElementsKnown
&& elementIndex
> maxElements
)
1032 maxElements
= elementIndex
;
1034 if (!hadError
&& DeclType
->isIncompleteArrayType()) {
1035 // If this is an incomplete array type, the actual type needs to
1036 // be calculated here.
1037 llvm::APSInt
Zero(maxElements
.getBitWidth(), maxElements
.isUnsigned());
1038 if (maxElements
== Zero
) {
1039 // Sizing an array implicitly to zero is not allowed by ISO C,
1040 // but is supported by GNU.
1041 SemaRef
.Diag(IList
->getLocStart(),
1042 diag::ext_typecheck_zero_array_size
);
1045 DeclType
= SemaRef
.Context
.getConstantArrayType(elementType
, maxElements
,
1046 ArrayType::Normal
, 0);
1050 void InitListChecker::CheckStructUnionTypes(const InitializedEntity
&Entity
,
1051 InitListExpr
*IList
,
1053 RecordDecl::field_iterator Field
,
1054 bool SubobjectIsDesignatorContext
,
1056 InitListExpr
*StructuredList
,
1057 unsigned &StructuredIndex
,
1058 bool TopLevelObject
) {
1059 RecordDecl
* structDecl
= DeclType
->getAs
<RecordType
>()->getDecl();
1061 // If the record is invalid, some of it's members are invalid. To avoid
1062 // confusion, we forgo checking the intializer for the entire record.
1063 if (structDecl
->isInvalidDecl()) {
1068 if (DeclType
->isUnionType() && IList
->getNumInits() == 0) {
1069 // Value-initialize the first named member of the union.
1070 RecordDecl
*RD
= DeclType
->getAs
<RecordType
>()->getDecl();
1071 for (RecordDecl::field_iterator FieldEnd
= RD
->field_end();
1072 Field
!= FieldEnd
; ++Field
) {
1073 if (Field
->getDeclName()) {
1074 StructuredList
->setInitializedFieldInUnion(*Field
);
1081 // If structDecl is a forward declaration, this loop won't do
1082 // anything except look at designated initializers; That's okay,
1083 // because an error should get printed out elsewhere. It might be
1084 // worthwhile to skip over the rest of the initializer, though.
1085 RecordDecl
*RD
= DeclType
->getAs
<RecordType
>()->getDecl();
1086 RecordDecl::field_iterator FieldEnd
= RD
->field_end();
1087 bool InitializedSomething
= false;
1088 bool CheckForMissingFields
= true;
1089 while (Index
< IList
->getNumInits()) {
1090 Expr
*Init
= IList
->getInit(Index
);
1092 if (DesignatedInitExpr
*DIE
= dyn_cast
<DesignatedInitExpr
>(Init
)) {
1093 // If we're not the subobject that matches up with the '{' for
1094 // the designator, we shouldn't be handling the
1095 // designator. Return immediately.
1096 if (!SubobjectIsDesignatorContext
)
1099 // Handle this designated initializer. Field will be updated to
1100 // the next field that we'll be initializing.
1101 if (CheckDesignatedInitializer(Entity
, IList
, DIE
, 0,
1102 DeclType
, &Field
, 0, Index
,
1103 StructuredList
, StructuredIndex
,
1104 true, TopLevelObject
))
1107 InitializedSomething
= true;
1109 // Disable check for missing fields when designators are used.
1110 // This matches gcc behaviour.
1111 CheckForMissingFields
= false;
1115 if (Field
== FieldEnd
) {
1116 // We've run out of fields. We're done.
1120 // We've already initialized a member of a union. We're done.
1121 if (InitializedSomething
&& DeclType
->isUnionType())
1124 // If we've hit the flexible array member at the end, we're done.
1125 if (Field
->getType()->isIncompleteArrayType())
1128 if (Field
->isUnnamedBitfield()) {
1129 // Don't initialize unnamed bitfields, e.g. "int : 20;"
1134 InitializedEntity MemberEntity
=
1135 InitializedEntity::InitializeMember(*Field
, &Entity
);
1136 CheckSubElementType(MemberEntity
, IList
, Field
->getType(), Index
,
1137 StructuredList
, StructuredIndex
);
1138 InitializedSomething
= true;
1140 if (DeclType
->isUnionType()) {
1141 // Initialize the first field within the union.
1142 StructuredList
->setInitializedFieldInUnion(*Field
);
1148 // Emit warnings for missing struct field initializers.
1149 if (InitializedSomething
&& CheckForMissingFields
&& Field
!= FieldEnd
&&
1150 !Field
->getType()->isIncompleteArrayType() && !DeclType
->isUnionType()) {
1151 // It is possible we have one or more unnamed bitfields remaining.
1152 // Find first (if any) named field and emit warning.
1153 for (RecordDecl::field_iterator it
= Field
, end
= RD
->field_end();
1155 if (!it
->isUnnamedBitfield()) {
1156 SemaRef
.Diag(IList
->getSourceRange().getEnd(),
1157 diag::warn_missing_field_initializers
) << it
->getName();
1163 if (Field
== FieldEnd
|| !Field
->getType()->isIncompleteArrayType() ||
1164 Index
>= IList
->getNumInits())
1167 // Handle GNU flexible array initializers.
1168 if (!TopLevelObject
&&
1169 (!isa
<InitListExpr
>(IList
->getInit(Index
)) ||
1170 cast
<InitListExpr
>(IList
->getInit(Index
))->getNumInits() > 0)) {
1171 SemaRef
.Diag(IList
->getInit(Index
)->getSourceRange().getBegin(),
1172 diag::err_flexible_array_init_nonempty
)
1173 << IList
->getInit(Index
)->getSourceRange().getBegin();
1174 SemaRef
.Diag(Field
->getLocation(), diag::note_flexible_array_member
)
1180 SemaRef
.Diag(IList
->getInit(Index
)->getSourceRange().getBegin(),
1181 diag::ext_flexible_array_init
)
1182 << IList
->getInit(Index
)->getSourceRange().getBegin();
1183 SemaRef
.Diag(Field
->getLocation(), diag::note_flexible_array_member
)
1187 InitializedEntity MemberEntity
=
1188 InitializedEntity::InitializeMember(*Field
, &Entity
);
1190 if (isa
<InitListExpr
>(IList
->getInit(Index
)))
1191 CheckSubElementType(MemberEntity
, IList
, Field
->getType(), Index
,
1192 StructuredList
, StructuredIndex
);
1194 CheckImplicitInitList(MemberEntity
, IList
, Field
->getType(), Index
,
1195 StructuredList
, StructuredIndex
);
1198 /// \brief Expand a field designator that refers to a member of an
1199 /// anonymous struct or union into a series of field designators that
1200 /// refers to the field within the appropriate subobject.
1202 static void ExpandAnonymousFieldDesignator(Sema
&SemaRef
,
1203 DesignatedInitExpr
*DIE
,
1205 IndirectFieldDecl
*IndirectField
) {
1206 typedef DesignatedInitExpr::Designator Designator
;
1208 // Build the replacement designators.
1209 llvm::SmallVector
<Designator
, 4> Replacements
;
1210 for (IndirectFieldDecl::chain_iterator PI
= IndirectField
->chain_begin(),
1211 PE
= IndirectField
->chain_end(); PI
!= PE
; ++PI
) {
1213 Replacements
.push_back(Designator((IdentifierInfo
*)0,
1214 DIE
->getDesignator(DesigIdx
)->getDotLoc(),
1215 DIE
->getDesignator(DesigIdx
)->getFieldLoc()));
1217 Replacements
.push_back(Designator((IdentifierInfo
*)0, SourceLocation(),
1219 assert(isa
<FieldDecl
>(*PI
));
1220 Replacements
.back().setField(cast
<FieldDecl
>(*PI
));
1223 // Expand the current designator into the set of replacement
1224 // designators, so we have a full subobject path down to where the
1225 // member of the anonymous struct/union is actually stored.
1226 DIE
->ExpandDesignator(SemaRef
.Context
, DesigIdx
, &Replacements
[0],
1227 &Replacements
[0] + Replacements
.size());
1230 /// \brief Given an implicit anonymous field, search the IndirectField that
1231 /// corresponds to FieldName.
1232 static IndirectFieldDecl
*FindIndirectFieldDesignator(FieldDecl
*AnonField
,
1233 IdentifierInfo
*FieldName
) {
1234 assert(AnonField
->isAnonymousStructOrUnion());
1235 Decl
*NextDecl
= AnonField
->getNextDeclInContext();
1236 while (IndirectFieldDecl
*IF
= dyn_cast
<IndirectFieldDecl
>(NextDecl
)) {
1237 if (FieldName
&& FieldName
== IF
->getAnonField()->getIdentifier())
1239 NextDecl
= NextDecl
->getNextDeclInContext();
1244 /// @brief Check the well-formedness of a C99 designated initializer.
1246 /// Determines whether the designated initializer @p DIE, which
1247 /// resides at the given @p Index within the initializer list @p
1248 /// IList, is well-formed for a current object of type @p DeclType
1249 /// (C99 6.7.8). The actual subobject that this designator refers to
1250 /// within the current subobject is returned in either
1251 /// @p NextField or @p NextElementIndex (whichever is appropriate).
1253 /// @param IList The initializer list in which this designated
1254 /// initializer occurs.
1256 /// @param DIE The designated initializer expression.
1258 /// @param DesigIdx The index of the current designator.
1260 /// @param DeclType The type of the "current object" (C99 6.7.8p17),
1261 /// into which the designation in @p DIE should refer.
1263 /// @param NextField If non-NULL and the first designator in @p DIE is
1264 /// a field, this will be set to the field declaration corresponding
1265 /// to the field named by the designator.
1267 /// @param NextElementIndex If non-NULL and the first designator in @p
1268 /// DIE is an array designator or GNU array-range designator, this
1269 /// will be set to the last index initialized by this designator.
1271 /// @param Index Index into @p IList where the designated initializer
1274 /// @param StructuredList The initializer list expression that
1275 /// describes all of the subobject initializers in the order they'll
1276 /// actually be initialized.
1278 /// @returns true if there was an error, false otherwise.
1280 InitListChecker::CheckDesignatedInitializer(const InitializedEntity
&Entity
,
1281 InitListExpr
*IList
,
1282 DesignatedInitExpr
*DIE
,
1284 QualType
&CurrentObjectType
,
1285 RecordDecl::field_iterator
*NextField
,
1286 llvm::APSInt
*NextElementIndex
,
1288 InitListExpr
*StructuredList
,
1289 unsigned &StructuredIndex
,
1290 bool FinishSubobjectInit
,
1291 bool TopLevelObject
) {
1292 if (DesigIdx
== DIE
->size()) {
1293 // Check the actual initialization for the designated object type.
1294 bool prevHadError
= hadError
;
1296 // Temporarily remove the designator expression from the
1297 // initializer list that the child calls see, so that we don't try
1298 // to re-process the designator.
1299 unsigned OldIndex
= Index
;
1300 IList
->setInit(OldIndex
, DIE
->getInit());
1302 CheckSubElementType(Entity
, IList
, CurrentObjectType
, Index
,
1303 StructuredList
, StructuredIndex
);
1305 // Restore the designated initializer expression in the syntactic
1306 // form of the initializer list.
1307 if (IList
->getInit(OldIndex
) != DIE
->getInit())
1308 DIE
->setInit(IList
->getInit(OldIndex
));
1309 IList
->setInit(OldIndex
, DIE
);
1311 return hadError
&& !prevHadError
;
1314 bool IsFirstDesignator
= (DesigIdx
== 0);
1315 assert((IsFirstDesignator
|| StructuredList
) &&
1316 "Need a non-designated initializer list to start from");
1318 DesignatedInitExpr::Designator
*D
= DIE
->getDesignator(DesigIdx
);
1319 // Determine the structural initializer list that corresponds to the
1320 // current subobject.
1321 StructuredList
= IsFirstDesignator
? SyntacticToSemantic
[IList
]
1322 : getStructuredSubobjectInit(IList
, Index
, CurrentObjectType
,
1323 StructuredList
, StructuredIndex
,
1324 SourceRange(D
->getStartLocation(),
1325 DIE
->getSourceRange().getEnd()));
1326 assert(StructuredList
&& "Expected a structured initializer list");
1328 if (D
->isFieldDesignator()) {
1331 // If a designator has the form
1335 // then the current object (defined below) shall have
1336 // structure or union type and the identifier shall be the
1337 // name of a member of that type.
1338 const RecordType
*RT
= CurrentObjectType
->getAs
<RecordType
>();
1340 SourceLocation Loc
= D
->getDotLoc();
1341 if (Loc
.isInvalid())
1342 Loc
= D
->getFieldLoc();
1343 SemaRef
.Diag(Loc
, diag::err_field_designator_non_aggr
)
1344 << SemaRef
.getLangOptions().CPlusPlus
<< CurrentObjectType
;
1349 // Note: we perform a linear search of the fields here, despite
1350 // the fact that we have a faster lookup method, because we always
1351 // need to compute the field's index.
1352 FieldDecl
*KnownField
= D
->getField();
1353 IdentifierInfo
*FieldName
= D
->getFieldName();
1354 unsigned FieldIndex
= 0;
1355 RecordDecl::field_iterator
1356 Field
= RT
->getDecl()->field_begin(),
1357 FieldEnd
= RT
->getDecl()->field_end();
1358 for (; Field
!= FieldEnd
; ++Field
) {
1359 if (Field
->isUnnamedBitfield())
1362 // If we find a field representing an anonymous field, look in the
1363 // IndirectFieldDecl that follow for the designated initializer.
1364 if (!KnownField
&& Field
->isAnonymousStructOrUnion()) {
1365 if (IndirectFieldDecl
*IF
=
1366 FindIndirectFieldDesignator(*Field
, FieldName
)) {
1367 ExpandAnonymousFieldDesignator(SemaRef
, DIE
, DesigIdx
, IF
);
1368 D
= DIE
->getDesignator(DesigIdx
);
1372 if (KnownField
&& KnownField
== *Field
)
1374 if (FieldName
&& FieldName
== Field
->getIdentifier())
1380 if (Field
== FieldEnd
) {
1381 // There was no normal field in the struct with the designated
1382 // name. Perform another lookup for this name, which may find
1383 // something that we can't designate (e.g., a member function),
1384 // may find nothing, or may find a member of an anonymous
1386 DeclContext::lookup_result Lookup
= RT
->getDecl()->lookup(FieldName
);
1387 FieldDecl
*ReplacementField
= 0;
1388 if (Lookup
.first
== Lookup
.second
) {
1389 // Name lookup didn't find anything. Determine whether this
1390 // was a typo for another field name.
1391 LookupResult
R(SemaRef
, FieldName
, D
->getFieldLoc(),
1392 Sema::LookupMemberName
);
1393 if (SemaRef
.CorrectTypo(R
, /*Scope=*/0, /*SS=*/0, RT
->getDecl(), false,
1394 Sema::CTC_NoKeywords
) &&
1395 (ReplacementField
= R
.getAsSingle
<FieldDecl
>()) &&
1396 ReplacementField
->getDeclContext()->getRedeclContext()
1397 ->Equals(RT
->getDecl())) {
1398 SemaRef
.Diag(D
->getFieldLoc(),
1399 diag::err_field_designator_unknown_suggest
)
1400 << FieldName
<< CurrentObjectType
<< R
.getLookupName()
1401 << FixItHint::CreateReplacement(D
->getFieldLoc(),
1402 R
.getLookupName().getAsString());
1403 SemaRef
.Diag(ReplacementField
->getLocation(),
1404 diag::note_previous_decl
)
1405 << ReplacementField
->getDeclName();
1407 SemaRef
.Diag(D
->getFieldLoc(), diag::err_field_designator_unknown
)
1408 << FieldName
<< CurrentObjectType
;
1414 if (!ReplacementField
) {
1415 // Name lookup found something, but it wasn't a field.
1416 SemaRef
.Diag(D
->getFieldLoc(), diag::err_field_designator_nonfield
)
1418 SemaRef
.Diag((*Lookup
.first
)->getLocation(),
1419 diag::note_field_designator_found
);
1425 // The replacement field comes from typo correction; find it
1426 // in the list of fields.
1428 Field
= RT
->getDecl()->field_begin();
1429 for (; Field
!= FieldEnd
; ++Field
) {
1430 if (Field
->isUnnamedBitfield())
1433 if (ReplacementField
== *Field
||
1434 Field
->getIdentifier() == ReplacementField
->getIdentifier())
1442 // All of the fields of a union are located at the same place in
1443 // the initializer list.
1444 if (RT
->getDecl()->isUnion()) {
1446 StructuredList
->setInitializedFieldInUnion(*Field
);
1449 // Update the designator with the field declaration.
1450 D
->setField(*Field
);
1452 // Make sure that our non-designated initializer list has space
1453 // for a subobject corresponding to this field.
1454 if (FieldIndex
>= StructuredList
->getNumInits())
1455 StructuredList
->resizeInits(SemaRef
.Context
, FieldIndex
+ 1);
1457 // This designator names a flexible array member.
1458 if (Field
->getType()->isIncompleteArrayType()) {
1459 bool Invalid
= false;
1460 if ((DesigIdx
+ 1) != DIE
->size()) {
1461 // We can't designate an object within the flexible array
1462 // member (because GCC doesn't allow it).
1463 DesignatedInitExpr::Designator
*NextD
1464 = DIE
->getDesignator(DesigIdx
+ 1);
1465 SemaRef
.Diag(NextD
->getStartLocation(),
1466 diag::err_designator_into_flexible_array_member
)
1467 << SourceRange(NextD
->getStartLocation(),
1468 DIE
->getSourceRange().getEnd());
1469 SemaRef
.Diag(Field
->getLocation(), diag::note_flexible_array_member
)
1474 if (!hadError
&& !isa
<InitListExpr
>(DIE
->getInit()) &&
1475 !isa
<StringLiteral
>(DIE
->getInit())) {
1476 // The initializer is not an initializer list.
1477 SemaRef
.Diag(DIE
->getInit()->getSourceRange().getBegin(),
1478 diag::err_flexible_array_init_needs_braces
)
1479 << DIE
->getInit()->getSourceRange();
1480 SemaRef
.Diag(Field
->getLocation(), diag::note_flexible_array_member
)
1485 // Handle GNU flexible array initializers.
1486 if (!Invalid
&& !TopLevelObject
&&
1487 cast
<InitListExpr
>(DIE
->getInit())->getNumInits() > 0) {
1488 SemaRef
.Diag(DIE
->getSourceRange().getBegin(),
1489 diag::err_flexible_array_init_nonempty
)
1490 << DIE
->getSourceRange().getBegin();
1491 SemaRef
.Diag(Field
->getLocation(), diag::note_flexible_array_member
)
1501 // Initialize the array.
1502 bool prevHadError
= hadError
;
1503 unsigned newStructuredIndex
= FieldIndex
;
1504 unsigned OldIndex
= Index
;
1505 IList
->setInit(Index
, DIE
->getInit());
1507 InitializedEntity MemberEntity
=
1508 InitializedEntity::InitializeMember(*Field
, &Entity
);
1509 CheckSubElementType(MemberEntity
, IList
, Field
->getType(), Index
,
1510 StructuredList
, newStructuredIndex
);
1512 IList
->setInit(OldIndex
, DIE
);
1513 if (hadError
&& !prevHadError
) {
1518 StructuredIndex
= FieldIndex
;
1522 // Recurse to check later designated subobjects.
1523 QualType FieldType
= (*Field
)->getType();
1524 unsigned newStructuredIndex
= FieldIndex
;
1526 InitializedEntity MemberEntity
=
1527 InitializedEntity::InitializeMember(*Field
, &Entity
);
1528 if (CheckDesignatedInitializer(MemberEntity
, IList
, DIE
, DesigIdx
+ 1,
1529 FieldType
, 0, 0, Index
,
1530 StructuredList
, newStructuredIndex
,
1535 // Find the position of the next field to be initialized in this
1540 // If this the first designator, our caller will continue checking
1541 // the rest of this struct/class/union subobject.
1542 if (IsFirstDesignator
) {
1545 StructuredIndex
= FieldIndex
;
1549 if (!FinishSubobjectInit
)
1552 // We've already initialized something in the union; we're done.
1553 if (RT
->getDecl()->isUnion())
1556 // Check the remaining fields within this class/struct/union subobject.
1557 bool prevHadError
= hadError
;
1559 CheckStructUnionTypes(Entity
, IList
, CurrentObjectType
, Field
, false, Index
,
1560 StructuredList
, FieldIndex
);
1561 return hadError
&& !prevHadError
;
1566 // If a designator has the form
1568 // [ constant-expression ]
1570 // then the current object (defined below) shall have array
1571 // type and the expression shall be an integer constant
1572 // expression. If the array is of unknown size, any
1573 // nonnegative value is valid.
1575 // Additionally, cope with the GNU extension that permits
1576 // designators of the form
1578 // [ constant-expression ... constant-expression ]
1579 const ArrayType
*AT
= SemaRef
.Context
.getAsArrayType(CurrentObjectType
);
1581 SemaRef
.Diag(D
->getLBracketLoc(), diag::err_array_designator_non_array
)
1582 << CurrentObjectType
;
1587 Expr
*IndexExpr
= 0;
1588 llvm::APSInt DesignatedStartIndex
, DesignatedEndIndex
;
1589 if (D
->isArrayDesignator()) {
1590 IndexExpr
= DIE
->getArrayIndex(*D
);
1591 DesignatedStartIndex
= IndexExpr
->EvaluateAsInt(SemaRef
.Context
);
1592 DesignatedEndIndex
= DesignatedStartIndex
;
1594 assert(D
->isArrayRangeDesignator() && "Need array-range designator");
1597 DesignatedStartIndex
=
1598 DIE
->getArrayRangeStart(*D
)->EvaluateAsInt(SemaRef
.Context
);
1599 DesignatedEndIndex
=
1600 DIE
->getArrayRangeEnd(*D
)->EvaluateAsInt(SemaRef
.Context
);
1601 IndexExpr
= DIE
->getArrayRangeEnd(*D
);
1603 if (DesignatedStartIndex
.getZExtValue() !=DesignatedEndIndex
.getZExtValue())
1604 FullyStructuredList
->sawArrayRangeDesignator();
1607 if (isa
<ConstantArrayType
>(AT
)) {
1608 llvm::APSInt
MaxElements(cast
<ConstantArrayType
>(AT
)->getSize(), false);
1609 DesignatedStartIndex
1610 = DesignatedStartIndex
.extOrTrunc(MaxElements
.getBitWidth());
1611 DesignatedStartIndex
.setIsUnsigned(MaxElements
.isUnsigned());
1613 = DesignatedEndIndex
.extOrTrunc(MaxElements
.getBitWidth());
1614 DesignatedEndIndex
.setIsUnsigned(MaxElements
.isUnsigned());
1615 if (DesignatedEndIndex
>= MaxElements
) {
1616 SemaRef
.Diag(IndexExpr
->getSourceRange().getBegin(),
1617 diag::err_array_designator_too_large
)
1618 << DesignatedEndIndex
.toString(10) << MaxElements
.toString(10)
1619 << IndexExpr
->getSourceRange();
1624 // Make sure the bit-widths and signedness match.
1625 if (DesignatedStartIndex
.getBitWidth() > DesignatedEndIndex
.getBitWidth())
1627 = DesignatedEndIndex
.extend(DesignatedStartIndex
.getBitWidth());
1628 else if (DesignatedStartIndex
.getBitWidth() <
1629 DesignatedEndIndex
.getBitWidth())
1630 DesignatedStartIndex
1631 = DesignatedStartIndex
.extend(DesignatedEndIndex
.getBitWidth());
1632 DesignatedStartIndex
.setIsUnsigned(true);
1633 DesignatedEndIndex
.setIsUnsigned(true);
1636 // Make sure that our non-designated initializer list has space
1637 // for a subobject corresponding to this array element.
1638 if (DesignatedEndIndex
.getZExtValue() >= StructuredList
->getNumInits())
1639 StructuredList
->resizeInits(SemaRef
.Context
,
1640 DesignatedEndIndex
.getZExtValue() + 1);
1642 // Repeatedly perform subobject initializations in the range
1643 // [DesignatedStartIndex, DesignatedEndIndex].
1645 // Move to the next designator
1646 unsigned ElementIndex
= DesignatedStartIndex
.getZExtValue();
1647 unsigned OldIndex
= Index
;
1649 InitializedEntity ElementEntity
=
1650 InitializedEntity::InitializeElement(SemaRef
.Context
, 0, Entity
);
1652 while (DesignatedStartIndex
<= DesignatedEndIndex
) {
1653 // Recurse to check later designated subobjects.
1654 QualType ElementType
= AT
->getElementType();
1657 ElementEntity
.setElementIndex(ElementIndex
);
1658 if (CheckDesignatedInitializer(ElementEntity
, IList
, DIE
, DesigIdx
+ 1,
1659 ElementType
, 0, 0, Index
,
1660 StructuredList
, ElementIndex
,
1661 (DesignatedStartIndex
== DesignatedEndIndex
),
1665 // Move to the next index in the array that we'll be initializing.
1666 ++DesignatedStartIndex
;
1667 ElementIndex
= DesignatedStartIndex
.getZExtValue();
1670 // If this the first designator, our caller will continue checking
1671 // the rest of this array subobject.
1672 if (IsFirstDesignator
) {
1673 if (NextElementIndex
)
1674 *NextElementIndex
= DesignatedStartIndex
;
1675 StructuredIndex
= ElementIndex
;
1679 if (!FinishSubobjectInit
)
1682 // Check the remaining elements within this array subobject.
1683 bool prevHadError
= hadError
;
1684 CheckArrayType(Entity
, IList
, CurrentObjectType
, DesignatedStartIndex
,
1685 /*SubobjectIsDesignatorContext=*/false, Index
,
1686 StructuredList
, ElementIndex
);
1687 return hadError
&& !prevHadError
;
1690 // Get the structured initializer list for a subobject of type
1691 // @p CurrentObjectType.
1693 InitListChecker::getStructuredSubobjectInit(InitListExpr
*IList
, unsigned Index
,
1694 QualType CurrentObjectType
,
1695 InitListExpr
*StructuredList
,
1696 unsigned StructuredIndex
,
1697 SourceRange InitRange
) {
1698 Expr
*ExistingInit
= 0;
1699 if (!StructuredList
)
1700 ExistingInit
= SyntacticToSemantic
[IList
];
1701 else if (StructuredIndex
< StructuredList
->getNumInits())
1702 ExistingInit
= StructuredList
->getInit(StructuredIndex
);
1704 if (InitListExpr
*Result
= dyn_cast_or_null
<InitListExpr
>(ExistingInit
))
1708 // We are creating an initializer list that initializes the
1709 // subobjects of the current object, but there was already an
1710 // initialization that completely initialized the current
1711 // subobject, e.g., by a compound literal:
1713 // struct X { int a, b; };
1714 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1716 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1717 // designated initializer re-initializes the whole
1718 // subobject [0], overwriting previous initializers.
1719 SemaRef
.Diag(InitRange
.getBegin(),
1720 diag::warn_subobject_initializer_overrides
)
1722 SemaRef
.Diag(ExistingInit
->getSourceRange().getBegin(),
1723 diag::note_previous_initializer
)
1724 << /*FIXME:has side effects=*/0
1725 << ExistingInit
->getSourceRange();
1728 InitListExpr
*Result
1729 = new (SemaRef
.Context
) InitListExpr(SemaRef
.Context
,
1730 InitRange
.getBegin(), 0, 0,
1731 InitRange
.getEnd());
1733 Result
->setType(CurrentObjectType
.getNonLValueExprType(SemaRef
.Context
));
1735 // Pre-allocate storage for the structured initializer list.
1736 unsigned NumElements
= 0;
1737 unsigned NumInits
= 0;
1738 if (!StructuredList
)
1739 NumInits
= IList
->getNumInits();
1740 else if (Index
< IList
->getNumInits()) {
1741 if (InitListExpr
*SubList
= dyn_cast
<InitListExpr
>(IList
->getInit(Index
)))
1742 NumInits
= SubList
->getNumInits();
1745 if (const ArrayType
*AType
1746 = SemaRef
.Context
.getAsArrayType(CurrentObjectType
)) {
1747 if (const ConstantArrayType
*CAType
= dyn_cast
<ConstantArrayType
>(AType
)) {
1748 NumElements
= CAType
->getSize().getZExtValue();
1749 // Simple heuristic so that we don't allocate a very large
1750 // initializer with many empty entries at the end.
1751 if (NumInits
&& NumElements
> NumInits
)
1754 } else if (const VectorType
*VType
= CurrentObjectType
->getAs
<VectorType
>())
1755 NumElements
= VType
->getNumElements();
1756 else if (const RecordType
*RType
= CurrentObjectType
->getAs
<RecordType
>()) {
1757 RecordDecl
*RDecl
= RType
->getDecl();
1758 if (RDecl
->isUnion())
1761 NumElements
= std::distance(RDecl
->field_begin(),
1762 RDecl
->field_end());
1765 if (NumElements
< NumInits
)
1766 NumElements
= IList
->getNumInits();
1768 Result
->reserveInits(SemaRef
.Context
, NumElements
);
1770 // Link this new initializer list into the structured initializer
1773 StructuredList
->updateInit(SemaRef
.Context
, StructuredIndex
, Result
);
1775 Result
->setSyntacticForm(IList
);
1776 SyntacticToSemantic
[IList
] = Result
;
1782 /// Update the initializer at index @p StructuredIndex within the
1783 /// structured initializer list to the value @p expr.
1784 void InitListChecker::UpdateStructuredListElement(InitListExpr
*StructuredList
,
1785 unsigned &StructuredIndex
,
1787 // No structured initializer list to update
1788 if (!StructuredList
)
1791 if (Expr
*PrevInit
= StructuredList
->updateInit(SemaRef
.Context
,
1792 StructuredIndex
, expr
)) {
1793 // This initializer overwrites a previous initializer. Warn.
1794 SemaRef
.Diag(expr
->getSourceRange().getBegin(),
1795 diag::warn_initializer_overrides
)
1796 << expr
->getSourceRange();
1797 SemaRef
.Diag(PrevInit
->getSourceRange().getBegin(),
1798 diag::note_previous_initializer
)
1799 << /*FIXME:has side effects=*/0
1800 << PrevInit
->getSourceRange();
1806 /// Check that the given Index expression is a valid array designator
1807 /// value. This is essentailly just a wrapper around
1808 /// VerifyIntegerConstantExpression that also checks for negative values
1809 /// and produces a reasonable diagnostic if there is a
1810 /// failure. Returns true if there was an error, false otherwise. If
1811 /// everything went okay, Value will receive the value of the constant
1814 CheckArrayDesignatorExpr(Sema
&S
, Expr
*Index
, llvm::APSInt
&Value
) {
1815 SourceLocation Loc
= Index
->getSourceRange().getBegin();
1817 // Make sure this is an integer constant expression.
1818 if (S
.VerifyIntegerConstantExpression(Index
, &Value
))
1821 if (Value
.isSigned() && Value
.isNegative())
1822 return S
.Diag(Loc
, diag::err_array_designator_negative
)
1823 << Value
.toString(10) << Index
->getSourceRange();
1825 Value
.setIsUnsigned(true);
1829 ExprResult
Sema::ActOnDesignatedInitializer(Designation
&Desig
,
1833 typedef DesignatedInitExpr::Designator ASTDesignator
;
1835 bool Invalid
= false;
1836 llvm::SmallVector
<ASTDesignator
, 32> Designators
;
1837 llvm::SmallVector
<Expr
*, 32> InitExpressions
;
1839 // Build designators and check array designator expressions.
1840 for (unsigned Idx
= 0; Idx
< Desig
.getNumDesignators(); ++Idx
) {
1841 const Designator
&D
= Desig
.getDesignator(Idx
);
1842 switch (D
.getKind()) {
1843 case Designator::FieldDesignator
:
1844 Designators
.push_back(ASTDesignator(D
.getField(), D
.getDotLoc(),
1848 case Designator::ArrayDesignator
: {
1849 Expr
*Index
= static_cast<Expr
*>(D
.getArrayIndex());
1850 llvm::APSInt IndexValue
;
1851 if (!Index
->isTypeDependent() &&
1852 !Index
->isValueDependent() &&
1853 CheckArrayDesignatorExpr(*this, Index
, IndexValue
))
1856 Designators
.push_back(ASTDesignator(InitExpressions
.size(),
1858 D
.getRBracketLoc()));
1859 InitExpressions
.push_back(Index
);
1864 case Designator::ArrayRangeDesignator
: {
1865 Expr
*StartIndex
= static_cast<Expr
*>(D
.getArrayRangeStart());
1866 Expr
*EndIndex
= static_cast<Expr
*>(D
.getArrayRangeEnd());
1867 llvm::APSInt StartValue
;
1868 llvm::APSInt EndValue
;
1869 bool StartDependent
= StartIndex
->isTypeDependent() ||
1870 StartIndex
->isValueDependent();
1871 bool EndDependent
= EndIndex
->isTypeDependent() ||
1872 EndIndex
->isValueDependent();
1873 if ((!StartDependent
&&
1874 CheckArrayDesignatorExpr(*this, StartIndex
, StartValue
)) ||
1876 CheckArrayDesignatorExpr(*this, EndIndex
, EndValue
)))
1879 // Make sure we're comparing values with the same bit width.
1880 if (StartDependent
|| EndDependent
) {
1881 // Nothing to compute.
1882 } else if (StartValue
.getBitWidth() > EndValue
.getBitWidth())
1883 EndValue
= EndValue
.extend(StartValue
.getBitWidth());
1884 else if (StartValue
.getBitWidth() < EndValue
.getBitWidth())
1885 StartValue
= StartValue
.extend(EndValue
.getBitWidth());
1887 if (!StartDependent
&& !EndDependent
&& EndValue
< StartValue
) {
1888 Diag(D
.getEllipsisLoc(), diag::err_array_designator_empty_range
)
1889 << StartValue
.toString(10) << EndValue
.toString(10)
1890 << StartIndex
->getSourceRange() << EndIndex
->getSourceRange();
1893 Designators
.push_back(ASTDesignator(InitExpressions
.size(),
1896 D
.getRBracketLoc()));
1897 InitExpressions
.push_back(StartIndex
);
1898 InitExpressions
.push_back(EndIndex
);
1906 if (Invalid
|| Init
.isInvalid())
1909 // Clear out the expressions within the designation.
1910 Desig
.ClearExprs(*this);
1912 DesignatedInitExpr
*DIE
1913 = DesignatedInitExpr::Create(Context
,
1914 Designators
.data(), Designators
.size(),
1915 InitExpressions
.data(), InitExpressions
.size(),
1916 Loc
, GNUSyntax
, Init
.takeAs
<Expr
>());
1918 if (getLangOptions().CPlusPlus
)
1919 Diag(DIE
->getLocStart(), diag::ext_designated_init
)
1920 << DIE
->getSourceRange();
1925 bool Sema::CheckInitList(const InitializedEntity
&Entity
,
1926 InitListExpr
*&InitList
, QualType
&DeclType
) {
1927 InitListChecker
CheckInitList(*this, Entity
, InitList
, DeclType
);
1928 if (!CheckInitList
.HadError())
1929 InitList
= CheckInitList
.getFullyStructuredList();
1931 return CheckInitList
.HadError();
1934 //===----------------------------------------------------------------------===//
1935 // Initialization entity
1936 //===----------------------------------------------------------------------===//
1938 InitializedEntity::InitializedEntity(ASTContext
&Context
, unsigned Index
,
1939 const InitializedEntity
&Parent
)
1940 : Parent(&Parent
), Index(Index
)
1942 if (const ArrayType
*AT
= Context
.getAsArrayType(Parent
.getType())) {
1943 Kind
= EK_ArrayElement
;
1944 Type
= AT
->getElementType();
1946 Kind
= EK_VectorElement
;
1947 Type
= Parent
.getType()->getAs
<VectorType
>()->getElementType();
1951 InitializedEntity
InitializedEntity::InitializeBase(ASTContext
&Context
,
1952 CXXBaseSpecifier
*Base
,
1953 bool IsInheritedVirtualBase
)
1955 InitializedEntity Result
;
1956 Result
.Kind
= EK_Base
;
1957 Result
.Base
= reinterpret_cast<uintptr_t>(Base
);
1958 if (IsInheritedVirtualBase
)
1959 Result
.Base
|= 0x01;
1961 Result
.Type
= Base
->getType();
1965 DeclarationName
InitializedEntity::getName() const {
1966 switch (getKind()) {
1968 if (!VariableOrMember
)
1969 return DeclarationName();
1974 return VariableOrMember
->getDeclName();
1981 case EK_ArrayElement
:
1982 case EK_VectorElement
:
1983 case EK_BlockElement
:
1984 return DeclarationName();
1987 // Silence GCC warning
1988 return DeclarationName();
1991 DeclaratorDecl
*InitializedEntity::getDecl() const {
1992 switch (getKind()) {
1996 return VariableOrMember
;
2003 case EK_ArrayElement
:
2004 case EK_VectorElement
:
2005 case EK_BlockElement
:
2009 // Silence GCC warning
2013 bool InitializedEntity::allowsNRVO() const {
2014 switch (getKind()) {
2017 return LocAndNRVO
.NRVO
;
2025 case EK_ArrayElement
:
2026 case EK_VectorElement
:
2027 case EK_BlockElement
:
2034 //===----------------------------------------------------------------------===//
2035 // Initialization sequence
2036 //===----------------------------------------------------------------------===//
2038 void InitializationSequence::Step::Destroy() {
2040 case SK_ResolveAddressOfOverloadedFunction
:
2041 case SK_CastDerivedToBaseRValue
:
2042 case SK_CastDerivedToBaseXValue
:
2043 case SK_CastDerivedToBaseLValue
:
2044 case SK_BindReference
:
2045 case SK_BindReferenceToTemporary
:
2046 case SK_ExtraneousCopyToTemporary
:
2047 case SK_UserConversion
:
2048 case SK_QualificationConversionRValue
:
2049 case SK_QualificationConversionXValue
:
2050 case SK_QualificationConversionLValue
:
2051 case SK_ListInitialization
:
2052 case SK_ConstructorInitialization
:
2053 case SK_ZeroInitialization
:
2054 case SK_CAssignment
:
2056 case SK_ObjCObjectConversion
:
2059 case SK_ConversionSequence
:
2064 bool InitializationSequence::isDirectReferenceBinding() const {
2065 return getKind() == ReferenceBinding
&& Steps
.back().Kind
== SK_BindReference
;
2068 bool InitializationSequence::isAmbiguous() const {
2069 if (getKind() != FailedSequence
)
2072 switch (getFailureKind()) {
2073 case FK_TooManyInitsForReference
:
2074 case FK_ArrayNeedsInitList
:
2075 case FK_ArrayNeedsInitListOrStringLiteral
:
2076 case FK_AddressOfOverloadFailed
: // FIXME: Could do better
2077 case FK_NonConstLValueReferenceBindingToTemporary
:
2078 case FK_NonConstLValueReferenceBindingToUnrelated
:
2079 case FK_RValueReferenceBindingToLValue
:
2080 case FK_ReferenceInitDropsQualifiers
:
2081 case FK_ReferenceInitFailed
:
2082 case FK_ConversionFailed
:
2083 case FK_TooManyInitsForScalar
:
2084 case FK_ReferenceBindingToInitList
:
2085 case FK_InitListBadDestinationType
:
2086 case FK_DefaultInitOfConst
:
2090 case FK_ReferenceInitOverloadFailed
:
2091 case FK_UserConversionOverloadFailed
:
2092 case FK_ConstructorOverloadFailed
:
2093 return FailedOverloadResult
== OR_Ambiguous
;
2099 bool InitializationSequence::isConstructorInitialization() const {
2100 return !Steps
.empty() && Steps
.back().Kind
== SK_ConstructorInitialization
;
2103 void InitializationSequence::AddAddressOverloadResolutionStep(
2104 FunctionDecl
*Function
,
2105 DeclAccessPair Found
) {
2107 S
.Kind
= SK_ResolveAddressOfOverloadedFunction
;
2108 S
.Type
= Function
->getType();
2109 S
.Function
.Function
= Function
;
2110 S
.Function
.FoundDecl
= Found
;
2114 void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType
,
2118 case VK_RValue
: S
.Kind
= SK_CastDerivedToBaseRValue
; break;
2119 case VK_XValue
: S
.Kind
= SK_CastDerivedToBaseXValue
; break;
2120 case VK_LValue
: S
.Kind
= SK_CastDerivedToBaseLValue
; break;
2121 default: llvm_unreachable("No such category");
2127 void InitializationSequence::AddReferenceBindingStep(QualType T
,
2128 bool BindingTemporary
) {
2130 S
.Kind
= BindingTemporary
? SK_BindReferenceToTemporary
: SK_BindReference
;
2135 void InitializationSequence::AddExtraneousCopyToTemporary(QualType T
) {
2137 S
.Kind
= SK_ExtraneousCopyToTemporary
;
2142 void InitializationSequence::AddUserConversionStep(FunctionDecl
*Function
,
2143 DeclAccessPair FoundDecl
,
2146 S
.Kind
= SK_UserConversion
;
2148 S
.Function
.Function
= Function
;
2149 S
.Function
.FoundDecl
= FoundDecl
;
2153 void InitializationSequence::AddQualificationConversionStep(QualType Ty
,
2156 S
.Kind
= SK_QualificationConversionRValue
; // work around a gcc warning
2159 S
.Kind
= SK_QualificationConversionRValue
;
2162 S
.Kind
= SK_QualificationConversionXValue
;
2165 S
.Kind
= SK_QualificationConversionLValue
;
2172 void InitializationSequence::AddConversionSequenceStep(
2173 const ImplicitConversionSequence
&ICS
,
2176 S
.Kind
= SK_ConversionSequence
;
2178 S
.ICS
= new ImplicitConversionSequence(ICS
);
2182 void InitializationSequence::AddListInitializationStep(QualType T
) {
2184 S
.Kind
= SK_ListInitialization
;
2190 InitializationSequence::AddConstructorInitializationStep(
2191 CXXConstructorDecl
*Constructor
,
2192 AccessSpecifier Access
,
2195 S
.Kind
= SK_ConstructorInitialization
;
2197 S
.Function
.Function
= Constructor
;
2198 S
.Function
.FoundDecl
= DeclAccessPair::make(Constructor
, Access
);
2202 void InitializationSequence::AddZeroInitializationStep(QualType T
) {
2204 S
.Kind
= SK_ZeroInitialization
;
2209 void InitializationSequence::AddCAssignmentStep(QualType T
) {
2211 S
.Kind
= SK_CAssignment
;
2216 void InitializationSequence::AddStringInitStep(QualType T
) {
2218 S
.Kind
= SK_StringInit
;
2223 void InitializationSequence::AddObjCObjectConversionStep(QualType T
) {
2225 S
.Kind
= SK_ObjCObjectConversion
;
2230 void InitializationSequence::SetOverloadFailure(FailureKind Failure
,
2231 OverloadingResult Result
) {
2232 SequenceKind
= FailedSequence
;
2233 this->Failure
= Failure
;
2234 this->FailedOverloadResult
= Result
;
2237 //===----------------------------------------------------------------------===//
2238 // Attempt initialization
2239 //===----------------------------------------------------------------------===//
2241 /// \brief Attempt list initialization (C++0x [dcl.init.list])
2242 static void TryListInitialization(Sema
&S
,
2243 const InitializedEntity
&Entity
,
2244 const InitializationKind
&Kind
,
2245 InitListExpr
*InitList
,
2246 InitializationSequence
&Sequence
) {
2247 // FIXME: We only perform rudimentary checking of list
2248 // initializations at this point, then assume that any list
2249 // initialization of an array, aggregate, or scalar will be
2250 // well-formed. When we actually "perform" list initialization, we'll
2251 // do all of the necessary checking. C++0x initializer lists will
2252 // force us to perform more checking here.
2253 Sequence
.setSequenceKind(InitializationSequence::ListInitialization
);
2255 QualType DestType
= Entity
.getType();
2257 // C++ [dcl.init]p13:
2258 // If T is a scalar type, then a declaration of the form
2265 if (DestType
->isScalarType()) {
2266 if (InitList
->getNumInits() > 1 && S
.getLangOptions().CPlusPlus
) {
2267 Sequence
.SetFailed(InitializationSequence::FK_TooManyInitsForScalar
);
2271 // Assume scalar initialization from a single value works.
2272 } else if (DestType
->isAggregateType()) {
2273 // Assume aggregate initialization works.
2274 } else if (DestType
->isVectorType()) {
2275 // Assume vector initialization works.
2276 } else if (DestType
->isReferenceType()) {
2277 // FIXME: C++0x defines behavior for this.
2278 Sequence
.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList
);
2280 } else if (DestType
->isRecordType()) {
2281 // FIXME: C++0x defines behavior for this
2282 Sequence
.SetFailed(InitializationSequence::FK_InitListBadDestinationType
);
2285 // Add a general "list initialization" step.
2286 Sequence
.AddListInitializationStep(DestType
);
2289 /// \brief Try a reference initialization that involves calling a conversion
2291 static OverloadingResult
TryRefInitWithConversionFunction(Sema
&S
,
2292 const InitializedEntity
&Entity
,
2293 const InitializationKind
&Kind
,
2296 InitializationSequence
&Sequence
) {
2297 QualType DestType
= Entity
.getType();
2298 QualType cv1T1
= DestType
->getAs
<ReferenceType
>()->getPointeeType();
2299 QualType T1
= cv1T1
.getUnqualifiedType();
2300 QualType cv2T2
= Initializer
->getType();
2301 QualType T2
= cv2T2
.getUnqualifiedType();
2304 bool ObjCConversion
;
2305 assert(!S
.CompareReferenceRelationship(Initializer
->getLocStart(),
2306 T1
, T2
, DerivedToBase
,
2308 "Must have incompatible references when binding via conversion");
2309 (void)DerivedToBase
;
2310 (void)ObjCConversion
;
2312 // Build the candidate set directly in the initialization sequence
2313 // structure, so that it will persist if we fail.
2314 OverloadCandidateSet
&CandidateSet
= Sequence
.getFailedCandidateSet();
2315 CandidateSet
.clear();
2317 // Determine whether we are allowed to call explicit constructors or
2318 // explicit conversion operators.
2319 bool AllowExplicit
= Kind
.getKind() == InitializationKind::IK_Direct
;
2321 const RecordType
*T1RecordType
= 0;
2322 if (AllowRValues
&& (T1RecordType
= T1
->getAs
<RecordType
>()) &&
2323 !S
.RequireCompleteType(Kind
.getLocation(), T1
, 0)) {
2324 // The type we're converting to is a class type. Enumerate its constructors
2325 // to see if there is a suitable conversion.
2326 CXXRecordDecl
*T1RecordDecl
= cast
<CXXRecordDecl
>(T1RecordType
->getDecl());
2328 DeclContext::lookup_iterator Con
, ConEnd
;
2329 for (llvm::tie(Con
, ConEnd
) = S
.LookupConstructors(T1RecordDecl
);
2330 Con
!= ConEnd
; ++Con
) {
2331 NamedDecl
*D
= *Con
;
2332 DeclAccessPair FoundDecl
= DeclAccessPair::make(D
, D
->getAccess());
2334 // Find the constructor (which may be a template).
2335 CXXConstructorDecl
*Constructor
= 0;
2336 FunctionTemplateDecl
*ConstructorTmpl
= dyn_cast
<FunctionTemplateDecl
>(D
);
2337 if (ConstructorTmpl
)
2338 Constructor
= cast
<CXXConstructorDecl
>(
2339 ConstructorTmpl
->getTemplatedDecl());
2341 Constructor
= cast
<CXXConstructorDecl
>(D
);
2343 if (!Constructor
->isInvalidDecl() &&
2344 Constructor
->isConvertingConstructor(AllowExplicit
)) {
2345 if (ConstructorTmpl
)
2346 S
.AddTemplateOverloadCandidate(ConstructorTmpl
, FoundDecl
,
2348 &Initializer
, 1, CandidateSet
,
2349 /*SuppressUserConversions=*/true);
2351 S
.AddOverloadCandidate(Constructor
, FoundDecl
,
2352 &Initializer
, 1, CandidateSet
,
2353 /*SuppressUserConversions=*/true);
2357 if (T1RecordType
&& T1RecordType
->getDecl()->isInvalidDecl())
2358 return OR_No_Viable_Function
;
2360 const RecordType
*T2RecordType
= 0;
2361 if ((T2RecordType
= T2
->getAs
<RecordType
>()) &&
2362 !S
.RequireCompleteType(Kind
.getLocation(), T2
, 0)) {
2363 // The type we're converting from is a class type, enumerate its conversion
2365 CXXRecordDecl
*T2RecordDecl
= cast
<CXXRecordDecl
>(T2RecordType
->getDecl());
2367 const UnresolvedSetImpl
*Conversions
2368 = T2RecordDecl
->getVisibleConversionFunctions();
2369 for (UnresolvedSetImpl::const_iterator I
= Conversions
->begin(),
2370 E
= Conversions
->end(); I
!= E
; ++I
) {
2372 CXXRecordDecl
*ActingDC
= cast
<CXXRecordDecl
>(D
->getDeclContext());
2373 if (isa
<UsingShadowDecl
>(D
))
2374 D
= cast
<UsingShadowDecl
>(D
)->getTargetDecl();
2376 FunctionTemplateDecl
*ConvTemplate
= dyn_cast
<FunctionTemplateDecl
>(D
);
2377 CXXConversionDecl
*Conv
;
2379 Conv
= cast
<CXXConversionDecl
>(ConvTemplate
->getTemplatedDecl());
2381 Conv
= cast
<CXXConversionDecl
>(D
);
2383 // If the conversion function doesn't return a reference type,
2384 // it can't be considered for this conversion unless we're allowed to
2385 // consider rvalues.
2386 // FIXME: Do we need to make sure that we only consider conversion
2387 // candidates with reference-compatible results? That might be needed to
2389 if ((AllowExplicit
|| !Conv
->isExplicit()) &&
2390 (AllowRValues
|| Conv
->getConversionType()->isLValueReferenceType())){
2392 S
.AddTemplateConversionCandidate(ConvTemplate
, I
.getPair(),
2393 ActingDC
, Initializer
,
2394 DestType
, CandidateSet
);
2396 S
.AddConversionCandidate(Conv
, I
.getPair(), ActingDC
,
2397 Initializer
, DestType
, CandidateSet
);
2401 if (T2RecordType
&& T2RecordType
->getDecl()->isInvalidDecl())
2402 return OR_No_Viable_Function
;
2404 SourceLocation DeclLoc
= Initializer
->getLocStart();
2406 // Perform overload resolution. If it fails, return the failed result.
2407 OverloadCandidateSet::iterator Best
;
2408 if (OverloadingResult Result
2409 = CandidateSet
.BestViableFunction(S
, DeclLoc
, Best
, true))
2412 FunctionDecl
*Function
= Best
->Function
;
2414 // Compute the returned type of the conversion.
2415 if (isa
<CXXConversionDecl
>(Function
))
2416 T2
= Function
->getResultType();
2420 // Add the user-defined conversion step.
2421 Sequence
.AddUserConversionStep(Function
, Best
->FoundDecl
,
2422 T2
.getNonLValueExprType(S
.Context
));
2424 // Determine whether we need to perform derived-to-base or
2425 // cv-qualification adjustments.
2426 ExprValueKind VK
= VK_RValue
;
2427 if (T2
->isLValueReferenceType())
2429 else if (const RValueReferenceType
*RRef
= T2
->getAs
<RValueReferenceType
>())
2430 VK
= RRef
->getPointeeType()->isFunctionType() ? VK_LValue
: VK_XValue
;
2432 bool NewDerivedToBase
= false;
2433 bool NewObjCConversion
= false;
2434 Sema::ReferenceCompareResult NewRefRelationship
2435 = S
.CompareReferenceRelationship(DeclLoc
, T1
,
2436 T2
.getNonLValueExprType(S
.Context
),
2437 NewDerivedToBase
, NewObjCConversion
);
2438 if (NewRefRelationship
== Sema::Ref_Incompatible
) {
2439 // If the type we've converted to is not reference-related to the
2440 // type we're looking for, then there is another conversion step
2441 // we need to perform to produce a temporary of the right type
2442 // that we'll be binding to.
2443 ImplicitConversionSequence ICS
;
2445 ICS
.Standard
= Best
->FinalConversion
;
2446 T2
= ICS
.Standard
.getToType(2);
2447 Sequence
.AddConversionSequenceStep(ICS
, T2
);
2448 } else if (NewDerivedToBase
)
2449 Sequence
.AddDerivedToBaseCastStep(
2450 S
.Context
.getQualifiedType(T1
,
2451 T2
.getNonReferenceType().getQualifiers()),
2453 else if (NewObjCConversion
)
2454 Sequence
.AddObjCObjectConversionStep(
2455 S
.Context
.getQualifiedType(T1
,
2456 T2
.getNonReferenceType().getQualifiers()));
2458 if (cv1T1
.getQualifiers() != T2
.getNonReferenceType().getQualifiers())
2459 Sequence
.AddQualificationConversionStep(cv1T1
, VK
);
2461 Sequence
.AddReferenceBindingStep(cv1T1
, !T2
->isReferenceType());
2465 /// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2466 static void TryReferenceInitialization(Sema
&S
,
2467 const InitializedEntity
&Entity
,
2468 const InitializationKind
&Kind
,
2470 InitializationSequence
&Sequence
) {
2471 Sequence
.setSequenceKind(InitializationSequence::ReferenceBinding
);
2473 QualType DestType
= Entity
.getType();
2474 QualType cv1T1
= DestType
->getAs
<ReferenceType
>()->getPointeeType();
2476 QualType T1
= S
.Context
.getUnqualifiedArrayType(cv1T1
, T1Quals
);
2477 QualType cv2T2
= Initializer
->getType();
2479 QualType T2
= S
.Context
.getUnqualifiedArrayType(cv2T2
, T2Quals
);
2480 SourceLocation DeclLoc
= Initializer
->getLocStart();
2482 // If the initializer is the address of an overloaded function, try
2483 // to resolve the overloaded function. If all goes well, T2 is the
2484 // type of the resulting function.
2485 if (S
.Context
.getCanonicalType(T2
) == S
.Context
.OverloadTy
) {
2486 DeclAccessPair Found
;
2487 if (FunctionDecl
*Fn
= S
.ResolveAddressOfOverloadedFunction(Initializer
,
2491 Sequence
.AddAddressOverloadResolutionStep(Fn
, Found
);
2492 cv2T2
= Fn
->getType();
2493 T2
= cv2T2
.getUnqualifiedType();
2494 } else if (!T1
->isRecordType()) {
2495 Sequence
.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed
);
2500 // Compute some basic properties of the types and the initializer.
2501 bool isLValueRef
= DestType
->isLValueReferenceType();
2502 bool isRValueRef
= !isLValueRef
;
2503 bool DerivedToBase
= false;
2504 bool ObjCConversion
= false;
2505 Expr::Classification InitCategory
= Initializer
->Classify(S
.Context
);
2506 Sema::ReferenceCompareResult RefRelationship
2507 = S
.CompareReferenceRelationship(DeclLoc
, cv1T1
, cv2T2
, DerivedToBase
,
2510 // C++0x [dcl.init.ref]p5:
2511 // A reference to type "cv1 T1" is initialized by an expression of type
2512 // "cv2 T2" as follows:
2514 // - If the reference is an lvalue reference and the initializer
2516 // Note the analogous bullet points for rvlaue refs to functions. Because
2517 // there are no function rvalues in C++, rvalue refs to functions are treated
2518 // like lvalue refs.
2519 OverloadingResult ConvOvlResult
= OR_Success
;
2520 bool T1Function
= T1
->isFunctionType();
2521 if (isLValueRef
|| T1Function
) {
2522 if (InitCategory
.isLValue() &&
2523 (RefRelationship
>= Sema::Ref_Compatible_With_Added_Qualification
||
2524 (Kind
.isCStyleOrFunctionalCast() &&
2525 RefRelationship
== Sema::Ref_Related
))) {
2526 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2527 // reference-compatible with "cv2 T2," or
2529 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
2530 // bit-field when we're determining whether the reference initialization
2531 // can occur. However, we do pay attention to whether it is a bit-field
2532 // to decide whether we're actually binding to a temporary created from
2535 Sequence
.AddDerivedToBaseCastStep(
2536 S
.Context
.getQualifiedType(T1
, T2Quals
),
2538 else if (ObjCConversion
)
2539 Sequence
.AddObjCObjectConversionStep(
2540 S
.Context
.getQualifiedType(T1
, T2Quals
));
2542 if (T1Quals
!= T2Quals
)
2543 Sequence
.AddQualificationConversionStep(cv1T1
, VK_LValue
);
2544 bool BindingTemporary
= T1Quals
.hasConst() && !T1Quals
.hasVolatile() &&
2545 (Initializer
->getBitField() || Initializer
->refersToVectorElement());
2546 Sequence
.AddReferenceBindingStep(cv1T1
, BindingTemporary
);
2550 // - has a class type (i.e., T2 is a class type), where T1 is not
2551 // reference-related to T2, and can be implicitly converted to an
2552 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2553 // with "cv3 T3" (this conversion is selected by enumerating the
2554 // applicable conversion functions (13.3.1.6) and choosing the best
2555 // one through overload resolution (13.3)),
2556 // If we have an rvalue ref to function type here, the rhs must be
2558 if (RefRelationship
== Sema::Ref_Incompatible
&& T2
->isRecordType() &&
2559 (isLValueRef
|| InitCategory
.isRValue())) {
2560 ConvOvlResult
= TryRefInitWithConversionFunction(S
, Entity
, Kind
,
2562 /*AllowRValues=*/isRValueRef
,
2564 if (ConvOvlResult
== OR_Success
)
2566 if (ConvOvlResult
!= OR_No_Viable_Function
) {
2567 Sequence
.SetOverloadFailure(
2568 InitializationSequence::FK_ReferenceInitOverloadFailed
,
2574 // - Otherwise, the reference shall be an lvalue reference to a
2575 // non-volatile const type (i.e., cv1 shall be const), or the reference
2576 // shall be an rvalue reference.
2577 if (isLValueRef
&& !(T1Quals
.hasConst() && !T1Quals
.hasVolatile())) {
2578 if (S
.Context
.getCanonicalType(T2
) == S
.Context
.OverloadTy
)
2579 Sequence
.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed
);
2580 else if (ConvOvlResult
&& !Sequence
.getFailedCandidateSet().empty())
2581 Sequence
.SetOverloadFailure(
2582 InitializationSequence::FK_ReferenceInitOverloadFailed
,
2585 Sequence
.SetFailed(InitCategory
.isLValue()
2586 ? (RefRelationship
== Sema::Ref_Related
2587 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2588 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated
)
2589 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary
);
2594 // - If the initializer expression
2595 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
2596 // "cv1 T1" is reference-compatible with "cv2 T2"
2597 // Note: functions are handled below.
2599 (RefRelationship
>= Sema::Ref_Compatible_With_Added_Qualification
||
2600 (Kind
.isCStyleOrFunctionalCast() &&
2601 RefRelationship
== Sema::Ref_Related
)) &&
2602 (InitCategory
.isXValue() ||
2603 (InitCategory
.isPRValue() && T2
->isRecordType()) ||
2604 (InitCategory
.isPRValue() && T2
->isArrayType()))) {
2605 ExprValueKind ValueKind
= InitCategory
.isXValue()? VK_XValue
: VK_RValue
;
2606 if (InitCategory
.isPRValue() && T2
->isRecordType()) {
2607 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2608 // compiler the freedom to perform a copy here or bind to the
2609 // object, while C++0x requires that we bind directly to the
2610 // object. Hence, we always bind to the object without making an
2611 // extra copy. However, in C++03 requires that we check for the
2612 // presence of a suitable copy constructor:
2614 // The constructor that would be used to make the copy shall
2615 // be callable whether or not the copy is actually done.
2616 if (!S
.getLangOptions().CPlusPlus0x
&& !S
.getLangOptions().Microsoft
)
2617 Sequence
.AddExtraneousCopyToTemporary(cv2T2
);
2621 Sequence
.AddDerivedToBaseCastStep(S
.Context
.getQualifiedType(T1
, T2Quals
),
2623 else if (ObjCConversion
)
2624 Sequence
.AddObjCObjectConversionStep(
2625 S
.Context
.getQualifiedType(T1
, T2Quals
));
2627 if (T1Quals
!= T2Quals
)
2628 Sequence
.AddQualificationConversionStep(cv1T1
, ValueKind
);
2629 Sequence
.AddReferenceBindingStep(cv1T1
,
2630 /*bindingTemporary=*/(InitCategory
.isPRValue() && !T2
->isArrayType()));
2634 // - has a class type (i.e., T2 is a class type), where T1 is not
2635 // reference-related to T2, and can be implicitly converted to an
2636 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
2637 // where "cv1 T1" is reference-compatible with "cv3 T3",
2638 if (T2
->isRecordType()) {
2639 if (RefRelationship
== Sema::Ref_Incompatible
) {
2640 ConvOvlResult
= TryRefInitWithConversionFunction(S
, Entity
,
2642 /*AllowRValues=*/true,
2645 Sequence
.SetOverloadFailure(
2646 InitializationSequence::FK_ReferenceInitOverloadFailed
,
2652 Sequence
.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers
);
2656 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
2657 // from the initializer expression using the rules for a non-reference
2658 // copy initialization (8.5). The reference is then bound to the
2661 // Determine whether we are allowed to call explicit constructors or
2662 // explicit conversion operators.
2663 bool AllowExplicit
= (Kind
.getKind() == InitializationKind::IK_Direct
);
2665 InitializedEntity TempEntity
= InitializedEntity::InitializeTemporary(cv1T1
);
2667 if (S
.TryImplicitConversion(Sequence
, TempEntity
, Initializer
,
2668 /*SuppressUserConversions*/ false,
2670 /*FIXME:InOverloadResolution=*/false,
2671 /*CStyle=*/Kind
.isCStyleOrFunctionalCast())) {
2672 // FIXME: Use the conversion function set stored in ICS to turn
2673 // this into an overloading ambiguity diagnostic. However, we need
2674 // to keep that set as an OverloadCandidateSet rather than as some
2675 // other kind of set.
2676 if (ConvOvlResult
&& !Sequence
.getFailedCandidateSet().empty())
2677 Sequence
.SetOverloadFailure(
2678 InitializationSequence::FK_ReferenceInitOverloadFailed
,
2680 else if (S
.Context
.getCanonicalType(T2
) == S
.Context
.OverloadTy
)
2681 Sequence
.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed
);
2683 Sequence
.SetFailed(InitializationSequence::FK_ReferenceInitFailed
);
2687 // [...] If T1 is reference-related to T2, cv1 must be the
2688 // same cv-qualification as, or greater cv-qualification
2689 // than, cv2; otherwise, the program is ill-formed.
2690 unsigned T1CVRQuals
= T1Quals
.getCVRQualifiers();
2691 unsigned T2CVRQuals
= T2Quals
.getCVRQualifiers();
2692 if (RefRelationship
== Sema::Ref_Related
&&
2693 (T1CVRQuals
| T2CVRQuals
) != T1CVRQuals
) {
2694 Sequence
.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers
);
2698 // [...] If T1 is reference-related to T2 and the reference is an rvalue
2699 // reference, the initializer expression shall not be an lvalue.
2700 if (RefRelationship
>= Sema::Ref_Related
&& !isLValueRef
&&
2701 InitCategory
.isLValue()) {
2703 InitializationSequence::FK_RValueReferenceBindingToLValue
);
2707 Sequence
.AddReferenceBindingStep(cv1T1
, /*bindingTemporary=*/true);
2711 /// \brief Attempt character array initialization from a string literal
2712 /// (C++ [dcl.init.string], C99 6.7.8).
2713 static void TryStringLiteralInitialization(Sema
&S
,
2714 const InitializedEntity
&Entity
,
2715 const InitializationKind
&Kind
,
2717 InitializationSequence
&Sequence
) {
2718 Sequence
.setSequenceKind(InitializationSequence::StringInit
);
2719 Sequence
.AddStringInitStep(Entity
.getType());
2722 /// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2723 /// enumerates the constructors of the initialized entity and performs overload
2724 /// resolution to select the best.
2725 static void TryConstructorInitialization(Sema
&S
,
2726 const InitializedEntity
&Entity
,
2727 const InitializationKind
&Kind
,
2728 Expr
**Args
, unsigned NumArgs
,
2730 InitializationSequence
&Sequence
) {
2731 Sequence
.setSequenceKind(InitializationSequence::ConstructorInitialization
);
2733 // Build the candidate set directly in the initialization sequence
2734 // structure, so that it will persist if we fail.
2735 OverloadCandidateSet
&CandidateSet
= Sequence
.getFailedCandidateSet();
2736 CandidateSet
.clear();
2738 // Determine whether we are allowed to call explicit constructors or
2739 // explicit conversion operators.
2740 bool AllowExplicit
= (Kind
.getKind() == InitializationKind::IK_Direct
||
2741 Kind
.getKind() == InitializationKind::IK_Value
||
2742 Kind
.getKind() == InitializationKind::IK_Default
);
2744 // The type we're constructing needs to be complete.
2745 if (S
.RequireCompleteType(Kind
.getLocation(), DestType
, 0)) {
2746 Sequence
.SetFailed(InitializationSequence::FK_Incomplete
);
2750 // The type we're converting to is a class type. Enumerate its constructors
2751 // to see if one is suitable.
2752 const RecordType
*DestRecordType
= DestType
->getAs
<RecordType
>();
2753 assert(DestRecordType
&& "Constructor initialization requires record type");
2754 CXXRecordDecl
*DestRecordDecl
2755 = cast
<CXXRecordDecl
>(DestRecordType
->getDecl());
2757 DeclContext::lookup_iterator Con
, ConEnd
;
2758 for (llvm::tie(Con
, ConEnd
) = S
.LookupConstructors(DestRecordDecl
);
2759 Con
!= ConEnd
; ++Con
) {
2760 NamedDecl
*D
= *Con
;
2761 DeclAccessPair FoundDecl
= DeclAccessPair::make(D
, D
->getAccess());
2762 bool SuppressUserConversions
= false;
2764 // Find the constructor (which may be a template).
2765 CXXConstructorDecl
*Constructor
= 0;
2766 FunctionTemplateDecl
*ConstructorTmpl
= dyn_cast
<FunctionTemplateDecl
>(D
);
2767 if (ConstructorTmpl
)
2768 Constructor
= cast
<CXXConstructorDecl
>(
2769 ConstructorTmpl
->getTemplatedDecl());
2771 Constructor
= cast
<CXXConstructorDecl
>(D
);
2773 // If we're performing copy initialization using a copy constructor, we
2774 // suppress user-defined conversions on the arguments.
2775 // FIXME: Move constructors?
2776 if (Kind
.getKind() == InitializationKind::IK_Copy
&&
2777 Constructor
->isCopyConstructor())
2778 SuppressUserConversions
= true;
2781 if (!Constructor
->isInvalidDecl() &&
2782 (AllowExplicit
|| !Constructor
->isExplicit())) {
2783 if (ConstructorTmpl
)
2784 S
.AddTemplateOverloadCandidate(ConstructorTmpl
, FoundDecl
,
2786 Args
, NumArgs
, CandidateSet
,
2787 SuppressUserConversions
);
2789 S
.AddOverloadCandidate(Constructor
, FoundDecl
,
2790 Args
, NumArgs
, CandidateSet
,
2791 SuppressUserConversions
);
2795 SourceLocation DeclLoc
= Kind
.getLocation();
2797 // Perform overload resolution. If it fails, return the failed result.
2798 OverloadCandidateSet::iterator Best
;
2799 if (OverloadingResult Result
2800 = CandidateSet
.BestViableFunction(S
, DeclLoc
, Best
)) {
2801 Sequence
.SetOverloadFailure(
2802 InitializationSequence::FK_ConstructorOverloadFailed
,
2807 // C++0x [dcl.init]p6:
2808 // If a program calls for the default initialization of an object
2809 // of a const-qualified type T, T shall be a class type with a
2810 // user-provided default constructor.
2811 if (Kind
.getKind() == InitializationKind::IK_Default
&&
2812 Entity
.getType().isConstQualified() &&
2813 cast
<CXXConstructorDecl
>(Best
->Function
)->isImplicit()) {
2814 Sequence
.SetFailed(InitializationSequence::FK_DefaultInitOfConst
);
2818 // Add the constructor initialization step. Any cv-qualification conversion is
2819 // subsumed by the initialization.
2820 Sequence
.AddConstructorInitializationStep(
2821 cast
<CXXConstructorDecl
>(Best
->Function
),
2822 Best
->FoundDecl
.getAccess(),
2826 /// \brief Attempt value initialization (C++ [dcl.init]p7).
2827 static void TryValueInitialization(Sema
&S
,
2828 const InitializedEntity
&Entity
,
2829 const InitializationKind
&Kind
,
2830 InitializationSequence
&Sequence
) {
2831 // C++ [dcl.init]p5:
2833 // To value-initialize an object of type T means:
2834 QualType T
= Entity
.getType();
2836 // -- if T is an array type, then each element is value-initialized;
2837 while (const ArrayType
*AT
= S
.Context
.getAsArrayType(T
))
2838 T
= AT
->getElementType();
2840 if (const RecordType
*RT
= T
->getAs
<RecordType
>()) {
2841 if (CXXRecordDecl
*ClassDecl
= dyn_cast
<CXXRecordDecl
>(RT
->getDecl())) {
2842 // -- if T is a class type (clause 9) with a user-declared
2843 // constructor (12.1), then the default constructor for T is
2844 // called (and the initialization is ill-formed if T has no
2845 // accessible default constructor);
2847 // FIXME: we really want to refer to a single subobject of the array,
2848 // but Entity doesn't have a way to capture that (yet).
2849 if (ClassDecl
->hasUserDeclaredConstructor())
2850 return TryConstructorInitialization(S
, Entity
, Kind
, 0, 0, T
, Sequence
);
2852 // -- if T is a (possibly cv-qualified) non-union class type
2853 // without a user-provided constructor, then the object is
2854 // zero-initialized and, if T's implicitly-declared default
2855 // constructor is non-trivial, that constructor is called.
2856 if ((ClassDecl
->getTagKind() == TTK_Class
||
2857 ClassDecl
->getTagKind() == TTK_Struct
)) {
2858 Sequence
.AddZeroInitializationStep(Entity
.getType());
2859 return TryConstructorInitialization(S
, Entity
, Kind
, 0, 0, T
, Sequence
);
2864 Sequence
.AddZeroInitializationStep(Entity
.getType());
2865 Sequence
.setSequenceKind(InitializationSequence::ZeroInitialization
);
2868 /// \brief Attempt default initialization (C++ [dcl.init]p6).
2869 static void TryDefaultInitialization(Sema
&S
,
2870 const InitializedEntity
&Entity
,
2871 const InitializationKind
&Kind
,
2872 InitializationSequence
&Sequence
) {
2873 assert(Kind
.getKind() == InitializationKind::IK_Default
);
2875 // C++ [dcl.init]p6:
2876 // To default-initialize an object of type T means:
2877 // - if T is an array type, each element is default-initialized;
2878 QualType DestType
= Entity
.getType();
2879 while (const ArrayType
*Array
= S
.Context
.getAsArrayType(DestType
))
2880 DestType
= Array
->getElementType();
2882 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2883 // constructor for T is called (and the initialization is ill-formed if
2884 // T has no accessible default constructor);
2885 if (DestType
->isRecordType() && S
.getLangOptions().CPlusPlus
) {
2886 TryConstructorInitialization(S
, Entity
, Kind
, 0, 0, DestType
, Sequence
);
2890 // - otherwise, no initialization is performed.
2891 Sequence
.setSequenceKind(InitializationSequence::NoInitialization
);
2893 // If a program calls for the default initialization of an object of
2894 // a const-qualified type T, T shall be a class type with a user-provided
2895 // default constructor.
2896 if (DestType
.isConstQualified() && S
.getLangOptions().CPlusPlus
)
2897 Sequence
.SetFailed(InitializationSequence::FK_DefaultInitOfConst
);
2900 /// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2901 /// which enumerates all conversion functions and performs overload resolution
2902 /// to select the best.
2903 static void TryUserDefinedConversion(Sema
&S
,
2904 const InitializedEntity
&Entity
,
2905 const InitializationKind
&Kind
,
2907 InitializationSequence
&Sequence
) {
2908 Sequence
.setSequenceKind(InitializationSequence::UserDefinedConversion
);
2910 QualType DestType
= Entity
.getType();
2911 assert(!DestType
->isReferenceType() && "References are handled elsewhere");
2912 QualType SourceType
= Initializer
->getType();
2913 assert((DestType
->isRecordType() || SourceType
->isRecordType()) &&
2914 "Must have a class type to perform a user-defined conversion");
2916 // Build the candidate set directly in the initialization sequence
2917 // structure, so that it will persist if we fail.
2918 OverloadCandidateSet
&CandidateSet
= Sequence
.getFailedCandidateSet();
2919 CandidateSet
.clear();
2921 // Determine whether we are allowed to call explicit constructors or
2922 // explicit conversion operators.
2923 bool AllowExplicit
= Kind
.getKind() == InitializationKind::IK_Direct
;
2925 if (const RecordType
*DestRecordType
= DestType
->getAs
<RecordType
>()) {
2926 // The type we're converting to is a class type. Enumerate its constructors
2927 // to see if there is a suitable conversion.
2928 CXXRecordDecl
*DestRecordDecl
2929 = cast
<CXXRecordDecl
>(DestRecordType
->getDecl());
2931 // Try to complete the type we're converting to.
2932 if (!S
.RequireCompleteType(Kind
.getLocation(), DestType
, 0)) {
2933 DeclContext::lookup_iterator Con
, ConEnd
;
2934 for (llvm::tie(Con
, ConEnd
) = S
.LookupConstructors(DestRecordDecl
);
2935 Con
!= ConEnd
; ++Con
) {
2936 NamedDecl
*D
= *Con
;
2937 DeclAccessPair FoundDecl
= DeclAccessPair::make(D
, D
->getAccess());
2939 // Find the constructor (which may be a template).
2940 CXXConstructorDecl
*Constructor
= 0;
2941 FunctionTemplateDecl
*ConstructorTmpl
2942 = dyn_cast
<FunctionTemplateDecl
>(D
);
2943 if (ConstructorTmpl
)
2944 Constructor
= cast
<CXXConstructorDecl
>(
2945 ConstructorTmpl
->getTemplatedDecl());
2947 Constructor
= cast
<CXXConstructorDecl
>(D
);
2949 if (!Constructor
->isInvalidDecl() &&
2950 Constructor
->isConvertingConstructor(AllowExplicit
)) {
2951 if (ConstructorTmpl
)
2952 S
.AddTemplateOverloadCandidate(ConstructorTmpl
, FoundDecl
,
2954 &Initializer
, 1, CandidateSet
,
2955 /*SuppressUserConversions=*/true);
2957 S
.AddOverloadCandidate(Constructor
, FoundDecl
,
2958 &Initializer
, 1, CandidateSet
,
2959 /*SuppressUserConversions=*/true);
2965 SourceLocation DeclLoc
= Initializer
->getLocStart();
2967 if (const RecordType
*SourceRecordType
= SourceType
->getAs
<RecordType
>()) {
2968 // The type we're converting from is a class type, enumerate its conversion
2971 // We can only enumerate the conversion functions for a complete type; if
2972 // the type isn't complete, simply skip this step.
2973 if (!S
.RequireCompleteType(DeclLoc
, SourceType
, 0)) {
2974 CXXRecordDecl
*SourceRecordDecl
2975 = cast
<CXXRecordDecl
>(SourceRecordType
->getDecl());
2977 const UnresolvedSetImpl
*Conversions
2978 = SourceRecordDecl
->getVisibleConversionFunctions();
2979 for (UnresolvedSetImpl::const_iterator I
= Conversions
->begin(),
2980 E
= Conversions
->end();
2983 CXXRecordDecl
*ActingDC
= cast
<CXXRecordDecl
>(D
->getDeclContext());
2984 if (isa
<UsingShadowDecl
>(D
))
2985 D
= cast
<UsingShadowDecl
>(D
)->getTargetDecl();
2987 FunctionTemplateDecl
*ConvTemplate
= dyn_cast
<FunctionTemplateDecl
>(D
);
2988 CXXConversionDecl
*Conv
;
2990 Conv
= cast
<CXXConversionDecl
>(ConvTemplate
->getTemplatedDecl());
2992 Conv
= cast
<CXXConversionDecl
>(D
);
2994 if (AllowExplicit
|| !Conv
->isExplicit()) {
2996 S
.AddTemplateConversionCandidate(ConvTemplate
, I
.getPair(),
2997 ActingDC
, Initializer
, DestType
,
3000 S
.AddConversionCandidate(Conv
, I
.getPair(), ActingDC
,
3001 Initializer
, DestType
, CandidateSet
);
3007 // Perform overload resolution. If it fails, return the failed result.
3008 OverloadCandidateSet::iterator Best
;
3009 if (OverloadingResult Result
3010 = CandidateSet
.BestViableFunction(S
, DeclLoc
, Best
, true)) {
3011 Sequence
.SetOverloadFailure(
3012 InitializationSequence::FK_UserConversionOverloadFailed
,
3017 FunctionDecl
*Function
= Best
->Function
;
3019 if (isa
<CXXConstructorDecl
>(Function
)) {
3020 // Add the user-defined conversion step. Any cv-qualification conversion is
3021 // subsumed by the initialization.
3022 Sequence
.AddUserConversionStep(Function
, Best
->FoundDecl
, DestType
);
3026 // Add the user-defined conversion step that calls the conversion function.
3027 QualType ConvType
= Function
->getCallResultType();
3028 if (ConvType
->getAs
<RecordType
>()) {
3029 // If we're converting to a class type, there may be an copy if
3030 // the resulting temporary object (possible to create an object of
3031 // a base class type). That copy is not a separate conversion, so
3032 // we just make a note of the actual destination type (possibly a
3033 // base class of the type returned by the conversion function) and
3034 // let the user-defined conversion step handle the conversion.
3035 Sequence
.AddUserConversionStep(Function
, Best
->FoundDecl
, DestType
);
3039 Sequence
.AddUserConversionStep(Function
, Best
->FoundDecl
, ConvType
);
3041 // If the conversion following the call to the conversion function
3042 // is interesting, add it as a separate step.
3043 if (Best
->FinalConversion
.First
|| Best
->FinalConversion
.Second
||
3044 Best
->FinalConversion
.Third
) {
3045 ImplicitConversionSequence ICS
;
3047 ICS
.Standard
= Best
->FinalConversion
;
3048 Sequence
.AddConversionSequenceStep(ICS
, DestType
);
3052 InitializationSequence::InitializationSequence(Sema
&S
,
3053 const InitializedEntity
&Entity
,
3054 const InitializationKind
&Kind
,
3057 : FailedCandidateSet(Kind
.getLocation()) {
3058 ASTContext
&Context
= S
.Context
;
3060 // C++0x [dcl.init]p16:
3061 // The semantics of initializers are as follows. The destination type is
3062 // the type of the object or reference being initialized and the source
3063 // type is the type of the initializer expression. The source type is not
3064 // defined when the initializer is a braced-init-list or when it is a
3065 // parenthesized list of expressions.
3066 QualType DestType
= Entity
.getType();
3068 if (DestType
->isDependentType() ||
3069 Expr::hasAnyTypeDependentArguments(Args
, NumArgs
)) {
3070 SequenceKind
= DependentSequence
;
3074 for (unsigned I
= 0; I
!= NumArgs
; ++I
)
3075 if (Args
[I
]->getObjectKind() == OK_ObjCProperty
)
3076 S
.ConvertPropertyForRValue(Args
[I
]);
3078 QualType SourceType
;
3079 Expr
*Initializer
= 0;
3081 Initializer
= Args
[0];
3082 if (!isa
<InitListExpr
>(Initializer
))
3083 SourceType
= Initializer
->getType();
3086 // - If the initializer is a braced-init-list, the object is
3087 // list-initialized (8.5.4).
3088 if (InitListExpr
*InitList
= dyn_cast_or_null
<InitListExpr
>(Initializer
)) {
3089 TryListInitialization(S
, Entity
, Kind
, InitList
, *this);
3093 // - If the destination type is a reference type, see 8.5.3.
3094 if (DestType
->isReferenceType()) {
3095 // C++0x [dcl.init.ref]p1:
3096 // A variable declared to be a T& or T&&, that is, "reference to type T"
3097 // (8.3.2), shall be initialized by an object, or function, of type T or
3098 // by an object that can be converted into a T.
3099 // (Therefore, multiple arguments are not permitted.)
3101 SetFailed(FK_TooManyInitsForReference
);
3103 TryReferenceInitialization(S
, Entity
, Kind
, Args
[0], *this);
3107 // - If the destination type is an array of characters, an array of
3108 // char16_t, an array of char32_t, or an array of wchar_t, and the
3109 // initializer is a string literal, see 8.5.2.
3110 if (Initializer
&& IsStringInit(Initializer
, DestType
, Context
)) {
3111 TryStringLiteralInitialization(S
, Entity
, Kind
, Initializer
, *this);
3115 // - If the initializer is (), the object is value-initialized.
3116 if (Kind
.getKind() == InitializationKind::IK_Value
||
3117 (Kind
.getKind() == InitializationKind::IK_Direct
&& NumArgs
== 0)) {
3118 TryValueInitialization(S
, Entity
, Kind
, *this);
3122 // Handle default initialization.
3123 if (Kind
.getKind() == InitializationKind::IK_Default
) {
3124 TryDefaultInitialization(S
, Entity
, Kind
, *this);
3128 // - Otherwise, if the destination type is an array, the program is
3130 if (const ArrayType
*AT
= Context
.getAsArrayType(DestType
)) {
3131 if (AT
->getElementType()->isAnyCharacterType())
3132 SetFailed(FK_ArrayNeedsInitListOrStringLiteral
);
3134 SetFailed(FK_ArrayNeedsInitList
);
3139 // Handle initialization in C
3140 if (!S
.getLangOptions().CPlusPlus
) {
3141 setSequenceKind(CAssignment
);
3142 AddCAssignmentStep(DestType
);
3146 // - If the destination type is a (possibly cv-qualified) class type:
3147 if (DestType
->isRecordType()) {
3148 // - If the initialization is direct-initialization, or if it is
3149 // copy-initialization where the cv-unqualified version of the
3150 // source type is the same class as, or a derived class of, the
3151 // class of the destination, constructors are considered. [...]
3152 if (Kind
.getKind() == InitializationKind::IK_Direct
||
3153 (Kind
.getKind() == InitializationKind::IK_Copy
&&
3154 (Context
.hasSameUnqualifiedType(SourceType
, DestType
) ||
3155 S
.IsDerivedFrom(SourceType
, DestType
))))
3156 TryConstructorInitialization(S
, Entity
, Kind
, Args
, NumArgs
,
3157 Entity
.getType(), *this);
3158 // - Otherwise (i.e., for the remaining copy-initialization cases),
3159 // user-defined conversion sequences that can convert from the source
3160 // type to the destination type or (when a conversion function is
3161 // used) to a derived class thereof are enumerated as described in
3162 // 13.3.1.4, and the best one is chosen through overload resolution
3165 TryUserDefinedConversion(S
, Entity
, Kind
, Initializer
, *this);
3170 SetFailed(FK_TooManyInitsForScalar
);
3173 assert(NumArgs
== 1 && "Zero-argument case handled above");
3175 // - Otherwise, if the source type is a (possibly cv-qualified) class
3176 // type, conversion functions are considered.
3177 if (!SourceType
.isNull() && SourceType
->isRecordType()) {
3178 TryUserDefinedConversion(S
, Entity
, Kind
, Initializer
, *this);
3182 // - Otherwise, the initial value of the object being initialized is the
3183 // (possibly converted) value of the initializer expression. Standard
3184 // conversions (Clause 4) will be used, if necessary, to convert the
3185 // initializer expression to the cv-unqualified version of the
3186 // destination type; no user-defined conversions are considered.
3187 if (S
.TryImplicitConversion(*this, Entity
, Initializer
,
3188 /*SuppressUserConversions*/ true,
3189 /*AllowExplicitConversions*/ false,
3190 /*InOverloadResolution*/ false,
3191 /*CStyle=*/Kind
.isCStyleOrFunctionalCast()))
3193 if (Initializer
->getType() == Context
.OverloadTy
)
3194 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed
);
3196 SetFailed(InitializationSequence::FK_ConversionFailed
);
3199 setSequenceKind(StandardConversion
);
3202 InitializationSequence::~InitializationSequence() {
3203 for (llvm::SmallVectorImpl
<Step
>::iterator Step
= Steps
.begin(),
3204 StepEnd
= Steps
.end();
3205 Step
!= StepEnd
; ++Step
)
3209 //===----------------------------------------------------------------------===//
3210 // Perform initialization
3211 //===----------------------------------------------------------------------===//
3212 static Sema::AssignmentAction
3213 getAssignmentAction(const InitializedEntity
&Entity
) {
3214 switch(Entity
.getKind()) {
3215 case InitializedEntity::EK_Variable
:
3216 case InitializedEntity::EK_New
:
3217 case InitializedEntity::EK_Exception
:
3218 case InitializedEntity::EK_Base
:
3219 return Sema::AA_Initializing
;
3221 case InitializedEntity::EK_Parameter
:
3222 if (Entity
.getDecl() &&
3223 isa
<ObjCMethodDecl
>(Entity
.getDecl()->getDeclContext()))
3224 return Sema::AA_Sending
;
3226 return Sema::AA_Passing
;
3228 case InitializedEntity::EK_Result
:
3229 return Sema::AA_Returning
;
3231 case InitializedEntity::EK_Temporary
:
3232 // FIXME: Can we tell apart casting vs. converting?
3233 return Sema::AA_Casting
;
3235 case InitializedEntity::EK_Member
:
3236 case InitializedEntity::EK_ArrayElement
:
3237 case InitializedEntity::EK_VectorElement
:
3238 case InitializedEntity::EK_BlockElement
:
3239 return Sema::AA_Initializing
;
3242 return Sema::AA_Converting
;
3245 /// \brief Whether we should binding a created object as a temporary when
3246 /// initializing the given entity.
3247 static bool shouldBindAsTemporary(const InitializedEntity
&Entity
) {
3248 switch (Entity
.getKind()) {
3249 case InitializedEntity::EK_ArrayElement
:
3250 case InitializedEntity::EK_Member
:
3251 case InitializedEntity::EK_Result
:
3252 case InitializedEntity::EK_New
:
3253 case InitializedEntity::EK_Variable
:
3254 case InitializedEntity::EK_Base
:
3255 case InitializedEntity::EK_VectorElement
:
3256 case InitializedEntity::EK_Exception
:
3257 case InitializedEntity::EK_BlockElement
:
3260 case InitializedEntity::EK_Parameter
:
3261 case InitializedEntity::EK_Temporary
:
3265 llvm_unreachable("missed an InitializedEntity kind?");
3268 /// \brief Whether the given entity, when initialized with an object
3269 /// created for that initialization, requires destruction.
3270 static bool shouldDestroyTemporary(const InitializedEntity
&Entity
) {
3271 switch (Entity
.getKind()) {
3272 case InitializedEntity::EK_Member
:
3273 case InitializedEntity::EK_Result
:
3274 case InitializedEntity::EK_New
:
3275 case InitializedEntity::EK_Base
:
3276 case InitializedEntity::EK_VectorElement
:
3277 case InitializedEntity::EK_BlockElement
:
3280 case InitializedEntity::EK_Variable
:
3281 case InitializedEntity::EK_Parameter
:
3282 case InitializedEntity::EK_Temporary
:
3283 case InitializedEntity::EK_ArrayElement
:
3284 case InitializedEntity::EK_Exception
:
3288 llvm_unreachable("missed an InitializedEntity kind?");
3291 /// \brief Make a (potentially elidable) temporary copy of the object
3292 /// provided by the given initializer by calling the appropriate copy
3295 /// \param S The Sema object used for type-checking.
3297 /// \param T The type of the temporary object, which must either be
3298 /// the type of the initializer expression or a superclass thereof.
3300 /// \param Enter The entity being initialized.
3302 /// \param CurInit The initializer expression.
3304 /// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3305 /// is permitted in C++03 (but not C++0x) when binding a reference to
3308 /// \returns An expression that copies the initializer expression into
3309 /// a temporary object, or an error expression if a copy could not be
3311 static ExprResult
CopyObject(Sema
&S
,
3313 const InitializedEntity
&Entity
,
3315 bool IsExtraneousCopy
) {
3316 // Determine which class type we're copying to.
3317 Expr
*CurInitExpr
= (Expr
*)CurInit
.get();
3318 CXXRecordDecl
*Class
= 0;
3319 if (const RecordType
*Record
= T
->getAs
<RecordType
>())
3320 Class
= cast
<CXXRecordDecl
>(Record
->getDecl());
3322 return move(CurInit
);
3324 // C++0x [class.copy]p32:
3325 // When certain criteria are met, an implementation is allowed to
3326 // omit the copy/move construction of a class object, even if the
3327 // copy/move constructor and/or destructor for the object have
3328 // side effects. [...]
3329 // - when a temporary class object that has not been bound to a
3330 // reference (12.2) would be copied/moved to a class object
3331 // with the same cv-unqualified type, the copy/move operation
3332 // can be omitted by constructing the temporary object
3333 // directly into the target of the omitted copy/move
3335 // Note that the other three bullets are handled elsewhere. Copy
3336 // elision for return statements and throw expressions are handled as part
3337 // of constructor initialization, while copy elision for exception handlers
3338 // is handled by the run-time.
3339 bool Elidable
= CurInitExpr
->isTemporaryObject(S
.Context
, Class
);
3341 switch (Entity
.getKind()) {
3342 case InitializedEntity::EK_Result
:
3343 Loc
= Entity
.getReturnLoc();
3346 case InitializedEntity::EK_Exception
:
3347 Loc
= Entity
.getThrowLoc();
3350 case InitializedEntity::EK_Variable
:
3351 Loc
= Entity
.getDecl()->getLocation();
3354 case InitializedEntity::EK_ArrayElement
:
3355 case InitializedEntity::EK_Member
:
3356 case InitializedEntity::EK_Parameter
:
3357 case InitializedEntity::EK_Temporary
:
3358 case InitializedEntity::EK_New
:
3359 case InitializedEntity::EK_Base
:
3360 case InitializedEntity::EK_VectorElement
:
3361 case InitializedEntity::EK_BlockElement
:
3362 Loc
= CurInitExpr
->getLocStart();
3366 // Make sure that the type we are copying is complete.
3367 if (S
.RequireCompleteType(Loc
, T
, S
.PDiag(diag::err_temp_copy_incomplete
)))
3368 return move(CurInit
);
3370 // Perform overload resolution using the class's copy/move constructors.
3371 DeclContext::lookup_iterator Con
, ConEnd
;
3372 OverloadCandidateSet
CandidateSet(Loc
);
3373 for (llvm::tie(Con
, ConEnd
) = S
.LookupConstructors(Class
);
3374 Con
!= ConEnd
; ++Con
) {
3375 // Only consider copy/move constructors and constructor templates. Per
3376 // C++0x [dcl.init]p16, second bullet to class types, this
3377 // initialization is direct-initialization.
3378 CXXConstructorDecl
*Constructor
= 0;
3380 if ((Constructor
= dyn_cast
<CXXConstructorDecl
>(*Con
))) {
3381 // Handle copy/moveconstructors, only.
3382 if (!Constructor
|| Constructor
->isInvalidDecl() ||
3383 !Constructor
->isCopyOrMoveConstructor() ||
3384 !Constructor
->isConvertingConstructor(/*AllowExplicit=*/true))
3387 DeclAccessPair FoundDecl
3388 = DeclAccessPair::make(Constructor
, Constructor
->getAccess());
3389 S
.AddOverloadCandidate(Constructor
, FoundDecl
,
3390 &CurInitExpr
, 1, CandidateSet
);
3394 // Handle constructor templates.
3395 FunctionTemplateDecl
*ConstructorTmpl
= cast
<FunctionTemplateDecl
>(*Con
);
3396 if (ConstructorTmpl
->isInvalidDecl())
3399 Constructor
= cast
<CXXConstructorDecl
>(
3400 ConstructorTmpl
->getTemplatedDecl());
3401 if (!Constructor
->isConvertingConstructor(/*AllowExplicit=*/true))
3404 // FIXME: Do we need to limit this to copy-constructor-like
3406 DeclAccessPair FoundDecl
3407 = DeclAccessPair::make(ConstructorTmpl
, ConstructorTmpl
->getAccess());
3408 S
.AddTemplateOverloadCandidate(ConstructorTmpl
, FoundDecl
, 0,
3409 &CurInitExpr
, 1, CandidateSet
, true);
3412 OverloadCandidateSet::iterator Best
;
3413 switch (CandidateSet
.BestViableFunction(S
, Loc
, Best
)) {
3417 case OR_No_Viable_Function
:
3418 S
.Diag(Loc
, IsExtraneousCopy
&& !S
.isSFINAEContext()
3419 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3420 : diag::err_temp_copy_no_viable
)
3421 << (int)Entity
.getKind() << CurInitExpr
->getType()
3422 << CurInitExpr
->getSourceRange();
3423 CandidateSet
.NoteCandidates(S
, OCD_AllCandidates
, &CurInitExpr
, 1);
3424 if (!IsExtraneousCopy
|| S
.isSFINAEContext())
3426 return move(CurInit
);
3429 S
.Diag(Loc
, diag::err_temp_copy_ambiguous
)
3430 << (int)Entity
.getKind() << CurInitExpr
->getType()
3431 << CurInitExpr
->getSourceRange();
3432 CandidateSet
.NoteCandidates(S
, OCD_ViableCandidates
, &CurInitExpr
, 1);
3436 S
.Diag(Loc
, diag::err_temp_copy_deleted
)
3437 << (int)Entity
.getKind() << CurInitExpr
->getType()
3438 << CurInitExpr
->getSourceRange();
3439 S
.Diag(Best
->Function
->getLocation(), diag::note_unavailable_here
)
3440 << Best
->Function
->isDeleted();
3444 CXXConstructorDecl
*Constructor
= cast
<CXXConstructorDecl
>(Best
->Function
);
3445 ASTOwningVector
<Expr
*> ConstructorArgs(S
);
3446 CurInit
.release(); // Ownership transferred into MultiExprArg, below.
3448 S
.CheckConstructorAccess(Loc
, Constructor
, Entity
,
3449 Best
->FoundDecl
.getAccess(), IsExtraneousCopy
);
3451 if (IsExtraneousCopy
) {
3452 // If this is a totally extraneous copy for C++03 reference
3453 // binding purposes, just return the original initialization
3454 // expression. We don't generate an (elided) copy operation here
3455 // because doing so would require us to pass down a flag to avoid
3456 // infinite recursion, where each step adds another extraneous,
3459 // Instantiate the default arguments of any extra parameters in
3460 // the selected copy constructor, as if we were going to create a
3461 // proper call to the copy constructor.
3462 for (unsigned I
= 1, N
= Constructor
->getNumParams(); I
!= N
; ++I
) {
3463 ParmVarDecl
*Parm
= Constructor
->getParamDecl(I
);
3464 if (S
.RequireCompleteType(Loc
, Parm
->getType(),
3465 S
.PDiag(diag::err_call_incomplete_argument
)))
3468 // Build the default argument expression; we don't actually care
3469 // if this succeeds or not, because this routine will complain
3470 // if there was a problem.
3471 S
.BuildCXXDefaultArgExpr(Loc
, Constructor
, Parm
);
3474 return S
.Owned(CurInitExpr
);
3477 // Determine the arguments required to actually perform the
3478 // constructor call (we might have derived-to-base conversions, or
3479 // the copy constructor may have default arguments).
3480 if (S
.CompleteConstructorCall(Constructor
, MultiExprArg(&CurInitExpr
, 1),
3481 Loc
, ConstructorArgs
))
3484 // Actually perform the constructor call.
3485 CurInit
= S
.BuildCXXConstructExpr(Loc
, T
, Constructor
, Elidable
,
3486 move_arg(ConstructorArgs
),
3488 CXXConstructExpr::CK_Complete
,
3491 // If we're supposed to bind temporaries, do so.
3492 if (!CurInit
.isInvalid() && shouldBindAsTemporary(Entity
))
3493 CurInit
= S
.MaybeBindToTemporary(CurInit
.takeAs
<Expr
>());
3494 return move(CurInit
);
3497 void InitializationSequence::PrintInitLocationNote(Sema
&S
,
3498 const InitializedEntity
&Entity
) {
3499 if (Entity
.getKind() == InitializedEntity::EK_Parameter
&& Entity
.getDecl()) {
3500 if (Entity
.getDecl()->getLocation().isInvalid())
3503 if (Entity
.getDecl()->getDeclName())
3504 S
.Diag(Entity
.getDecl()->getLocation(), diag::note_parameter_named_here
)
3505 << Entity
.getDecl()->getDeclName();
3507 S
.Diag(Entity
.getDecl()->getLocation(), diag::note_parameter_here
);
3512 InitializationSequence::Perform(Sema
&S
,
3513 const InitializedEntity
&Entity
,
3514 const InitializationKind
&Kind
,
3516 QualType
*ResultType
) {
3517 if (SequenceKind
== FailedSequence
) {
3518 unsigned NumArgs
= Args
.size();
3519 Diagnose(S
, Entity
, Kind
, (Expr
**)Args
.release(), NumArgs
);
3523 if (SequenceKind
== DependentSequence
) {
3524 // If the declaration is a non-dependent, incomplete array type
3525 // that has an initializer, then its type will be completed once
3526 // the initializer is instantiated.
3527 if (ResultType
&& !Entity
.getType()->isDependentType() &&
3529 QualType DeclType
= Entity
.getType();
3530 if (const IncompleteArrayType
*ArrayT
3531 = S
.Context
.getAsIncompleteArrayType(DeclType
)) {
3532 // FIXME: We don't currently have the ability to accurately
3533 // compute the length of an initializer list without
3534 // performing full type-checking of the initializer list
3535 // (since we have to determine where braces are implicitly
3536 // introduced and such). So, we fall back to making the array
3537 // type a dependently-sized array type with no specified
3539 if (isa
<InitListExpr
>((Expr
*)Args
.get()[0])) {
3540 SourceRange Brackets
;
3542 // Scavange the location of the brackets from the entity, if we can.
3543 if (DeclaratorDecl
*DD
= Entity
.getDecl()) {
3544 if (TypeSourceInfo
*TInfo
= DD
->getTypeSourceInfo()) {
3545 TypeLoc TL
= TInfo
->getTypeLoc();
3546 if (IncompleteArrayTypeLoc
*ArrayLoc
3547 = dyn_cast
<IncompleteArrayTypeLoc
>(&TL
))
3548 Brackets
= ArrayLoc
->getBracketsRange();
3553 = S
.Context
.getDependentSizedArrayType(ArrayT
->getElementType(),
3555 ArrayT
->getSizeModifier(),
3556 ArrayT
->getIndexTypeCVRQualifiers(),
3563 if (Kind
.getKind() == InitializationKind::IK_Copy
|| Kind
.isExplicitCast())
3564 return ExprResult(Args
.release()[0]);
3566 if (Args
.size() == 0)
3567 return S
.Owned((Expr
*)0);
3569 unsigned NumArgs
= Args
.size();
3570 return S
.Owned(new (S
.Context
) ParenListExpr(S
.Context
,
3572 (Expr
**)Args
.release(),
3577 if (SequenceKind
== NoInitialization
)
3578 return S
.Owned((Expr
*)0);
3580 QualType DestType
= Entity
.getType().getNonReferenceType();
3581 // FIXME: Ugly hack around the fact that Entity.getType() is not
3582 // the same as Entity.getDecl()->getType() in cases involving type merging,
3583 // and we want latter when it makes sense.
3585 *ResultType
= Entity
.getDecl() ? Entity
.getDecl()->getType() :
3588 ExprResult CurInit
= S
.Owned((Expr
*)0);
3590 assert(!Steps
.empty() && "Cannot have an empty initialization sequence");
3592 // For initialization steps that start with a single initializer,
3593 // grab the only argument out the Args and place it into the "current"
3595 switch (Steps
.front().Kind
) {
3596 case SK_ResolveAddressOfOverloadedFunction
:
3597 case SK_CastDerivedToBaseRValue
:
3598 case SK_CastDerivedToBaseXValue
:
3599 case SK_CastDerivedToBaseLValue
:
3600 case SK_BindReference
:
3601 case SK_BindReferenceToTemporary
:
3602 case SK_ExtraneousCopyToTemporary
:
3603 case SK_UserConversion
:
3604 case SK_QualificationConversionLValue
:
3605 case SK_QualificationConversionXValue
:
3606 case SK_QualificationConversionRValue
:
3607 case SK_ConversionSequence
:
3608 case SK_ListInitialization
:
3609 case SK_CAssignment
:
3611 case SK_ObjCObjectConversion
: {
3612 assert(Args
.size() == 1);
3613 Expr
*CurInitExpr
= Args
.get()[0];
3614 if (!CurInitExpr
) return ExprError();
3616 // Read from a property when initializing something with it.
3617 if (CurInitExpr
->getObjectKind() == OK_ObjCProperty
)
3618 S
.ConvertPropertyForRValue(CurInitExpr
);
3620 CurInit
= ExprResult(CurInitExpr
);
3624 case SK_ConstructorInitialization
:
3625 case SK_ZeroInitialization
:
3629 // Walk through the computed steps for the initialization sequence,
3630 // performing the specified conversions along the way.
3631 bool ConstructorInitRequiresZeroInit
= false;
3632 for (step_iterator Step
= step_begin(), StepEnd
= step_end();
3633 Step
!= StepEnd
; ++Step
) {
3634 if (CurInit
.isInvalid())
3637 Expr
*CurInitExpr
= CurInit
.get();
3638 QualType SourceType
= CurInitExpr
? CurInitExpr
->getType() : QualType();
3640 switch (Step
->Kind
) {
3641 case SK_ResolveAddressOfOverloadedFunction
:
3642 // Overload resolution determined which function invoke; update the
3643 // initializer to reflect that choice.
3644 S
.CheckAddressOfMemberAccess(CurInitExpr
, Step
->Function
.FoundDecl
);
3645 S
.DiagnoseUseOfDecl(Step
->Function
.FoundDecl
, Kind
.getLocation());
3646 CurInit
= S
.FixOverloadedFunctionReference(move(CurInit
),
3647 Step
->Function
.FoundDecl
,
3648 Step
->Function
.Function
);
3651 case SK_CastDerivedToBaseRValue
:
3652 case SK_CastDerivedToBaseXValue
:
3653 case SK_CastDerivedToBaseLValue
: {
3654 // We have a derived-to-base cast that produces either an rvalue or an
3655 // lvalue. Perform that cast.
3657 CXXCastPath BasePath
;
3659 // Casts to inaccessible base classes are allowed with C-style casts.
3660 bool IgnoreBaseAccess
= Kind
.isCStyleOrFunctionalCast();
3661 if (S
.CheckDerivedToBaseConversion(SourceType
, Step
->Type
,
3662 CurInitExpr
->getLocStart(),
3663 CurInitExpr
->getSourceRange(),
3664 &BasePath
, IgnoreBaseAccess
))
3667 if (S
.BasePathInvolvesVirtualBase(BasePath
)) {
3668 QualType T
= SourceType
;
3669 if (const PointerType
*Pointer
= T
->getAs
<PointerType
>())
3670 T
= Pointer
->getPointeeType();
3671 if (const RecordType
*RecordTy
= T
->getAs
<RecordType
>())
3672 S
.MarkVTableUsed(CurInitExpr
->getLocStart(),
3673 cast
<CXXRecordDecl
>(RecordTy
->getDecl()));
3677 Step
->Kind
== SK_CastDerivedToBaseLValue
?
3679 (Step
->Kind
== SK_CastDerivedToBaseXValue
?
3682 CurInit
= S
.Owned(ImplicitCastExpr::Create(S
.Context
,
3690 case SK_BindReference
:
3691 if (FieldDecl
*BitField
= CurInitExpr
->getBitField()) {
3692 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3693 S
.Diag(Kind
.getLocation(), diag::err_reference_bind_to_bitfield
)
3694 << Entity
.getType().isVolatileQualified()
3695 << BitField
->getDeclName()
3696 << CurInitExpr
->getSourceRange();
3697 S
.Diag(BitField
->getLocation(), diag::note_bitfield_decl
);
3701 if (CurInitExpr
->refersToVectorElement()) {
3702 // References cannot bind to vector elements.
3703 S
.Diag(Kind
.getLocation(), diag::err_reference_bind_to_vector_element
)
3704 << Entity
.getType().isVolatileQualified()
3705 << CurInitExpr
->getSourceRange();
3706 PrintInitLocationNote(S
, Entity
);
3710 // Reference binding does not have any corresponding ASTs.
3712 // Check exception specifications
3713 if (S
.CheckExceptionSpecCompatibility(CurInitExpr
, DestType
))
3718 case SK_BindReferenceToTemporary
:
3719 // Reference binding does not have any corresponding ASTs.
3721 // Check exception specifications
3722 if (S
.CheckExceptionSpecCompatibility(CurInitExpr
, DestType
))
3727 case SK_ExtraneousCopyToTemporary
:
3728 CurInit
= CopyObject(S
, Step
->Type
, Entity
, move(CurInit
),
3729 /*IsExtraneousCopy=*/true);
3732 case SK_UserConversion
: {
3733 // We have a user-defined conversion that invokes either a constructor
3734 // or a conversion function.
3736 bool IsCopy
= false;
3737 FunctionDecl
*Fn
= Step
->Function
.Function
;
3738 DeclAccessPair FoundFn
= Step
->Function
.FoundDecl
;
3739 bool CreatedObject
= false;
3740 bool IsLvalue
= false;
3741 if (CXXConstructorDecl
*Constructor
= dyn_cast
<CXXConstructorDecl
>(Fn
)) {
3742 // Build a call to the selected constructor.
3743 ASTOwningVector
<Expr
*> ConstructorArgs(S
);
3744 SourceLocation Loc
= CurInitExpr
->getLocStart();
3745 CurInit
.release(); // Ownership transferred into MultiExprArg, below.
3747 // Determine the arguments required to actually perform the constructor
3749 if (S
.CompleteConstructorCall(Constructor
,
3750 MultiExprArg(&CurInitExpr
, 1),
3751 Loc
, ConstructorArgs
))
3754 // Build the an expression that constructs a temporary.
3755 CurInit
= S
.BuildCXXConstructExpr(Loc
, Step
->Type
, Constructor
,
3756 move_arg(ConstructorArgs
),
3758 CXXConstructExpr::CK_Complete
,
3760 if (CurInit
.isInvalid())
3763 S
.CheckConstructorAccess(Kind
.getLocation(), Constructor
, Entity
,
3764 FoundFn
.getAccess());
3765 S
.DiagnoseUseOfDecl(FoundFn
, Kind
.getLocation());
3767 CastKind
= CK_ConstructorConversion
;
3768 QualType Class
= S
.Context
.getTypeDeclType(Constructor
->getParent());
3769 if (S
.Context
.hasSameUnqualifiedType(SourceType
, Class
) ||
3770 S
.IsDerivedFrom(SourceType
, Class
))
3773 CreatedObject
= true;
3775 // Build a call to the conversion function.
3776 CXXConversionDecl
*Conversion
= cast
<CXXConversionDecl
>(Fn
);
3777 IsLvalue
= Conversion
->getResultType()->isLValueReferenceType();
3778 S
.CheckMemberOperatorAccess(Kind
.getLocation(), CurInitExpr
, 0,
3780 S
.DiagnoseUseOfDecl(FoundFn
, Kind
.getLocation());
3782 // FIXME: Should we move this initialization into a separate
3783 // derived-to-base conversion? I believe the answer is "no", because
3784 // we don't want to turn off access control here for c-style casts.
3785 if (S
.PerformObjectArgumentInitialization(CurInitExpr
, /*Qualifier=*/0,
3786 FoundFn
, Conversion
))
3789 // Do a little dance to make sure that CurInit has the proper
3793 // Build the actual call to the conversion function.
3794 CurInit
= S
.BuildCXXMemberCallExpr(CurInitExpr
, FoundFn
, Conversion
);
3795 if (CurInit
.isInvalid() || !CurInit
.get())
3798 CastKind
= CK_UserDefinedConversion
;
3800 CreatedObject
= Conversion
->getResultType()->isRecordType();
3803 bool RequiresCopy
= !IsCopy
&&
3804 getKind() != InitializationSequence::ReferenceBinding
;
3805 if (RequiresCopy
|| shouldBindAsTemporary(Entity
))
3806 CurInit
= S
.MaybeBindToTemporary(CurInit
.takeAs
<Expr
>());
3807 else if (CreatedObject
&& shouldDestroyTemporary(Entity
)) {
3808 CurInitExpr
= static_cast<Expr
*>(CurInit
.get());
3809 QualType T
= CurInitExpr
->getType();
3810 if (const RecordType
*Record
= T
->getAs
<RecordType
>()) {
3811 CXXDestructorDecl
*Destructor
3812 = S
.LookupDestructor(cast
<CXXRecordDecl
>(Record
->getDecl()));
3813 S
.CheckDestructorAccess(CurInitExpr
->getLocStart(), Destructor
,
3814 S
.PDiag(diag::err_access_dtor_temp
) << T
);
3815 S
.MarkDeclarationReferenced(CurInitExpr
->getLocStart(), Destructor
);
3816 S
.DiagnoseUseOfDecl(Destructor
, CurInitExpr
->getLocStart());
3820 CurInitExpr
= CurInit
.takeAs
<Expr
>();
3822 CurInit
= S
.Owned(ImplicitCastExpr::Create(S
.Context
,
3823 CurInitExpr
->getType(),
3824 CastKind
, CurInitExpr
, 0,
3825 IsLvalue
? VK_LValue
: VK_RValue
));
3828 CurInit
= CopyObject(S
, Entity
.getType().getNonReferenceType(), Entity
,
3829 move(CurInit
), /*IsExtraneousCopy=*/false);
3834 case SK_QualificationConversionLValue
:
3835 case SK_QualificationConversionXValue
:
3836 case SK_QualificationConversionRValue
: {
3837 // Perform a qualification conversion; these can never go wrong.
3839 Step
->Kind
== SK_QualificationConversionLValue
?
3841 (Step
->Kind
== SK_QualificationConversionXValue
?
3844 S
.ImpCastExprToType(CurInitExpr
, Step
->Type
, CK_NoOp
, VK
);
3846 CurInit
= S
.Owned(CurInitExpr
);
3850 case SK_ConversionSequence
: {
3851 if (S
.PerformImplicitConversion(CurInitExpr
, Step
->Type
, *Step
->ICS
,
3852 getAssignmentAction(Entity
),
3853 Kind
.isCStyleOrFunctionalCast()))
3857 CurInit
= S
.Owned(CurInitExpr
);
3861 case SK_ListInitialization
: {
3862 InitListExpr
*InitList
= cast
<InitListExpr
>(CurInitExpr
);
3863 QualType Ty
= Step
->Type
;
3864 if (S
.CheckInitList(Entity
, InitList
, ResultType
? *ResultType
: Ty
))
3868 CurInit
= S
.Owned(InitList
);
3872 case SK_ConstructorInitialization
: {
3873 unsigned NumArgs
= Args
.size();
3874 CXXConstructorDecl
*Constructor
3875 = cast
<CXXConstructorDecl
>(Step
->Function
.Function
);
3877 // Build a call to the selected constructor.
3878 ASTOwningVector
<Expr
*> ConstructorArgs(S
);
3879 SourceLocation Loc
= (Kind
.isCopyInit() && Kind
.getEqualLoc().isValid())
3880 ? Kind
.getEqualLoc()
3881 : Kind
.getLocation();
3883 if (Kind
.getKind() == InitializationKind::IK_Default
) {
3884 // Force even a trivial, implicit default constructor to be
3885 // semantically checked. We do this explicitly because we don't build
3886 // the definition for completely trivial constructors.
3887 CXXRecordDecl
*ClassDecl
= Constructor
->getParent();
3888 assert(ClassDecl
&& "No parent class for constructor.");
3889 if (Constructor
->isImplicit() && Constructor
->isDefaultConstructor() &&
3890 ClassDecl
->hasTrivialConstructor() && !Constructor
->isUsed(false))
3891 S
.DefineImplicitDefaultConstructor(Loc
, Constructor
);
3894 // Determine the arguments required to actually perform the constructor
3896 if (S
.CompleteConstructorCall(Constructor
, move(Args
),
3897 Loc
, ConstructorArgs
))
3901 if (Entity
.getKind() == InitializedEntity::EK_Temporary
&&
3902 NumArgs
!= 1 && // FIXME: Hack to work around cast weirdness
3903 (Kind
.getKind() == InitializationKind::IK_Direct
||
3904 Kind
.getKind() == InitializationKind::IK_Value
)) {
3905 // An explicitly-constructed temporary, e.g., X(1, 2).
3906 unsigned NumExprs
= ConstructorArgs
.size();
3907 Expr
**Exprs
= (Expr
**)ConstructorArgs
.take();
3908 S
.MarkDeclarationReferenced(Loc
, Constructor
);
3909 S
.DiagnoseUseOfDecl(Constructor
, Loc
);
3911 TypeSourceInfo
*TSInfo
= Entity
.getTypeSourceInfo();
3913 TSInfo
= S
.Context
.getTrivialTypeSourceInfo(Entity
.getType(), Loc
);
3915 CurInit
= S
.Owned(new (S
.Context
) CXXTemporaryObjectExpr(S
.Context
,
3920 Kind
.getParenRange(),
3921 ConstructorInitRequiresZeroInit
));
3923 CXXConstructExpr::ConstructionKind ConstructKind
=
3924 CXXConstructExpr::CK_Complete
;
3926 if (Entity
.getKind() == InitializedEntity::EK_Base
) {
3927 ConstructKind
= Entity
.getBaseSpecifier()->isVirtual() ?
3928 CXXConstructExpr::CK_VirtualBase
:
3929 CXXConstructExpr::CK_NonVirtualBase
;
3932 // Only get the parenthesis range if it is a direct construction.
3933 SourceRange parenRange
=
3934 Kind
.getKind() == InitializationKind::IK_Direct
?
3935 Kind
.getParenRange() : SourceRange();
3937 // If the entity allows NRVO, mark the construction as elidable
3939 if (Entity
.allowsNRVO())
3940 CurInit
= S
.BuildCXXConstructExpr(Loc
, Entity
.getType(),
3941 Constructor
, /*Elidable=*/true,
3942 move_arg(ConstructorArgs
),
3943 ConstructorInitRequiresZeroInit
,
3947 CurInit
= S
.BuildCXXConstructExpr(Loc
, Entity
.getType(),
3949 move_arg(ConstructorArgs
),
3950 ConstructorInitRequiresZeroInit
,
3954 if (CurInit
.isInvalid())
3957 // Only check access if all of that succeeded.
3958 S
.CheckConstructorAccess(Loc
, Constructor
, Entity
,
3959 Step
->Function
.FoundDecl
.getAccess());
3960 S
.DiagnoseUseOfDecl(Step
->Function
.FoundDecl
, Loc
);
3962 if (shouldBindAsTemporary(Entity
))
3963 CurInit
= S
.MaybeBindToTemporary(CurInit
.takeAs
<Expr
>());
3968 case SK_ZeroInitialization
: {
3969 step_iterator NextStep
= Step
;
3971 if (NextStep
!= StepEnd
&&
3972 NextStep
->Kind
== SK_ConstructorInitialization
) {
3973 // The need for zero-initialization is recorded directly into
3974 // the call to the object's constructor within the next step.
3975 ConstructorInitRequiresZeroInit
= true;
3976 } else if (Kind
.getKind() == InitializationKind::IK_Value
&&
3977 S
.getLangOptions().CPlusPlus
&&
3978 !Kind
.isImplicitValueInit()) {
3979 TypeSourceInfo
*TSInfo
= Entity
.getTypeSourceInfo();
3981 TSInfo
= S
.Context
.getTrivialTypeSourceInfo(Step
->Type
,
3982 Kind
.getRange().getBegin());
3984 CurInit
= S
.Owned(new (S
.Context
) CXXScalarValueInitExpr(
3985 TSInfo
->getType().getNonLValueExprType(S
.Context
),
3987 Kind
.getRange().getEnd()));
3989 CurInit
= S
.Owned(new (S
.Context
) ImplicitValueInitExpr(Step
->Type
));
3994 case SK_CAssignment
: {
3995 QualType SourceType
= CurInitExpr
->getType();
3996 Sema::AssignConvertType ConvTy
=
3997 S
.CheckSingleAssignmentConstraints(Step
->Type
, CurInitExpr
);
3999 // If this is a call, allow conversion to a transparent union.
4000 if (ConvTy
!= Sema::Compatible
&&
4001 Entity
.getKind() == InitializedEntity::EK_Parameter
&&
4002 S
.CheckTransparentUnionArgumentConstraints(Step
->Type
, CurInitExpr
)
4003 == Sema::Compatible
)
4004 ConvTy
= Sema::Compatible
;
4007 if (S
.DiagnoseAssignmentResult(ConvTy
, Kind
.getLocation(),
4008 Step
->Type
, SourceType
,
4010 getAssignmentAction(Entity
),
4012 PrintInitLocationNote(S
, Entity
);
4014 } else if (Complained
)
4015 PrintInitLocationNote(S
, Entity
);
4018 CurInit
= S
.Owned(CurInitExpr
);
4022 case SK_StringInit
: {
4023 QualType Ty
= Step
->Type
;
4024 CheckStringInit(CurInitExpr
, ResultType
? *ResultType
: Ty
, S
);
4028 case SK_ObjCObjectConversion
:
4029 S
.ImpCastExprToType(CurInitExpr
, Step
->Type
,
4030 CK_ObjCObjectLValueCast
,
4031 S
.CastCategory(CurInitExpr
));
4033 CurInit
= S
.Owned(CurInitExpr
);
4038 // Diagnose non-fatal problems with the completed initialization.
4039 if (Entity
.getKind() == InitializedEntity::EK_Member
&&
4040 cast
<FieldDecl
>(Entity
.getDecl())->isBitField())
4041 S
.CheckBitFieldInitialization(Kind
.getLocation(),
4042 cast
<FieldDecl
>(Entity
.getDecl()),
4045 return move(CurInit
);
4048 //===----------------------------------------------------------------------===//
4049 // Diagnose initialization failures
4050 //===----------------------------------------------------------------------===//
4051 bool InitializationSequence::Diagnose(Sema
&S
,
4052 const InitializedEntity
&Entity
,
4053 const InitializationKind
&Kind
,
4054 Expr
**Args
, unsigned NumArgs
) {
4055 if (SequenceKind
!= FailedSequence
)
4058 QualType DestType
= Entity
.getType();
4060 case FK_TooManyInitsForReference
:
4061 // FIXME: Customize for the initialized entity?
4063 S
.Diag(Kind
.getLocation(), diag::err_reference_without_init
)
4064 << DestType
.getNonReferenceType();
4065 else // FIXME: diagnostic below could be better!
4066 S
.Diag(Kind
.getLocation(), diag::err_reference_has_multiple_inits
)
4067 << SourceRange(Args
[0]->getLocStart(), Args
[NumArgs
- 1]->getLocEnd());
4070 case FK_ArrayNeedsInitList
:
4071 case FK_ArrayNeedsInitListOrStringLiteral
:
4072 S
.Diag(Kind
.getLocation(), diag::err_array_init_not_init_list
)
4073 << (Failure
== FK_ArrayNeedsInitListOrStringLiteral
);
4076 case FK_AddressOfOverloadFailed
: {
4077 DeclAccessPair Found
;
4078 S
.ResolveAddressOfOverloadedFunction(Args
[0],
4079 DestType
.getNonReferenceType(),
4085 case FK_ReferenceInitOverloadFailed
:
4086 case FK_UserConversionOverloadFailed
:
4087 switch (FailedOverloadResult
) {
4089 if (Failure
== FK_UserConversionOverloadFailed
)
4090 S
.Diag(Kind
.getLocation(), diag::err_typecheck_ambiguous_condition
)
4091 << Args
[0]->getType() << DestType
4092 << Args
[0]->getSourceRange();
4094 S
.Diag(Kind
.getLocation(), diag::err_ref_init_ambiguous
)
4095 << DestType
<< Args
[0]->getType()
4096 << Args
[0]->getSourceRange();
4098 FailedCandidateSet
.NoteCandidates(S
, OCD_ViableCandidates
, Args
, NumArgs
);
4101 case OR_No_Viable_Function
:
4102 S
.Diag(Kind
.getLocation(), diag::err_typecheck_nonviable_condition
)
4103 << Args
[0]->getType() << DestType
.getNonReferenceType()
4104 << Args
[0]->getSourceRange();
4105 FailedCandidateSet
.NoteCandidates(S
, OCD_AllCandidates
, Args
, NumArgs
);
4109 S
.Diag(Kind
.getLocation(), diag::err_typecheck_deleted_function
)
4110 << Args
[0]->getType() << DestType
.getNonReferenceType()
4111 << Args
[0]->getSourceRange();
4112 OverloadCandidateSet::iterator Best
;
4113 OverloadingResult Ovl
4114 = FailedCandidateSet
.BestViableFunction(S
, Kind
.getLocation(), Best
,
4116 if (Ovl
== OR_Deleted
) {
4117 S
.Diag(Best
->Function
->getLocation(), diag::note_unavailable_here
)
4118 << Best
->Function
->isDeleted();
4120 llvm_unreachable("Inconsistent overload resolution?");
4126 llvm_unreachable("Conversion did not fail!");
4131 case FK_NonConstLValueReferenceBindingToTemporary
:
4132 case FK_NonConstLValueReferenceBindingToUnrelated
:
4133 S
.Diag(Kind
.getLocation(),
4134 Failure
== FK_NonConstLValueReferenceBindingToTemporary
4135 ? diag::err_lvalue_reference_bind_to_temporary
4136 : diag::err_lvalue_reference_bind_to_unrelated
)
4137 << DestType
.getNonReferenceType().isVolatileQualified()
4138 << DestType
.getNonReferenceType()
4139 << Args
[0]->getType()
4140 << Args
[0]->getSourceRange();
4143 case FK_RValueReferenceBindingToLValue
:
4144 S
.Diag(Kind
.getLocation(), diag::err_lvalue_to_rvalue_ref
)
4145 << DestType
.getNonReferenceType() << Args
[0]->getType()
4146 << Args
[0]->getSourceRange();
4149 case FK_ReferenceInitDropsQualifiers
:
4150 S
.Diag(Kind
.getLocation(), diag::err_reference_bind_drops_quals
)
4151 << DestType
.getNonReferenceType()
4152 << Args
[0]->getType()
4153 << Args
[0]->getSourceRange();
4156 case FK_ReferenceInitFailed
:
4157 S
.Diag(Kind
.getLocation(), diag::err_reference_bind_failed
)
4158 << DestType
.getNonReferenceType()
4159 << Args
[0]->isLValue()
4160 << Args
[0]->getType()
4161 << Args
[0]->getSourceRange();
4164 case FK_ConversionFailed
:
4165 S
.Diag(Kind
.getLocation(), diag::err_init_conversion_failed
)
4166 << (int)Entity
.getKind()
4168 << Args
[0]->isLValue()
4169 << Args
[0]->getType()
4170 << Args
[0]->getSourceRange();
4173 case FK_TooManyInitsForScalar
: {
4176 if (InitListExpr
*InitList
= dyn_cast
<InitListExpr
>(Args
[0]))
4177 R
= SourceRange(InitList
->getInit(0)->getLocEnd(),
4178 InitList
->getLocEnd());
4180 R
= SourceRange(Args
[0]->getLocEnd(), Args
[NumArgs
- 1]->getLocEnd());
4182 R
.setBegin(S
.PP
.getLocForEndOfToken(R
.getBegin()));
4183 if (Kind
.isCStyleOrFunctionalCast())
4184 S
.Diag(Kind
.getLocation(), diag::err_builtin_func_cast_more_than_one_arg
)
4187 S
.Diag(Kind
.getLocation(), diag::err_excess_initializers
)
4188 << /*scalar=*/2 << R
;
4192 case FK_ReferenceBindingToInitList
:
4193 S
.Diag(Kind
.getLocation(), diag::err_reference_bind_init_list
)
4194 << DestType
.getNonReferenceType() << Args
[0]->getSourceRange();
4197 case FK_InitListBadDestinationType
:
4198 S
.Diag(Kind
.getLocation(), diag::err_init_list_bad_dest_type
)
4199 << (DestType
->isRecordType()) << DestType
<< Args
[0]->getSourceRange();
4202 case FK_ConstructorOverloadFailed
: {
4203 SourceRange ArgsRange
;
4205 ArgsRange
= SourceRange(Args
[0]->getLocStart(),
4206 Args
[NumArgs
- 1]->getLocEnd());
4208 // FIXME: Using "DestType" for the entity we're printing is probably
4210 switch (FailedOverloadResult
) {
4212 S
.Diag(Kind
.getLocation(), diag::err_ovl_ambiguous_init
)
4213 << DestType
<< ArgsRange
;
4214 FailedCandidateSet
.NoteCandidates(S
, OCD_ViableCandidates
,
4218 case OR_No_Viable_Function
:
4219 if (Kind
.getKind() == InitializationKind::IK_Default
&&
4220 (Entity
.getKind() == InitializedEntity::EK_Base
||
4221 Entity
.getKind() == InitializedEntity::EK_Member
) &&
4222 isa
<CXXConstructorDecl
>(S
.CurContext
)) {
4223 // This is implicit default initialization of a member or
4224 // base within a constructor. If no viable function was
4225 // found, notify the user that she needs to explicitly
4226 // initialize this base/member.
4227 CXXConstructorDecl
*Constructor
4228 = cast
<CXXConstructorDecl
>(S
.CurContext
);
4229 if (Entity
.getKind() == InitializedEntity::EK_Base
) {
4230 S
.Diag(Kind
.getLocation(), diag::err_missing_default_ctor
)
4231 << Constructor
->isImplicit()
4232 << S
.Context
.getTypeDeclType(Constructor
->getParent())
4234 << Entity
.getType();
4236 RecordDecl
*BaseDecl
4237 = Entity
.getBaseSpecifier()->getType()->getAs
<RecordType
>()
4239 S
.Diag(BaseDecl
->getLocation(), diag::note_previous_decl
)
4240 << S
.Context
.getTagDeclType(BaseDecl
);
4242 S
.Diag(Kind
.getLocation(), diag::err_missing_default_ctor
)
4243 << Constructor
->isImplicit()
4244 << S
.Context
.getTypeDeclType(Constructor
->getParent())
4246 << Entity
.getName();
4247 S
.Diag(Entity
.getDecl()->getLocation(), diag::note_field_decl
);
4249 if (const RecordType
*Record
4250 = Entity
.getType()->getAs
<RecordType
>())
4251 S
.Diag(Record
->getDecl()->getLocation(),
4252 diag::note_previous_decl
)
4253 << S
.Context
.getTagDeclType(Record
->getDecl());
4258 S
.Diag(Kind
.getLocation(), diag::err_ovl_no_viable_function_in_init
)
4259 << DestType
<< ArgsRange
;
4260 FailedCandidateSet
.NoteCandidates(S
, OCD_AllCandidates
, Args
, NumArgs
);
4264 S
.Diag(Kind
.getLocation(), diag::err_ovl_deleted_init
)
4265 << true << DestType
<< ArgsRange
;
4266 OverloadCandidateSet::iterator Best
;
4267 OverloadingResult Ovl
4268 = FailedCandidateSet
.BestViableFunction(S
, Kind
.getLocation(), Best
);
4269 if (Ovl
== OR_Deleted
) {
4270 S
.Diag(Best
->Function
->getLocation(), diag::note_unavailable_here
)
4271 << Best
->Function
->isDeleted();
4273 llvm_unreachable("Inconsistent overload resolution?");
4279 llvm_unreachable("Conversion did not fail!");
4285 case FK_DefaultInitOfConst
:
4286 if (Entity
.getKind() == InitializedEntity::EK_Member
&&
4287 isa
<CXXConstructorDecl
>(S
.CurContext
)) {
4288 // This is implicit default-initialization of a const member in
4289 // a constructor. Complain that it needs to be explicitly
4291 CXXConstructorDecl
*Constructor
= cast
<CXXConstructorDecl
>(S
.CurContext
);
4292 S
.Diag(Kind
.getLocation(), diag::err_uninitialized_member_in_ctor
)
4293 << Constructor
->isImplicit()
4294 << S
.Context
.getTypeDeclType(Constructor
->getParent())
4296 << Entity
.getName();
4297 S
.Diag(Entity
.getDecl()->getLocation(), diag::note_previous_decl
)
4298 << Entity
.getName();
4300 S
.Diag(Kind
.getLocation(), diag::err_default_init_const
)
4301 << DestType
<< (bool)DestType
->getAs
<RecordType
>();
4306 S
.RequireCompleteType(Kind
.getLocation(), DestType
,
4307 diag::err_init_incomplete_type
);
4311 PrintInitLocationNote(S
, Entity
);
4315 void InitializationSequence::dump(llvm::raw_ostream
&OS
) const {
4316 switch (SequenceKind
) {
4317 case FailedSequence
: {
4318 OS
<< "Failed sequence: ";
4320 case FK_TooManyInitsForReference
:
4321 OS
<< "too many initializers for reference";
4324 case FK_ArrayNeedsInitList
:
4325 OS
<< "array requires initializer list";
4328 case FK_ArrayNeedsInitListOrStringLiteral
:
4329 OS
<< "array requires initializer list or string literal";
4332 case FK_AddressOfOverloadFailed
:
4333 OS
<< "address of overloaded function failed";
4336 case FK_ReferenceInitOverloadFailed
:
4337 OS
<< "overload resolution for reference initialization failed";
4340 case FK_NonConstLValueReferenceBindingToTemporary
:
4341 OS
<< "non-const lvalue reference bound to temporary";
4344 case FK_NonConstLValueReferenceBindingToUnrelated
:
4345 OS
<< "non-const lvalue reference bound to unrelated type";
4348 case FK_RValueReferenceBindingToLValue
:
4349 OS
<< "rvalue reference bound to an lvalue";
4352 case FK_ReferenceInitDropsQualifiers
:
4353 OS
<< "reference initialization drops qualifiers";
4356 case FK_ReferenceInitFailed
:
4357 OS
<< "reference initialization failed";
4360 case FK_ConversionFailed
:
4361 OS
<< "conversion failed";
4364 case FK_TooManyInitsForScalar
:
4365 OS
<< "too many initializers for scalar";
4368 case FK_ReferenceBindingToInitList
:
4369 OS
<< "referencing binding to initializer list";
4372 case FK_InitListBadDestinationType
:
4373 OS
<< "initializer list for non-aggregate, non-scalar type";
4376 case FK_UserConversionOverloadFailed
:
4377 OS
<< "overloading failed for user-defined conversion";
4380 case FK_ConstructorOverloadFailed
:
4381 OS
<< "constructor overloading failed";
4384 case FK_DefaultInitOfConst
:
4385 OS
<< "default initialization of a const variable";
4389 OS
<< "initialization of incomplete type";
4396 case DependentSequence
:
4397 OS
<< "Dependent sequence: ";
4400 case UserDefinedConversion
:
4401 OS
<< "User-defined conversion sequence: ";
4404 case ConstructorInitialization
:
4405 OS
<< "Constructor initialization sequence: ";
4408 case ReferenceBinding
:
4409 OS
<< "Reference binding: ";
4412 case ListInitialization
:
4413 OS
<< "List initialization: ";
4416 case ZeroInitialization
:
4417 OS
<< "Zero initialization\n";
4420 case NoInitialization
:
4421 OS
<< "No initialization\n";
4424 case StandardConversion
:
4425 OS
<< "Standard conversion: ";
4429 OS
<< "C assignment: ";
4433 OS
<< "String initialization: ";
4437 for (step_iterator S
= step_begin(), SEnd
= step_end(); S
!= SEnd
; ++S
) {
4438 if (S
!= step_begin()) {
4443 case SK_ResolveAddressOfOverloadedFunction
:
4444 OS
<< "resolve address of overloaded function";
4447 case SK_CastDerivedToBaseRValue
:
4448 OS
<< "derived-to-base case (rvalue" << S
->Type
.getAsString() << ")";
4451 case SK_CastDerivedToBaseXValue
:
4452 OS
<< "derived-to-base case (xvalue" << S
->Type
.getAsString() << ")";
4455 case SK_CastDerivedToBaseLValue
:
4456 OS
<< "derived-to-base case (lvalue" << S
->Type
.getAsString() << ")";
4459 case SK_BindReference
:
4460 OS
<< "bind reference to lvalue";
4463 case SK_BindReferenceToTemporary
:
4464 OS
<< "bind reference to a temporary";
4467 case SK_ExtraneousCopyToTemporary
:
4468 OS
<< "extraneous C++03 copy to temporary";
4471 case SK_UserConversion
:
4472 OS
<< "user-defined conversion via " << S
->Function
.Function
;
4475 case SK_QualificationConversionRValue
:
4476 OS
<< "qualification conversion (rvalue)";
4478 case SK_QualificationConversionXValue
:
4479 OS
<< "qualification conversion (xvalue)";
4481 case SK_QualificationConversionLValue
:
4482 OS
<< "qualification conversion (lvalue)";
4485 case SK_ConversionSequence
:
4486 OS
<< "implicit conversion sequence (";
4487 S
->ICS
->DebugPrint(); // FIXME: use OS
4491 case SK_ListInitialization
:
4492 OS
<< "list initialization";
4495 case SK_ConstructorInitialization
:
4496 OS
<< "constructor initialization";
4499 case SK_ZeroInitialization
:
4500 OS
<< "zero initialization";
4503 case SK_CAssignment
:
4504 OS
<< "C assignment";
4508 OS
<< "string initialization";
4511 case SK_ObjCObjectConversion
:
4512 OS
<< "Objective-C object conversion";
4518 void InitializationSequence::dump() const {
4522 //===----------------------------------------------------------------------===//
4523 // Initialization helper functions
4524 //===----------------------------------------------------------------------===//
4526 Sema::PerformCopyInitialization(const InitializedEntity
&Entity
,
4527 SourceLocation EqualLoc
,
4529 if (Init
.isInvalid())
4532 Expr
*InitE
= Init
.get();
4533 assert(InitE
&& "No initialization expression?");
4535 if (EqualLoc
.isInvalid())
4536 EqualLoc
= InitE
->getLocStart();
4538 InitializationKind Kind
= InitializationKind::CreateCopy(InitE
->getLocStart(),
4540 InitializationSequence
Seq(*this, Entity
, Kind
, &InitE
, 1);
4542 return Seq
.Perform(*this, Entity
, Kind
, MultiExprArg(&InitE
, 1));