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.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/Designator.h"
15 #include "clang/Sema/Initialization.h"
16 #include "clang/Sema/Lookup.h"
17 #include "clang/Sema/SemaInternal.h"
18 #include "clang/Lex/Preprocessor.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/TypeLoc.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/raw_ostream.h"
27 using namespace clang;
29 //===----------------------------------------------------------------------===//
30 // Sema Initialization Checking
31 //===----------------------------------------------------------------------===//
33 static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
34 ASTContext &Context) {
35 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
38 // See if this is a string literal or @encode.
39 Init = Init->IgnoreParens();
41 // Handle @encode, which is a narrow string.
42 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
45 // Otherwise we can only handle string literals.
46 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
47 if (SL == 0) return 0;
49 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
51 switch (SL->getKind()) {
52 case StringLiteral::Ascii:
53 case StringLiteral::UTF8:
54 // char array can be initialized with a narrow string.
55 // Only allow char x[] = "foo"; not char x[] = L"foo";
56 return ElemTy->isCharType() ? Init : 0;
57 case StringLiteral::UTF16:
58 return ElemTy->isChar16Type() ? Init : 0;
59 case StringLiteral::UTF32:
60 return ElemTy->isChar32Type() ? Init : 0;
61 case StringLiteral::Wide:
62 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
63 // correction from DR343): "An array with element type compatible with a
64 // qualified or unqualified version of wchar_t may be initialized by a wide
65 // string literal, optionally enclosed in braces."
66 if (Context.typesAreCompatible(Context.getWCharType(),
67 ElemTy.getUnqualifiedType()))
73 llvm_unreachable("missed a StringLiteral kind?");
76 static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
77 const ArrayType *arrayType = Context.getAsArrayType(declType);
78 if (!arrayType) return 0;
80 return IsStringInit(init, arrayType, Context);
83 static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
85 // Get the length of the string as parsed.
87 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
90 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
91 // C99 6.7.8p14. We have an array of character type with unknown size
92 // being initialized to a string literal.
93 llvm::APSInt ConstVal(32);
95 // Return a new array type (C99 6.7.8p22).
96 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
98 ArrayType::Normal, 0);
102 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
104 // We have an array of character type with known size. However,
105 // the size may be smaller or larger than the string we are initializing.
106 // FIXME: Avoid truncation for 64-bit length strings.
107 if (S.getLangOptions().CPlusPlus) {
108 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
109 // For Pascal strings it's OK to strip off the terminating null character,
110 // so the example below is valid:
112 // unsigned char a[2] = "\pa";
117 // [dcl.init.string]p2
118 if (StrLength > CAT->getSize().getZExtValue())
119 S.Diag(Str->getSourceRange().getBegin(),
120 diag::err_initializer_string_for_char_array_too_long)
121 << Str->getSourceRange();
124 if (StrLength-1 > CAT->getSize().getZExtValue())
125 S.Diag(Str->getSourceRange().getBegin(),
126 diag::warn_initializer_string_for_char_array_too_long)
127 << Str->getSourceRange();
130 // Set the type to the actual size that we are initializing. If we have
132 // char x[1] = "foo";
133 // then this will set the string literal's type to char[1].
137 //===----------------------------------------------------------------------===//
138 // Semantic checking for initializer lists.
139 //===----------------------------------------------------------------------===//
141 /// @brief Semantic checking for initializer lists.
143 /// The InitListChecker class contains a set of routines that each
144 /// handle the initialization of a certain kind of entity, e.g.,
145 /// arrays, vectors, struct/union types, scalars, etc. The
146 /// InitListChecker itself performs a recursive walk of the subobject
147 /// structure of the type to be initialized, while stepping through
148 /// the initializer list one element at a time. The IList and Index
149 /// parameters to each of the Check* routines contain the active
150 /// (syntactic) initializer list and the index into that initializer
151 /// list that represents the current initializer. Each routine is
152 /// responsible for moving that Index forward as it consumes elements.
154 /// Each Check* routine also has a StructuredList/StructuredIndex
155 /// arguments, which contains the current "structured" (semantic)
156 /// initializer list and the index into that initializer list where we
157 /// are copying initializers as we map them over to the semantic
158 /// list. Once we have completed our recursive walk of the subobject
159 /// structure, we will have constructed a full semantic initializer
162 /// C99 designators cause changes in the initializer list traversal,
163 /// because they make the initialization "jump" into a specific
164 /// subobject and then continue the initialization from that
165 /// point. CheckDesignatedInitializer() recursively steps into the
166 /// designated subobject and manages backing out the recursion to
167 /// initialize the subobjects after the one designated.
169 class InitListChecker {
172 bool VerifyOnly; // no diagnostics, no structure building
173 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
174 InitListExpr *FullyStructuredList;
176 void CheckImplicitInitList(const InitializedEntity &Entity,
177 InitListExpr *ParentIList, QualType T,
178 unsigned &Index, InitListExpr *StructuredList,
179 unsigned &StructuredIndex);
180 void CheckExplicitInitList(const InitializedEntity &Entity,
181 InitListExpr *IList, QualType &T,
182 unsigned &Index, InitListExpr *StructuredList,
183 unsigned &StructuredIndex,
184 bool TopLevelObject = false);
185 void CheckListElementTypes(const InitializedEntity &Entity,
186 InitListExpr *IList, QualType &DeclType,
187 bool SubobjectIsDesignatorContext,
189 InitListExpr *StructuredList,
190 unsigned &StructuredIndex,
191 bool TopLevelObject = false);
192 void CheckSubElementType(const InitializedEntity &Entity,
193 InitListExpr *IList, QualType ElemType,
195 InitListExpr *StructuredList,
196 unsigned &StructuredIndex);
197 void CheckComplexType(const InitializedEntity &Entity,
198 InitListExpr *IList, QualType DeclType,
200 InitListExpr *StructuredList,
201 unsigned &StructuredIndex);
202 void CheckScalarType(const InitializedEntity &Entity,
203 InitListExpr *IList, QualType DeclType,
205 InitListExpr *StructuredList,
206 unsigned &StructuredIndex);
207 void CheckReferenceType(const InitializedEntity &Entity,
208 InitListExpr *IList, QualType DeclType,
210 InitListExpr *StructuredList,
211 unsigned &StructuredIndex);
212 void CheckVectorType(const InitializedEntity &Entity,
213 InitListExpr *IList, QualType DeclType, unsigned &Index,
214 InitListExpr *StructuredList,
215 unsigned &StructuredIndex);
216 void CheckStructUnionTypes(const InitializedEntity &Entity,
217 InitListExpr *IList, QualType DeclType,
218 RecordDecl::field_iterator Field,
219 bool SubobjectIsDesignatorContext, unsigned &Index,
220 InitListExpr *StructuredList,
221 unsigned &StructuredIndex,
222 bool TopLevelObject = false);
223 void CheckArrayType(const InitializedEntity &Entity,
224 InitListExpr *IList, QualType &DeclType,
225 llvm::APSInt elementIndex,
226 bool SubobjectIsDesignatorContext, unsigned &Index,
227 InitListExpr *StructuredList,
228 unsigned &StructuredIndex);
229 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
230 InitListExpr *IList, DesignatedInitExpr *DIE,
232 QualType &CurrentObjectType,
233 RecordDecl::field_iterator *NextField,
234 llvm::APSInt *NextElementIndex,
236 InitListExpr *StructuredList,
237 unsigned &StructuredIndex,
238 bool FinishSubobjectInit,
239 bool TopLevelObject);
240 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
241 QualType CurrentObjectType,
242 InitListExpr *StructuredList,
243 unsigned StructuredIndex,
244 SourceRange InitRange);
245 void UpdateStructuredListElement(InitListExpr *StructuredList,
246 unsigned &StructuredIndex,
248 int numArrayElements(QualType DeclType);
249 int numStructUnionElements(QualType DeclType);
251 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
252 const InitializedEntity &ParentEntity,
253 InitListExpr *ILE, bool &RequiresSecondPass);
254 void FillInValueInitializations(const InitializedEntity &Entity,
255 InitListExpr *ILE, bool &RequiresSecondPass);
256 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
257 Expr *InitExpr, FieldDecl *Field,
258 bool TopLevelObject);
260 InitListChecker(Sema &S, const InitializedEntity &Entity,
261 InitListExpr *IL, QualType &T, bool VerifyOnly);
262 bool HadError() { return hadError; }
264 // @brief Retrieves the fully-structured initializer list used for
265 // semantic analysis and code generation.
266 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
268 } // end anonymous namespace
270 void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
271 const InitializedEntity &ParentEntity,
273 bool &RequiresSecondPass) {
274 SourceLocation Loc = ILE->getSourceRange().getBegin();
275 unsigned NumInits = ILE->getNumInits();
276 InitializedEntity MemberEntity
277 = InitializedEntity::InitializeMember(Field, &ParentEntity);
278 if (Init >= NumInits || !ILE->getInit(Init)) {
279 // FIXME: We probably don't need to handle references
280 // specially here, since value-initialization of references is
281 // handled in InitializationSequence.
282 if (Field->getType()->isReferenceType()) {
283 // C++ [dcl.init.aggr]p9:
284 // If an incomplete or empty initializer-list leaves a
285 // member of reference type uninitialized, the program is
287 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
289 << ILE->getSyntacticForm()->getSourceRange();
290 SemaRef.Diag(Field->getLocation(),
291 diag::note_uninit_reference_member);
296 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
298 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
300 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
305 ExprResult MemberInit
306 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
307 if (MemberInit.isInvalid()) {
314 } else if (Init < NumInits) {
315 ILE->setInit(Init, MemberInit.takeAs<Expr>());
316 } else if (InitSeq.isConstructorInitialization()) {
317 // Value-initialization requires a constructor call, so
318 // extend the initializer list to include the constructor
319 // call and make a note that we'll need to take another pass
320 // through the initializer list.
321 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
322 RequiresSecondPass = true;
324 } else if (InitListExpr *InnerILE
325 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
326 FillInValueInitializations(MemberEntity, InnerILE,
330 /// Recursively replaces NULL values within the given initializer list
331 /// with expressions that perform value-initialization of the
332 /// appropriate type.
334 InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
336 bool &RequiresSecondPass) {
337 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
338 "Should not have void type");
339 SourceLocation Loc = ILE->getSourceRange().getBegin();
340 if (ILE->getSyntacticForm())
341 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
343 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
344 if (RType->getDecl()->isUnion() &&
345 ILE->getInitializedFieldInUnion())
346 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
347 Entity, ILE, RequiresSecondPass);
350 for (RecordDecl::field_iterator
351 Field = RType->getDecl()->field_begin(),
352 FieldEnd = RType->getDecl()->field_end();
353 Field != FieldEnd; ++Field) {
354 if (Field->isUnnamedBitfield())
360 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
366 // Only look at the first initialization of a union.
367 if (RType->getDecl()->isUnion())
375 QualType ElementType;
377 InitializedEntity ElementEntity = Entity;
378 unsigned NumInits = ILE->getNumInits();
379 unsigned NumElements = NumInits;
380 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
381 ElementType = AType->getElementType();
382 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
383 NumElements = CAType->getSize().getZExtValue();
384 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
386 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
387 ElementType = VType->getElementType();
388 NumElements = VType->getNumElements();
389 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
392 ElementType = ILE->getType();
395 for (unsigned Init = 0; Init != NumElements; ++Init) {
399 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
400 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
401 ElementEntity.setElementIndex(Init);
403 if (Init >= NumInits || !ILE->getInit(Init)) {
404 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
406 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
408 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
413 ExprResult ElementInit
414 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
415 if (ElementInit.isInvalid()) {
422 } else if (Init < NumInits) {
423 // For arrays, just set the expression used for value-initialization
424 // of the "holes" in the array.
425 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
426 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
428 ILE->setInit(Init, ElementInit.takeAs<Expr>());
430 // For arrays, just set the expression used for value-initialization
431 // of the rest of elements and exit.
432 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
433 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
437 if (InitSeq.isConstructorInitialization()) {
438 // Value-initialization requires a constructor call, so
439 // extend the initializer list to include the constructor
440 // call and make a note that we'll need to take another pass
441 // through the initializer list.
442 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
443 RequiresSecondPass = true;
446 } else if (InitListExpr *InnerILE
447 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
448 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
453 InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
454 InitListExpr *IL, QualType &T,
456 : SemaRef(S), VerifyOnly(VerifyOnly) {
459 unsigned newIndex = 0;
460 unsigned newStructuredIndex = 0;
462 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
463 CheckExplicitInitList(Entity, IL, T, newIndex,
464 FullyStructuredList, newStructuredIndex,
465 /*TopLevelObject=*/true);
467 if (!hadError && !VerifyOnly) {
468 bool RequiresSecondPass = false;
469 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
470 if (RequiresSecondPass && !hadError)
471 FillInValueInitializations(Entity, FullyStructuredList,
476 int InitListChecker::numArrayElements(QualType DeclType) {
477 // FIXME: use a proper constant
478 int maxElements = 0x7FFFFFFF;
479 if (const ConstantArrayType *CAT =
480 SemaRef.Context.getAsConstantArrayType(DeclType)) {
481 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
486 int InitListChecker::numStructUnionElements(QualType DeclType) {
487 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
488 int InitializableMembers = 0;
489 for (RecordDecl::field_iterator
490 Field = structDecl->field_begin(),
491 FieldEnd = structDecl->field_end();
492 Field != FieldEnd; ++Field) {
493 if (!Field->isUnnamedBitfield())
494 ++InitializableMembers;
496 if (structDecl->isUnion())
497 return std::min(InitializableMembers, 1);
498 return InitializableMembers - structDecl->hasFlexibleArrayMember();
501 void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
502 InitListExpr *ParentIList,
503 QualType T, unsigned &Index,
504 InitListExpr *StructuredList,
505 unsigned &StructuredIndex) {
508 if (T->isArrayType())
509 maxElements = numArrayElements(T);
510 else if (T->isRecordType())
511 maxElements = numStructUnionElements(T);
512 else if (T->isVectorType())
513 maxElements = T->getAs<VectorType>()->getNumElements();
515 llvm_unreachable("CheckImplicitInitList(): Illegal type");
517 if (maxElements == 0) {
519 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
520 diag::err_implicit_empty_initializer);
526 // Build a structured initializer list corresponding to this subobject.
527 InitListExpr *StructuredSubobjectInitList
528 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
530 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
531 ParentIList->getSourceRange().getEnd()));
532 unsigned StructuredSubobjectInitIndex = 0;
534 // Check the element types and build the structural subobject.
535 unsigned StartIndex = Index;
536 CheckListElementTypes(Entity, ParentIList, T,
537 /*SubobjectIsDesignatorContext=*/false, Index,
538 StructuredSubobjectInitList,
539 StructuredSubobjectInitIndex);
540 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
542 StructuredSubobjectInitList->setType(T);
544 // Update the structured sub-object initializer so that it's ending
545 // range corresponds with the end of the last initializer it used.
546 if (EndIndex < ParentIList->getNumInits()) {
547 SourceLocation EndLoc
548 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
549 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
552 // Warn about missing braces.
553 if (T->isArrayType() || T->isRecordType()) {
554 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
555 diag::warn_missing_braces)
556 << StructuredSubobjectInitList->getSourceRange()
557 << FixItHint::CreateInsertion(
558 StructuredSubobjectInitList->getLocStart(), "{")
559 << FixItHint::CreateInsertion(
560 SemaRef.PP.getLocForEndOfToken(
561 StructuredSubobjectInitList->getLocEnd()),
567 void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
568 InitListExpr *IList, QualType &T,
570 InitListExpr *StructuredList,
571 unsigned &StructuredIndex,
572 bool TopLevelObject) {
573 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
575 SyntacticToSemantic[IList] = StructuredList;
576 StructuredList->setSyntacticForm(IList);
578 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
579 Index, StructuredList, StructuredIndex, TopLevelObject);
581 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
582 IList->setType(ExprTy);
583 StructuredList->setType(ExprTy);
588 if (Index < IList->getNumInits()) {
589 // We have leftover initializers
591 if (SemaRef.getLangOptions().CPlusPlus ||
592 (SemaRef.getLangOptions().OpenCL &&
593 IList->getType()->isVectorType())) {
599 if (StructuredIndex == 1 &&
600 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
601 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
602 if (SemaRef.getLangOptions().CPlusPlus) {
603 DK = diag::err_excess_initializers_in_char_array_initializer;
607 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
608 << IList->getInit(Index)->getSourceRange();
609 } else if (!T->isIncompleteType()) {
610 // Don't complain for incomplete types, since we'll get an error
612 QualType CurrentObjectType = StructuredList->getType();
614 CurrentObjectType->isArrayType()? 0 :
615 CurrentObjectType->isVectorType()? 1 :
616 CurrentObjectType->isScalarType()? 2 :
617 CurrentObjectType->isUnionType()? 3 :
620 unsigned DK = diag::warn_excess_initializers;
621 if (SemaRef.getLangOptions().CPlusPlus) {
622 DK = diag::err_excess_initializers;
625 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
626 DK = diag::err_excess_initializers;
630 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
631 << initKind << IList->getInit(Index)->getSourceRange();
635 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
637 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
638 << IList->getSourceRange()
639 << FixItHint::CreateRemoval(IList->getLocStart())
640 << FixItHint::CreateRemoval(IList->getLocEnd());
643 void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
646 bool SubobjectIsDesignatorContext,
648 InitListExpr *StructuredList,
649 unsigned &StructuredIndex,
650 bool TopLevelObject) {
651 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
652 // Explicitly braced initializer for complex type can be real+imaginary
654 CheckComplexType(Entity, IList, DeclType, Index,
655 StructuredList, StructuredIndex);
656 } else if (DeclType->isScalarType()) {
657 CheckScalarType(Entity, IList, DeclType, Index,
658 StructuredList, StructuredIndex);
659 } else if (DeclType->isVectorType()) {
660 CheckVectorType(Entity, IList, DeclType, Index,
661 StructuredList, StructuredIndex);
662 } else if (DeclType->isAggregateType()) {
663 if (DeclType->isRecordType()) {
664 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
665 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
666 SubobjectIsDesignatorContext, Index,
667 StructuredList, StructuredIndex,
669 } else if (DeclType->isArrayType()) {
671 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
673 CheckArrayType(Entity, IList, DeclType, Zero,
674 SubobjectIsDesignatorContext, Index,
675 StructuredList, StructuredIndex);
677 llvm_unreachable("Aggregate that isn't a structure or array?!");
678 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
679 // This type is invalid, issue a diagnostic.
682 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
685 } else if (DeclType->isRecordType()) {
686 // C++ [dcl.init]p14:
687 // [...] If the class is an aggregate (8.5.1), and the initializer
688 // is a brace-enclosed list, see 8.5.1.
690 // Note: 8.5.1 is handled below; here, we diagnose the case where
691 // we have an initializer list and a destination type that is not
693 // FIXME: In C++0x, this is yet another form of initialization.
695 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
696 << DeclType << IList->getSourceRange();
698 } else if (DeclType->isReferenceType()) {
699 CheckReferenceType(Entity, IList, DeclType, Index,
700 StructuredList, StructuredIndex);
701 } else if (DeclType->isObjCObjectType()) {
703 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
708 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
714 void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
718 InitListExpr *StructuredList,
719 unsigned &StructuredIndex) {
720 Expr *expr = IList->getInit(Index);
721 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
722 unsigned newIndex = 0;
723 unsigned newStructuredIndex = 0;
724 InitListExpr *newStructuredList
725 = getStructuredSubobjectInit(IList, Index, ElemType,
726 StructuredList, StructuredIndex,
727 SubInitList->getSourceRange());
728 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
729 newStructuredList, newStructuredIndex);
733 } else if (ElemType->isScalarType()) {
734 return CheckScalarType(Entity, IList, ElemType, Index,
735 StructuredList, StructuredIndex);
736 } else if (ElemType->isReferenceType()) {
737 return CheckReferenceType(Entity, IList, ElemType, Index,
738 StructuredList, StructuredIndex);
741 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
742 // arrayType can be incomplete if we're initializing a flexible
743 // array member. There's nothing we can do with the completed
744 // type here, though.
746 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
748 CheckStringInit(Str, ElemType, arrayType, SemaRef);
749 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
755 // Fall through for subaggregate initialization.
757 } else if (SemaRef.getLangOptions().CPlusPlus) {
758 // C++ [dcl.init.aggr]p12:
759 // All implicit type conversions (clause 4) are considered when
760 // initializing the aggregate member with an initializer from
761 // an initializer-list. If the initializer can initialize a
762 // member, the member is initialized. [...]
764 // FIXME: Better EqualLoc?
765 InitializationKind Kind =
766 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
767 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
772 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
773 if (Result.isInvalid())
776 UpdateStructuredListElement(StructuredList, StructuredIndex,
777 Result.takeAs<Expr>());
783 // Fall through for subaggregate initialization
787 // The initializer for a structure or union object that has
788 // automatic storage duration shall be either an initializer
789 // list as described below, or a single expression that has
790 // compatible structure or union type. In the latter case, the
791 // initial value of the object, including unnamed members, is
792 // that of the expression.
793 ExprResult ExprRes = SemaRef.Owned(expr);
794 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
795 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
797 == Sema::Compatible) {
798 if (ExprRes.isInvalid())
801 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
802 if (ExprRes.isInvalid())
805 UpdateStructuredListElement(StructuredList, StructuredIndex,
806 ExprRes.takeAs<Expr>());
811 // Fall through for subaggregate initialization
814 // C++ [dcl.init.aggr]p12:
816 // [...] Otherwise, if the member is itself a non-empty
817 // subaggregate, brace elision is assumed and the initializer is
818 // considered for the initialization of the first member of
820 if (!SemaRef.getLangOptions().OpenCL &&
821 (ElemType->isAggregateType() || ElemType->isVectorType())) {
822 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
827 // We cannot initialize this element, so let
828 // PerformCopyInitialization produce the appropriate diagnostic.
829 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
831 /*TopLevelOfInitList=*/true);
839 void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
840 InitListExpr *IList, QualType DeclType,
842 InitListExpr *StructuredList,
843 unsigned &StructuredIndex) {
844 assert(Index == 0 && "Index in explicit init list must be zero");
846 // As an extension, clang supports complex initializers, which initialize
847 // a complex number component-wise. When an explicit initializer list for
848 // a complex number contains two two initializers, this extension kicks in:
849 // it exepcts the initializer list to contain two elements convertible to
850 // the element type of the complex type. The first element initializes
851 // the real part, and the second element intitializes the imaginary part.
853 if (IList->getNumInits() != 2)
854 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
857 // This is an extension in C. (The builtin _Complex type does not exist
858 // in the C++ standard.)
859 if (!SemaRef.getLangOptions().CPlusPlus && !VerifyOnly)
860 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
861 << IList->getSourceRange();
863 // Initialize the complex number.
864 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
865 InitializedEntity ElementEntity =
866 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
868 for (unsigned i = 0; i < 2; ++i) {
869 ElementEntity.setElementIndex(Index);
870 CheckSubElementType(ElementEntity, IList, elementType, Index,
871 StructuredList, StructuredIndex);
876 void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
877 InitListExpr *IList, QualType DeclType,
879 InitListExpr *StructuredList,
880 unsigned &StructuredIndex) {
881 if (Index >= IList->getNumInits()) {
882 if (!SemaRef.getLangOptions().CPlusPlus0x) {
884 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
885 << IList->getSourceRange();
893 Expr *expr = IList->getInit(Index);
894 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
896 SemaRef.Diag(SubIList->getLocStart(),
897 diag::warn_many_braces_around_scalar_init)
898 << SubIList->getSourceRange();
900 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
903 } else if (isa<DesignatedInitExpr>(expr)) {
905 SemaRef.Diag(expr->getSourceRange().getBegin(),
906 diag::err_designator_for_scalar_init)
907 << DeclType << expr->getSourceRange();
915 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
922 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
924 /*TopLevelOfInitList=*/true);
926 Expr *ResultExpr = 0;
928 if (Result.isInvalid())
929 hadError = true; // types weren't compatible.
931 ResultExpr = Result.takeAs<Expr>();
933 if (ResultExpr != expr) {
934 // The type was promoted, update initializer list.
935 IList->setInit(Index, ResultExpr);
941 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
945 void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
946 InitListExpr *IList, QualType DeclType,
948 InitListExpr *StructuredList,
949 unsigned &StructuredIndex) {
950 if (Index >= IList->getNumInits()) {
951 // FIXME: It would be wonderful if we could point at the actual member. In
952 // general, it would be useful to pass location information down the stack,
953 // so that we know the location (or decl) of the "current object" being
956 SemaRef.Diag(IList->getLocStart(),
957 diag::err_init_reference_member_uninitialized)
959 << IList->getSourceRange();
966 Expr *expr = IList->getInit(Index);
967 if (isa<InitListExpr>(expr)) {
968 // FIXME: Allowed in C++11.
970 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
971 << DeclType << IList->getSourceRange();
979 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
986 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
988 /*TopLevelOfInitList=*/true);
990 if (Result.isInvalid())
993 expr = Result.takeAs<Expr>();
994 IList->setInit(Index, expr);
999 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1003 void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1004 InitListExpr *IList, QualType DeclType,
1006 InitListExpr *StructuredList,
1007 unsigned &StructuredIndex) {
1008 if (Index >= IList->getNumInits())
1011 const VectorType *VT = DeclType->getAs<VectorType>();
1012 unsigned maxElements = VT->getNumElements();
1013 unsigned numEltsInit = 0;
1014 QualType elementType = VT->getElementType();
1016 if (!SemaRef.getLangOptions().OpenCL) {
1017 // If the initializing element is a vector, try to copy-initialize
1018 // instead of breaking it apart (which is doomed to failure anyway).
1019 Expr *Init = IList->getInit(Index);
1020 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1022 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1029 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
1030 SemaRef.Owned(Init),
1031 /*TopLevelOfInitList=*/true);
1033 Expr *ResultExpr = 0;
1034 if (Result.isInvalid())
1035 hadError = true; // types weren't compatible.
1037 ResultExpr = Result.takeAs<Expr>();
1039 if (ResultExpr != Init) {
1040 // The type was promoted, update initializer list.
1041 IList->setInit(Index, ResultExpr);
1047 UpdateStructuredListElement(StructuredList, StructuredIndex,
1053 InitializedEntity ElementEntity =
1054 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1056 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1057 // Don't attempt to go past the end of the init list
1058 if (Index >= IList->getNumInits())
1061 ElementEntity.setElementIndex(Index);
1062 CheckSubElementType(ElementEntity, IList, elementType, Index,
1063 StructuredList, StructuredIndex);
1068 InitializedEntity ElementEntity =
1069 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1071 // OpenCL initializers allows vectors to be constructed from vectors.
1072 for (unsigned i = 0; i < maxElements; ++i) {
1073 // Don't attempt to go past the end of the init list
1074 if (Index >= IList->getNumInits())
1077 ElementEntity.setElementIndex(Index);
1079 QualType IType = IList->getInit(Index)->getType();
1080 if (!IType->isVectorType()) {
1081 CheckSubElementType(ElementEntity, IList, elementType, Index,
1082 StructuredList, StructuredIndex);
1086 const VectorType *IVT = IType->getAs<VectorType>();
1087 unsigned numIElts = IVT->getNumElements();
1089 if (IType->isExtVectorType())
1090 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1092 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1093 IVT->getVectorKind());
1094 CheckSubElementType(ElementEntity, IList, VecType, Index,
1095 StructuredList, StructuredIndex);
1096 numEltsInit += numIElts;
1100 // OpenCL requires all elements to be initialized.
1101 // FIXME: Shouldn't this set hadError to true then?
1102 if (numEltsInit != maxElements && !VerifyOnly)
1103 SemaRef.Diag(IList->getSourceRange().getBegin(),
1104 diag::err_vector_incorrect_num_initializers)
1105 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1108 void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1109 InitListExpr *IList, QualType &DeclType,
1110 llvm::APSInt elementIndex,
1111 bool SubobjectIsDesignatorContext,
1113 InitListExpr *StructuredList,
1114 unsigned &StructuredIndex) {
1115 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1117 // Check for the special-case of initializing an array with a string.
1118 if (Index < IList->getNumInits()) {
1119 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
1121 // We place the string literal directly into the resulting
1122 // initializer list. This is the only place where the structure
1123 // of the structured initializer list doesn't match exactly,
1124 // because doing so would involve allocating one character
1125 // constant for each string.
1127 CheckStringInit(Str, DeclType, arrayType, SemaRef);
1128 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1129 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1135 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1136 // Check for VLAs; in standard C it would be possible to check this
1137 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1138 // them in all sorts of strange places).
1140 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1141 diag::err_variable_object_no_init)
1142 << VAT->getSizeExpr()->getSourceRange();
1149 // We might know the maximum number of elements in advance.
1150 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1151 elementIndex.isUnsigned());
1152 bool maxElementsKnown = false;
1153 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
1154 maxElements = CAT->getSize();
1155 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
1156 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1157 maxElementsKnown = true;
1160 QualType elementType = arrayType->getElementType();
1161 while (Index < IList->getNumInits()) {
1162 Expr *Init = IList->getInit(Index);
1163 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1164 // If we're not the subobject that matches up with the '{' for
1165 // the designator, we shouldn't be handling the
1166 // designator. Return immediately.
1167 if (!SubobjectIsDesignatorContext)
1170 // Handle this designated initializer. elementIndex will be
1171 // updated to be the next array element we'll initialize.
1172 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1173 DeclType, 0, &elementIndex, Index,
1174 StructuredList, StructuredIndex, true,
1180 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1181 maxElements = maxElements.extend(elementIndex.getBitWidth());
1182 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1183 elementIndex = elementIndex.extend(maxElements.getBitWidth());
1184 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1186 // If the array is of incomplete type, keep track of the number of
1187 // elements in the initializer.
1188 if (!maxElementsKnown && elementIndex > maxElements)
1189 maxElements = elementIndex;
1194 // If we know the maximum number of elements, and we've already
1195 // hit it, stop consuming elements in the initializer list.
1196 if (maxElementsKnown && elementIndex == maxElements)
1199 InitializedEntity ElementEntity =
1200 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1202 // Check this element.
1203 CheckSubElementType(ElementEntity, IList, elementType, Index,
1204 StructuredList, StructuredIndex);
1207 // If the array is of incomplete type, keep track of the number of
1208 // elements in the initializer.
1209 if (!maxElementsKnown && elementIndex > maxElements)
1210 maxElements = elementIndex;
1212 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
1213 // If this is an incomplete array type, the actual type needs to
1214 // be calculated here.
1215 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
1216 if (maxElements == Zero) {
1217 // Sizing an array implicitly to zero is not allowed by ISO C,
1218 // but is supported by GNU.
1219 SemaRef.Diag(IList->getLocStart(),
1220 diag::ext_typecheck_zero_array_size);
1223 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
1224 ArrayType::Normal, 0);
1228 bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1231 bool TopLevelObject) {
1232 // Handle GNU flexible array initializers.
1233 unsigned FlexArrayDiag;
1234 if (isa<InitListExpr>(InitExpr) &&
1235 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1236 // Empty flexible array init always allowed as an extension
1237 FlexArrayDiag = diag::ext_flexible_array_init;
1238 } else if (SemaRef.getLangOptions().CPlusPlus) {
1239 // Disallow flexible array init in C++; it is not required for gcc
1240 // compatibility, and it needs work to IRGen correctly in general.
1241 FlexArrayDiag = diag::err_flexible_array_init;
1242 } else if (!TopLevelObject) {
1243 // Disallow flexible array init on non-top-level object
1244 FlexArrayDiag = diag::err_flexible_array_init;
1245 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1246 // Disallow flexible array init on anything which is not a variable.
1247 FlexArrayDiag = diag::err_flexible_array_init;
1248 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1249 // Disallow flexible array init on local variables.
1250 FlexArrayDiag = diag::err_flexible_array_init;
1252 // Allow other cases.
1253 FlexArrayDiag = diag::ext_flexible_array_init;
1257 SemaRef.Diag(InitExpr->getSourceRange().getBegin(),
1259 << InitExpr->getSourceRange().getBegin();
1260 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1264 return FlexArrayDiag != diag::ext_flexible_array_init;
1267 void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
1268 InitListExpr *IList,
1270 RecordDecl::field_iterator Field,
1271 bool SubobjectIsDesignatorContext,
1273 InitListExpr *StructuredList,
1274 unsigned &StructuredIndex,
1275 bool TopLevelObject) {
1276 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
1278 // If the record is invalid, some of it's members are invalid. To avoid
1279 // confusion, we forgo checking the intializer for the entire record.
1280 if (structDecl->isInvalidDecl()) {
1285 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1287 // Value-initialize the first named member of the union.
1288 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1289 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1290 Field != FieldEnd; ++Field) {
1291 if (Field->getDeclName()) {
1292 StructuredList->setInitializedFieldInUnion(*Field);
1300 // If structDecl is a forward declaration, this loop won't do
1301 // anything except look at designated initializers; That's okay,
1302 // because an error should get printed out elsewhere. It might be
1303 // worthwhile to skip over the rest of the initializer, though.
1304 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1305 RecordDecl::field_iterator FieldEnd = RD->field_end();
1306 bool InitializedSomething = false;
1307 bool CheckForMissingFields = true;
1308 while (Index < IList->getNumInits()) {
1309 Expr *Init = IList->getInit(Index);
1311 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1312 // If we're not the subobject that matches up with the '{' for
1313 // the designator, we shouldn't be handling the
1314 // designator. Return immediately.
1315 if (!SubobjectIsDesignatorContext)
1318 // Handle this designated initializer. Field will be updated to
1319 // the next field that we'll be initializing.
1320 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1321 DeclType, &Field, 0, Index,
1322 StructuredList, StructuredIndex,
1323 true, TopLevelObject))
1326 InitializedSomething = true;
1328 // Disable check for missing fields when designators are used.
1329 // This matches gcc behaviour.
1330 CheckForMissingFields = false;
1334 if (Field == FieldEnd) {
1335 // We've run out of fields. We're done.
1339 // We've already initialized a member of a union. We're done.
1340 if (InitializedSomething && DeclType->isUnionType())
1343 // If we've hit the flexible array member at the end, we're done.
1344 if (Field->getType()->isIncompleteArrayType())
1347 if (Field->isUnnamedBitfield()) {
1348 // Don't initialize unnamed bitfields, e.g. "int : 20;"
1353 // Make sure we can use this declaration.
1356 InvalidUse = !SemaRef.CanUseDecl(*Field);
1358 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1359 IList->getInit(Index)->getLocStart());
1367 InitializedEntity MemberEntity =
1368 InitializedEntity::InitializeMember(*Field, &Entity);
1369 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1370 StructuredList, StructuredIndex);
1371 InitializedSomething = true;
1373 if (DeclType->isUnionType() && !VerifyOnly) {
1374 // Initialize the first field within the union.
1375 StructuredList->setInitializedFieldInUnion(*Field);
1381 // Emit warnings for missing struct field initializers.
1382 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1383 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1384 !DeclType->isUnionType()) {
1385 // It is possible we have one or more unnamed bitfields remaining.
1386 // Find first (if any) named field and emit warning.
1387 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1389 if (!it->isUnnamedBitfield()) {
1390 SemaRef.Diag(IList->getSourceRange().getEnd(),
1391 diag::warn_missing_field_initializers) << it->getName();
1397 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
1398 Index >= IList->getNumInits())
1401 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1408 InitializedEntity MemberEntity =
1409 InitializedEntity::InitializeMember(*Field, &Entity);
1411 if (isa<InitListExpr>(IList->getInit(Index)))
1412 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1413 StructuredList, StructuredIndex);
1415 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
1416 StructuredList, StructuredIndex);
1419 /// \brief Expand a field designator that refers to a member of an
1420 /// anonymous struct or union into a series of field designators that
1421 /// refers to the field within the appropriate subobject.
1423 static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1424 DesignatedInitExpr *DIE,
1426 IndirectFieldDecl *IndirectField) {
1427 typedef DesignatedInitExpr::Designator Designator;
1429 // Build the replacement designators.
1430 SmallVector<Designator, 4> Replacements;
1431 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1432 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1434 Replacements.push_back(Designator((IdentifierInfo *)0,
1435 DIE->getDesignator(DesigIdx)->getDotLoc(),
1436 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1438 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1440 assert(isa<FieldDecl>(*PI));
1441 Replacements.back().setField(cast<FieldDecl>(*PI));
1444 // Expand the current designator into the set of replacement
1445 // designators, so we have a full subobject path down to where the
1446 // member of the anonymous struct/union is actually stored.
1447 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
1448 &Replacements[0] + Replacements.size());
1451 /// \brief Given an implicit anonymous field, search the IndirectField that
1452 /// corresponds to FieldName.
1453 static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1454 IdentifierInfo *FieldName) {
1455 assert(AnonField->isAnonymousStructOrUnion());
1456 Decl *NextDecl = AnonField->getNextDeclInContext();
1457 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1458 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1460 NextDecl = NextDecl->getNextDeclInContext();
1465 static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1466 DesignatedInitExpr *DIE) {
1467 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1468 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1469 for (unsigned I = 0; I < NumIndexExprs; ++I)
1470 IndexExprs[I] = DIE->getSubExpr(I + 1);
1471 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1472 DIE->size(), IndexExprs.data(),
1473 NumIndexExprs, DIE->getEqualOrColonLoc(),
1474 DIE->usesGNUSyntax(), DIE->getInit());
1477 /// @brief Check the well-formedness of a C99 designated initializer.
1479 /// Determines whether the designated initializer @p DIE, which
1480 /// resides at the given @p Index within the initializer list @p
1481 /// IList, is well-formed for a current object of type @p DeclType
1482 /// (C99 6.7.8). The actual subobject that this designator refers to
1483 /// within the current subobject is returned in either
1484 /// @p NextField or @p NextElementIndex (whichever is appropriate).
1486 /// @param IList The initializer list in which this designated
1487 /// initializer occurs.
1489 /// @param DIE The designated initializer expression.
1491 /// @param DesigIdx The index of the current designator.
1493 /// @param DeclType The type of the "current object" (C99 6.7.8p17),
1494 /// into which the designation in @p DIE should refer.
1496 /// @param NextField If non-NULL and the first designator in @p DIE is
1497 /// a field, this will be set to the field declaration corresponding
1498 /// to the field named by the designator.
1500 /// @param NextElementIndex If non-NULL and the first designator in @p
1501 /// DIE is an array designator or GNU array-range designator, this
1502 /// will be set to the last index initialized by this designator.
1504 /// @param Index Index into @p IList where the designated initializer
1507 /// @param StructuredList The initializer list expression that
1508 /// describes all of the subobject initializers in the order they'll
1509 /// actually be initialized.
1511 /// @returns true if there was an error, false otherwise.
1513 InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
1514 InitListExpr *IList,
1515 DesignatedInitExpr *DIE,
1517 QualType &CurrentObjectType,
1518 RecordDecl::field_iterator *NextField,
1519 llvm::APSInt *NextElementIndex,
1521 InitListExpr *StructuredList,
1522 unsigned &StructuredIndex,
1523 bool FinishSubobjectInit,
1524 bool TopLevelObject) {
1525 if (DesigIdx == DIE->size()) {
1526 // Check the actual initialization for the designated object type.
1527 bool prevHadError = hadError;
1529 // Temporarily remove the designator expression from the
1530 // initializer list that the child calls see, so that we don't try
1531 // to re-process the designator.
1532 unsigned OldIndex = Index;
1533 IList->setInit(OldIndex, DIE->getInit());
1535 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
1536 StructuredList, StructuredIndex);
1538 // Restore the designated initializer expression in the syntactic
1539 // form of the initializer list.
1540 if (IList->getInit(OldIndex) != DIE->getInit())
1541 DIE->setInit(IList->getInit(OldIndex));
1542 IList->setInit(OldIndex, DIE);
1544 return hadError && !prevHadError;
1547 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
1548 bool IsFirstDesignator = (DesigIdx == 0);
1550 assert((IsFirstDesignator || StructuredList) &&
1551 "Need a non-designated initializer list to start from");
1553 // Determine the structural initializer list that corresponds to the
1554 // current subobject.
1555 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1556 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1557 StructuredList, StructuredIndex,
1558 SourceRange(D->getStartLocation(),
1559 DIE->getSourceRange().getEnd()));
1560 assert(StructuredList && "Expected a structured initializer list");
1563 if (D->isFieldDesignator()) {
1566 // If a designator has the form
1570 // then the current object (defined below) shall have
1571 // structure or union type and the identifier shall be the
1572 // name of a member of that type.
1573 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
1575 SourceLocation Loc = D->getDotLoc();
1576 if (Loc.isInvalid())
1577 Loc = D->getFieldLoc();
1579 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1580 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
1585 // Note: we perform a linear search of the fields here, despite
1586 // the fact that we have a faster lookup method, because we always
1587 // need to compute the field's index.
1588 FieldDecl *KnownField = D->getField();
1589 IdentifierInfo *FieldName = D->getFieldName();
1590 unsigned FieldIndex = 0;
1591 RecordDecl::field_iterator
1592 Field = RT->getDecl()->field_begin(),
1593 FieldEnd = RT->getDecl()->field_end();
1594 for (; Field != FieldEnd; ++Field) {
1595 if (Field->isUnnamedBitfield())
1598 // If we find a field representing an anonymous field, look in the
1599 // IndirectFieldDecl that follow for the designated initializer.
1600 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1601 if (IndirectFieldDecl *IF =
1602 FindIndirectFieldDesignator(*Field, FieldName)) {
1603 // In verify mode, don't modify the original.
1605 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
1606 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1607 D = DIE->getDesignator(DesigIdx);
1611 if (KnownField && KnownField == *Field)
1613 if (FieldName && FieldName == Field->getIdentifier())
1619 if (Field == FieldEnd) {
1622 return true; // No typo correction when just trying this out.
1625 // There was no normal field in the struct with the designated
1626 // name. Perform another lookup for this name, which may find
1627 // something that we can't designate (e.g., a member function),
1628 // may find nothing, or may find a member of an anonymous
1630 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
1631 FieldDecl *ReplacementField = 0;
1632 if (Lookup.first == Lookup.second) {
1633 // Name lookup didn't find anything. Determine whether this
1634 // was a typo for another field name.
1635 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1636 Sema::LookupMemberName);
1637 TypoCorrection Corrected = SemaRef.CorrectTypo(
1638 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1639 Sema::LookupMemberName, /*Scope=*/NULL, /*SS=*/NULL,
1640 RT->getDecl(), false, Sema::CTC_NoKeywords);
1641 if ((ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>()) &&
1642 ReplacementField->getDeclContext()->getRedeclContext()
1643 ->Equals(RT->getDecl())) {
1644 std::string CorrectedStr(
1645 Corrected.getAsString(SemaRef.getLangOptions()));
1646 std::string CorrectedQuotedStr(
1647 Corrected.getQuoted(SemaRef.getLangOptions()));
1648 SemaRef.Diag(D->getFieldLoc(),
1649 diag::err_field_designator_unknown_suggest)
1650 << FieldName << CurrentObjectType << CorrectedQuotedStr
1651 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
1652 SemaRef.Diag(ReplacementField->getLocation(),
1653 diag::note_previous_decl) << CorrectedQuotedStr;
1656 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1657 << FieldName << CurrentObjectType;
1663 if (!ReplacementField) {
1664 // Name lookup found something, but it wasn't a field.
1665 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
1667 SemaRef.Diag((*Lookup.first)->getLocation(),
1668 diag::note_field_designator_found);
1674 // The replacement field comes from typo correction; find it
1675 // in the list of fields.
1677 Field = RT->getDecl()->field_begin();
1678 for (; Field != FieldEnd; ++Field) {
1679 if (Field->isUnnamedBitfield())
1682 if (ReplacementField == *Field ||
1683 Field->getIdentifier() == ReplacementField->getIdentifier())
1691 // All of the fields of a union are located at the same place in
1692 // the initializer list.
1693 if (RT->getDecl()->isUnion()) {
1696 StructuredList->setInitializedFieldInUnion(*Field);
1699 // Make sure we can use this declaration.
1702 InvalidUse = !SemaRef.CanUseDecl(*Field);
1704 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1711 // Update the designator with the field declaration.
1712 D->setField(*Field);
1714 // Make sure that our non-designated initializer list has space
1715 // for a subobject corresponding to this field.
1716 if (FieldIndex >= StructuredList->getNumInits())
1717 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1720 // This designator names a flexible array member.
1721 if (Field->getType()->isIncompleteArrayType()) {
1722 bool Invalid = false;
1723 if ((DesigIdx + 1) != DIE->size()) {
1724 // We can't designate an object within the flexible array
1725 // member (because GCC doesn't allow it).
1727 DesignatedInitExpr::Designator *NextD
1728 = DIE->getDesignator(DesigIdx + 1);
1729 SemaRef.Diag(NextD->getStartLocation(),
1730 diag::err_designator_into_flexible_array_member)
1731 << SourceRange(NextD->getStartLocation(),
1732 DIE->getSourceRange().getEnd());
1733 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1739 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1740 !isa<StringLiteral>(DIE->getInit())) {
1741 // The initializer is not an initializer list.
1743 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
1744 diag::err_flexible_array_init_needs_braces)
1745 << DIE->getInit()->getSourceRange();
1746 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1752 // Check GNU flexible array initializer.
1753 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1762 // Initialize the array.
1763 bool prevHadError = hadError;
1764 unsigned newStructuredIndex = FieldIndex;
1765 unsigned OldIndex = Index;
1766 IList->setInit(Index, DIE->getInit());
1768 InitializedEntity MemberEntity =
1769 InitializedEntity::InitializeMember(*Field, &Entity);
1770 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1771 StructuredList, newStructuredIndex);
1773 IList->setInit(OldIndex, DIE);
1774 if (hadError && !prevHadError) {
1779 StructuredIndex = FieldIndex;
1783 // Recurse to check later designated subobjects.
1784 QualType FieldType = (*Field)->getType();
1785 unsigned newStructuredIndex = FieldIndex;
1787 InitializedEntity MemberEntity =
1788 InitializedEntity::InitializeMember(*Field, &Entity);
1789 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1790 FieldType, 0, 0, Index,
1791 StructuredList, newStructuredIndex,
1796 // Find the position of the next field to be initialized in this
1801 // If this the first designator, our caller will continue checking
1802 // the rest of this struct/class/union subobject.
1803 if (IsFirstDesignator) {
1806 StructuredIndex = FieldIndex;
1810 if (!FinishSubobjectInit)
1813 // We've already initialized something in the union; we're done.
1814 if (RT->getDecl()->isUnion())
1817 // Check the remaining fields within this class/struct/union subobject.
1818 bool prevHadError = hadError;
1820 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
1821 StructuredList, FieldIndex);
1822 return hadError && !prevHadError;
1827 // If a designator has the form
1829 // [ constant-expression ]
1831 // then the current object (defined below) shall have array
1832 // type and the expression shall be an integer constant
1833 // expression. If the array is of unknown size, any
1834 // nonnegative value is valid.
1836 // Additionally, cope with the GNU extension that permits
1837 // designators of the form
1839 // [ constant-expression ... constant-expression ]
1840 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
1843 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1844 << CurrentObjectType;
1849 Expr *IndexExpr = 0;
1850 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1851 if (D->isArrayDesignator()) {
1852 IndexExpr = DIE->getArrayIndex(*D);
1853 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
1854 DesignatedEndIndex = DesignatedStartIndex;
1856 assert(D->isArrayRangeDesignator() && "Need array-range designator");
1858 DesignatedStartIndex =
1859 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
1860 DesignatedEndIndex =
1861 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
1862 IndexExpr = DIE->getArrayRangeEnd(*D);
1864 // Codegen can't handle evaluating array range designators that have side
1865 // effects, because we replicate the AST value for each initialized element.
1866 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1867 // elements with something that has a side effect, so codegen can emit an
1868 // "error unsupported" error instead of miscompiling the app.
1869 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
1870 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
1871 FullyStructuredList->sawArrayRangeDesignator();
1874 if (isa<ConstantArrayType>(AT)) {
1875 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
1876 DesignatedStartIndex
1877 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1878 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1880 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1881 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1882 if (DesignatedEndIndex >= MaxElements) {
1884 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
1885 diag::err_array_designator_too_large)
1886 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1887 << IndexExpr->getSourceRange();
1892 // Make sure the bit-widths and signedness match.
1893 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1895 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
1896 else if (DesignatedStartIndex.getBitWidth() <
1897 DesignatedEndIndex.getBitWidth())
1898 DesignatedStartIndex
1899 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1900 DesignatedStartIndex.setIsUnsigned(true);
1901 DesignatedEndIndex.setIsUnsigned(true);
1904 // Make sure that our non-designated initializer list has space
1905 // for a subobject corresponding to this array element.
1907 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
1908 StructuredList->resizeInits(SemaRef.Context,
1909 DesignatedEndIndex.getZExtValue() + 1);
1911 // Repeatedly perform subobject initializations in the range
1912 // [DesignatedStartIndex, DesignatedEndIndex].
1914 // Move to the next designator
1915 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1916 unsigned OldIndex = Index;
1918 InitializedEntity ElementEntity =
1919 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1921 while (DesignatedStartIndex <= DesignatedEndIndex) {
1922 // Recurse to check later designated subobjects.
1923 QualType ElementType = AT->getElementType();
1926 ElementEntity.setElementIndex(ElementIndex);
1927 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1928 ElementType, 0, 0, Index,
1929 StructuredList, ElementIndex,
1930 (DesignatedStartIndex == DesignatedEndIndex),
1934 // Move to the next index in the array that we'll be initializing.
1935 ++DesignatedStartIndex;
1936 ElementIndex = DesignatedStartIndex.getZExtValue();
1939 // If this the first designator, our caller will continue checking
1940 // the rest of this array subobject.
1941 if (IsFirstDesignator) {
1942 if (NextElementIndex)
1943 *NextElementIndex = DesignatedStartIndex;
1944 StructuredIndex = ElementIndex;
1948 if (!FinishSubobjectInit)
1951 // Check the remaining elements within this array subobject.
1952 bool prevHadError = hadError;
1953 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
1954 /*SubobjectIsDesignatorContext=*/false, Index,
1955 StructuredList, ElementIndex);
1956 return hadError && !prevHadError;
1959 // Get the structured initializer list for a subobject of type
1960 // @p CurrentObjectType.
1962 InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1963 QualType CurrentObjectType,
1964 InitListExpr *StructuredList,
1965 unsigned StructuredIndex,
1966 SourceRange InitRange) {
1968 return 0; // No structured list in verification-only mode.
1969 Expr *ExistingInit = 0;
1970 if (!StructuredList)
1971 ExistingInit = SyntacticToSemantic[IList];
1972 else if (StructuredIndex < StructuredList->getNumInits())
1973 ExistingInit = StructuredList->getInit(StructuredIndex);
1975 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1979 // We are creating an initializer list that initializes the
1980 // subobjects of the current object, but there was already an
1981 // initialization that completely initialized the current
1982 // subobject, e.g., by a compound literal:
1984 // struct X { int a, b; };
1985 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1987 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1988 // designated initializer re-initializes the whole
1989 // subobject [0], overwriting previous initializers.
1990 SemaRef.Diag(InitRange.getBegin(),
1991 diag::warn_subobject_initializer_overrides)
1993 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
1994 diag::note_previous_initializer)
1995 << /*FIXME:has side effects=*/0
1996 << ExistingInit->getSourceRange();
1999 InitListExpr *Result
2000 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2001 InitRange.getBegin(), 0, 0,
2002 InitRange.getEnd());
2004 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
2006 // Pre-allocate storage for the structured initializer list.
2007 unsigned NumElements = 0;
2008 unsigned NumInits = 0;
2009 bool GotNumInits = false;
2010 if (!StructuredList) {
2011 NumInits = IList->getNumInits();
2013 } else if (Index < IList->getNumInits()) {
2014 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
2015 NumInits = SubList->getNumInits();
2020 if (const ArrayType *AType
2021 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2022 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2023 NumElements = CAType->getSize().getZExtValue();
2024 // Simple heuristic so that we don't allocate a very large
2025 // initializer with many empty entries at the end.
2026 if (GotNumInits && NumElements > NumInits)
2029 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
2030 NumElements = VType->getNumElements();
2031 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
2032 RecordDecl *RDecl = RType->getDecl();
2033 if (RDecl->isUnion())
2036 NumElements = std::distance(RDecl->field_begin(),
2037 RDecl->field_end());
2040 Result->reserveInits(SemaRef.Context, NumElements);
2042 // Link this new initializer list into the structured initializer
2045 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
2047 Result->setSyntacticForm(IList);
2048 SyntacticToSemantic[IList] = Result;
2054 /// Update the initializer at index @p StructuredIndex within the
2055 /// structured initializer list to the value @p expr.
2056 void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2057 unsigned &StructuredIndex,
2059 // No structured initializer list to update
2060 if (!StructuredList)
2063 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2064 StructuredIndex, expr)) {
2065 // This initializer overwrites a previous initializer. Warn.
2066 SemaRef.Diag(expr->getSourceRange().getBegin(),
2067 diag::warn_initializer_overrides)
2068 << expr->getSourceRange();
2069 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
2070 diag::note_previous_initializer)
2071 << /*FIXME:has side effects=*/0
2072 << PrevInit->getSourceRange();
2078 /// Check that the given Index expression is a valid array designator
2079 /// value. This is essentailly just a wrapper around
2080 /// VerifyIntegerConstantExpression that also checks for negative values
2081 /// and produces a reasonable diagnostic if there is a
2082 /// failure. Returns true if there was an error, false otherwise. If
2083 /// everything went okay, Value will receive the value of the constant
2086 CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
2087 SourceLocation Loc = Index->getSourceRange().getBegin();
2089 // Make sure this is an integer constant expression.
2090 if (S.VerifyIntegerConstantExpression(Index, &Value))
2093 if (Value.isSigned() && Value.isNegative())
2094 return S.Diag(Loc, diag::err_array_designator_negative)
2095 << Value.toString(10) << Index->getSourceRange();
2097 Value.setIsUnsigned(true);
2101 ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
2105 typedef DesignatedInitExpr::Designator ASTDesignator;
2107 bool Invalid = false;
2108 SmallVector<ASTDesignator, 32> Designators;
2109 SmallVector<Expr *, 32> InitExpressions;
2111 // Build designators and check array designator expressions.
2112 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2113 const Designator &D = Desig.getDesignator(Idx);
2114 switch (D.getKind()) {
2115 case Designator::FieldDesignator:
2116 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
2120 case Designator::ArrayDesignator: {
2121 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2122 llvm::APSInt IndexValue;
2123 if (!Index->isTypeDependent() &&
2124 !Index->isValueDependent() &&
2125 CheckArrayDesignatorExpr(*this, Index, IndexValue))
2128 Designators.push_back(ASTDesignator(InitExpressions.size(),
2130 D.getRBracketLoc()));
2131 InitExpressions.push_back(Index);
2136 case Designator::ArrayRangeDesignator: {
2137 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2138 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2139 llvm::APSInt StartValue;
2140 llvm::APSInt EndValue;
2141 bool StartDependent = StartIndex->isTypeDependent() ||
2142 StartIndex->isValueDependent();
2143 bool EndDependent = EndIndex->isTypeDependent() ||
2144 EndIndex->isValueDependent();
2145 if ((!StartDependent &&
2146 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
2148 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
2151 // Make sure we're comparing values with the same bit width.
2152 if (StartDependent || EndDependent) {
2153 // Nothing to compute.
2154 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
2155 EndValue = EndValue.extend(StartValue.getBitWidth());
2156 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
2157 StartValue = StartValue.extend(EndValue.getBitWidth());
2159 if (!StartDependent && !EndDependent && EndValue < StartValue) {
2160 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
2161 << StartValue.toString(10) << EndValue.toString(10)
2162 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2165 Designators.push_back(ASTDesignator(InitExpressions.size(),
2168 D.getRBracketLoc()));
2169 InitExpressions.push_back(StartIndex);
2170 InitExpressions.push_back(EndIndex);
2178 if (Invalid || Init.isInvalid())
2181 // Clear out the expressions within the designation.
2182 Desig.ClearExprs(*this);
2184 DesignatedInitExpr *DIE
2185 = DesignatedInitExpr::Create(Context,
2186 Designators.data(), Designators.size(),
2187 InitExpressions.data(), InitExpressions.size(),
2188 Loc, GNUSyntax, Init.takeAs<Expr>());
2190 if (getLangOptions().CPlusPlus)
2191 Diag(DIE->getLocStart(), diag::ext_designated_init_cxx)
2192 << DIE->getSourceRange();
2193 else if (!getLangOptions().C99)
2194 Diag(DIE->getLocStart(), diag::ext_designated_init)
2195 << DIE->getSourceRange();
2200 //===----------------------------------------------------------------------===//
2201 // Initialization entity
2202 //===----------------------------------------------------------------------===//
2204 InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
2205 const InitializedEntity &Parent)
2206 : Parent(&Parent), Index(Index)
2208 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2209 Kind = EK_ArrayElement;
2210 Type = AT->getElementType();
2211 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
2212 Kind = EK_VectorElement;
2213 Type = VT->getElementType();
2215 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2216 assert(CT && "Unexpected type");
2217 Kind = EK_ComplexElement;
2218 Type = CT->getElementType();
2222 InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
2223 CXXBaseSpecifier *Base,
2224 bool IsInheritedVirtualBase)
2226 InitializedEntity Result;
2227 Result.Kind = EK_Base;
2228 Result.Base = reinterpret_cast<uintptr_t>(Base);
2229 if (IsInheritedVirtualBase)
2230 Result.Base |= 0x01;
2232 Result.Type = Base->getType();
2236 DeclarationName InitializedEntity::getName() const {
2237 switch (getKind()) {
2238 case EK_Parameter: {
2239 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2240 return (D ? D->getDeclName() : DeclarationName());
2245 return VariableOrMember->getDeclName();
2253 case EK_ArrayElement:
2254 case EK_VectorElement:
2255 case EK_ComplexElement:
2256 case EK_BlockElement:
2257 return DeclarationName();
2260 // Silence GCC warning
2261 return DeclarationName();
2264 DeclaratorDecl *InitializedEntity::getDecl() const {
2265 switch (getKind()) {
2268 return VariableOrMember;
2271 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2279 case EK_ArrayElement:
2280 case EK_VectorElement:
2281 case EK_ComplexElement:
2282 case EK_BlockElement:
2286 // Silence GCC warning
2290 bool InitializedEntity::allowsNRVO() const {
2291 switch (getKind()) {
2294 return LocAndNRVO.NRVO;
2303 case EK_ArrayElement:
2304 case EK_VectorElement:
2305 case EK_ComplexElement:
2306 case EK_BlockElement:
2313 //===----------------------------------------------------------------------===//
2314 // Initialization sequence
2315 //===----------------------------------------------------------------------===//
2317 void InitializationSequence::Step::Destroy() {
2319 case SK_ResolveAddressOfOverloadedFunction:
2320 case SK_CastDerivedToBaseRValue:
2321 case SK_CastDerivedToBaseXValue:
2322 case SK_CastDerivedToBaseLValue:
2323 case SK_BindReference:
2324 case SK_BindReferenceToTemporary:
2325 case SK_ExtraneousCopyToTemporary:
2326 case SK_UserConversion:
2327 case SK_QualificationConversionRValue:
2328 case SK_QualificationConversionXValue:
2329 case SK_QualificationConversionLValue:
2330 case SK_ListInitialization:
2331 case SK_ListConstructorCall:
2332 case SK_ConstructorInitialization:
2333 case SK_ZeroInitialization:
2334 case SK_CAssignment:
2336 case SK_ObjCObjectConversion:
2338 case SK_PassByIndirectCopyRestore:
2339 case SK_PassByIndirectRestore:
2340 case SK_ProduceObjCObject:
2343 case SK_ConversionSequence:
2348 bool InitializationSequence::isDirectReferenceBinding() const {
2349 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
2352 bool InitializationSequence::isAmbiguous() const {
2356 switch (getFailureKind()) {
2357 case FK_TooManyInitsForReference:
2358 case FK_ArrayNeedsInitList:
2359 case FK_ArrayNeedsInitListOrStringLiteral:
2360 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2361 case FK_NonConstLValueReferenceBindingToTemporary:
2362 case FK_NonConstLValueReferenceBindingToUnrelated:
2363 case FK_RValueReferenceBindingToLValue:
2364 case FK_ReferenceInitDropsQualifiers:
2365 case FK_ReferenceInitFailed:
2366 case FK_ConversionFailed:
2367 case FK_ConversionFromPropertyFailed:
2368 case FK_TooManyInitsForScalar:
2369 case FK_ReferenceBindingToInitList:
2370 case FK_InitListBadDestinationType:
2371 case FK_DefaultInitOfConst:
2373 case FK_ArrayTypeMismatch:
2374 case FK_NonConstantArrayInit:
2375 case FK_ListInitializationFailed:
2378 case FK_ReferenceInitOverloadFailed:
2379 case FK_UserConversionOverloadFailed:
2380 case FK_ConstructorOverloadFailed:
2381 return FailedOverloadResult == OR_Ambiguous;
2387 bool InitializationSequence::isConstructorInitialization() const {
2388 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2391 bool InitializationSequence::endsWithNarrowing(ASTContext &Ctx,
2392 const Expr *Initializer,
2393 bool *isInitializerConstant,
2394 APValue *ConstantValue) const {
2395 if (Steps.empty() || Initializer->isValueDependent())
2398 const Step &LastStep = Steps.back();
2399 if (LastStep.Kind != SK_ConversionSequence)
2402 const ImplicitConversionSequence &ICS = *LastStep.ICS;
2403 const StandardConversionSequence *SCS = NULL;
2404 switch (ICS.getKind()) {
2405 case ImplicitConversionSequence::StandardConversion:
2406 SCS = &ICS.Standard;
2408 case ImplicitConversionSequence::UserDefinedConversion:
2409 SCS = &ICS.UserDefined.After;
2411 case ImplicitConversionSequence::AmbiguousConversion:
2412 case ImplicitConversionSequence::EllipsisConversion:
2413 case ImplicitConversionSequence::BadConversion:
2417 // Check if SCS represents a narrowing conversion, according to C++0x
2418 // [dcl.init.list]p7:
2420 // A narrowing conversion is an implicit conversion ...
2421 ImplicitConversionKind PossibleNarrowing = SCS->Second;
2422 QualType FromType = SCS->getToType(0);
2423 QualType ToType = SCS->getToType(1);
2424 switch (PossibleNarrowing) {
2425 // * from a floating-point type to an integer type, or
2427 // * from an integer type or unscoped enumeration type to a floating-point
2428 // type, except where the source is a constant expression and the actual
2429 // value after conversion will fit into the target type and will produce
2430 // the original value when converted back to the original type, or
2431 case ICK_Floating_Integral:
2432 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
2433 *isInitializerConstant = false;
2435 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
2436 llvm::APSInt IntConstantValue;
2438 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
2439 // Convert the integer to the floating type.
2440 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
2441 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
2442 llvm::APFloat::rmNearestTiesToEven);
2444 llvm::APSInt ConvertedValue = IntConstantValue;
2446 Result.convertToInteger(ConvertedValue,
2447 llvm::APFloat::rmTowardZero, &ignored);
2448 // If the resulting value is different, this was a narrowing conversion.
2449 if (IntConstantValue != ConvertedValue) {
2450 *isInitializerConstant = true;
2451 *ConstantValue = APValue(IntConstantValue);
2455 // Variables are always narrowings.
2456 *isInitializerConstant = false;
2462 // * from long double to double or float, or from double to float, except
2463 // where the source is a constant expression and the actual value after
2464 // conversion is within the range of values that can be represented (even
2465 // if it cannot be represented exactly), or
2466 case ICK_Floating_Conversion:
2467 if (1 == Ctx.getFloatingTypeOrder(FromType, ToType)) {
2468 // FromType is larger than ToType.
2469 Expr::EvalResult InitializerValue;
2470 // FIXME: Check whether Initializer is a constant expression according
2471 // to C++0x [expr.const], rather than just whether it can be folded.
2472 if (Initializer->Evaluate(InitializerValue, Ctx) &&
2473 !InitializerValue.HasSideEffects && InitializerValue.Val.isFloat()) {
2474 // Constant! (Except for FIXME above.)
2475 llvm::APFloat FloatVal = InitializerValue.Val.getFloat();
2476 // Convert the source value into the target type.
2478 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
2479 Ctx.getFloatTypeSemantics(ToType),
2480 llvm::APFloat::rmNearestTiesToEven, &ignored);
2481 // If there was no overflow, the source value is within the range of
2482 // values that can be represented.
2483 if (ConvertStatus & llvm::APFloat::opOverflow) {
2484 *isInitializerConstant = true;
2485 *ConstantValue = InitializerValue.Val;
2489 *isInitializerConstant = false;
2495 // * from an integer type or unscoped enumeration type to an integer type
2496 // that cannot represent all the values of the original type, except where
2497 // the source is a constant expression and the actual value after
2498 // conversion will fit into the target type and will produce the original
2499 // value when converted back to the original type.
2500 case ICK_Boolean_Conversion: // Bools are integers too.
2501 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
2502 // Boolean conversions can be from pointers and pointers to members
2503 // [conv.bool], and those aren't considered narrowing conversions.
2505 } // Otherwise, fall through to the integral case.
2506 case ICK_Integral_Conversion: {
2507 assert(FromType->isIntegralOrUnscopedEnumerationType());
2508 assert(ToType->isIntegralOrUnscopedEnumerationType());
2509 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
2510 const unsigned FromWidth = Ctx.getIntWidth(FromType);
2511 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
2512 const unsigned ToWidth = Ctx.getIntWidth(ToType);
2514 if (FromWidth > ToWidth ||
2515 (FromWidth == ToWidth && FromSigned != ToSigned)) {
2516 // Not all values of FromType can be represented in ToType.
2517 llvm::APSInt InitializerValue;
2518 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
2519 *isInitializerConstant = true;
2520 *ConstantValue = APValue(InitializerValue);
2522 // Add a bit to the InitializerValue so we don't have to worry about
2523 // signed vs. unsigned comparisons.
2524 InitializerValue = InitializerValue.extend(
2525 InitializerValue.getBitWidth() + 1);
2526 // Convert the initializer to and from the target width and signed-ness.
2527 llvm::APSInt ConvertedValue = InitializerValue;
2528 ConvertedValue = ConvertedValue.trunc(ToWidth);
2529 ConvertedValue.setIsSigned(ToSigned);
2530 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
2531 ConvertedValue.setIsSigned(InitializerValue.isSigned());
2532 // If the result is different, this was a narrowing conversion.
2533 return ConvertedValue != InitializerValue;
2535 // Variables are always narrowings.
2536 *isInitializerConstant = false;
2544 // Other kinds of conversions are not narrowings.
2549 void InitializationSequence::AddAddressOverloadResolutionStep(
2550 FunctionDecl *Function,
2551 DeclAccessPair Found) {
2553 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2554 S.Type = Function->getType();
2555 S.Function.HadMultipleCandidates = false;
2556 S.Function.Function = Function;
2557 S.Function.FoundDecl = Found;
2561 void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2565 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2566 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2567 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
2568 default: llvm_unreachable("No such category");
2574 void InitializationSequence::AddReferenceBindingStep(QualType T,
2575 bool BindingTemporary) {
2577 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2582 void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2584 S.Kind = SK_ExtraneousCopyToTemporary;
2589 void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2590 DeclAccessPair FoundDecl,
2593 S.Kind = SK_UserConversion;
2595 S.Function.HadMultipleCandidates = false;
2596 S.Function.Function = Function;
2597 S.Function.FoundDecl = FoundDecl;
2601 void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2604 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
2607 S.Kind = SK_QualificationConversionRValue;
2610 S.Kind = SK_QualificationConversionXValue;
2613 S.Kind = SK_QualificationConversionLValue;
2620 void InitializationSequence::AddConversionSequenceStep(
2621 const ImplicitConversionSequence &ICS,
2624 S.Kind = SK_ConversionSequence;
2626 S.ICS = new ImplicitConversionSequence(ICS);
2630 void InitializationSequence::AddListInitializationStep(QualType T) {
2632 S.Kind = SK_ListInitialization;
2638 InitializationSequence::AddConstructorInitializationStep(
2639 CXXConstructorDecl *Constructor,
2640 AccessSpecifier Access,
2643 S.Kind = SK_ConstructorInitialization;
2645 S.Function.HadMultipleCandidates = false;
2646 S.Function.Function = Constructor;
2647 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
2651 void InitializationSequence::AddZeroInitializationStep(QualType T) {
2653 S.Kind = SK_ZeroInitialization;
2658 void InitializationSequence::AddCAssignmentStep(QualType T) {
2660 S.Kind = SK_CAssignment;
2665 void InitializationSequence::AddStringInitStep(QualType T) {
2667 S.Kind = SK_StringInit;
2672 void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2674 S.Kind = SK_ObjCObjectConversion;
2679 void InitializationSequence::AddArrayInitStep(QualType T) {
2681 S.Kind = SK_ArrayInit;
2686 void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2689 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2690 : SK_PassByIndirectRestore);
2695 void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2697 S.Kind = SK_ProduceObjCObject;
2702 void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2703 OverloadingResult Result) {
2704 setSequenceKind(FailedSequence);
2705 this->Failure = Failure;
2706 this->FailedOverloadResult = Result;
2709 //===----------------------------------------------------------------------===//
2710 // Attempt initialization
2711 //===----------------------------------------------------------------------===//
2713 static void MaybeProduceObjCObject(Sema &S,
2714 InitializationSequence &Sequence,
2715 const InitializedEntity &Entity) {
2716 if (!S.getLangOptions().ObjCAutoRefCount) return;
2718 /// When initializing a parameter, produce the value if it's marked
2719 /// __attribute__((ns_consumed)).
2720 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2721 if (!Entity.isParameterConsumed())
2724 assert(Entity.getType()->isObjCRetainableType() &&
2725 "consuming an object of unretainable type?");
2726 Sequence.AddProduceObjCObjectStep(Entity.getType());
2728 /// When initializing a return value, if the return type is a
2729 /// retainable type, then returns need to immediately retain the
2730 /// object. If an autorelease is required, it will be done at the
2732 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2733 if (!Entity.getType()->isObjCRetainableType())
2736 Sequence.AddProduceObjCObjectStep(Entity.getType());
2740 /// \brief Attempt list initialization (C++0x [dcl.init.list])
2741 static void TryListInitialization(Sema &S,
2742 const InitializedEntity &Entity,
2743 const InitializationKind &Kind,
2744 InitListExpr *InitList,
2745 InitializationSequence &Sequence) {
2746 QualType DestType = Entity.getType();
2748 // C++ doesn't allow scalar initialization with more than one argument.
2749 // But C99 complex numbers are scalars and it makes sense there.
2750 if (S.getLangOptions().CPlusPlus && DestType->isScalarType() &&
2751 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
2752 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2755 // FIXME: C++0x defines behavior for these two cases.
2756 if (DestType->isReferenceType()) {
2757 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2760 if (DestType->isRecordType() && !DestType->isAggregateType()) {
2761 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2765 InitListChecker CheckInitList(S, Entity, InitList,
2766 DestType, /*VerifyOnly=*/true);
2767 if (CheckInitList.HadError()) {
2768 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
2772 // Add the list initialization step with the built init list.
2773 Sequence.AddListInitializationStep(DestType);
2776 /// \brief Try a reference initialization that involves calling a conversion
2778 static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2779 const InitializedEntity &Entity,
2780 const InitializationKind &Kind,
2783 InitializationSequence &Sequence) {
2784 QualType DestType = Entity.getType();
2785 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2786 QualType T1 = cv1T1.getUnqualifiedType();
2787 QualType cv2T2 = Initializer->getType();
2788 QualType T2 = cv2T2.getUnqualifiedType();
2791 bool ObjCConversion;
2792 bool ObjCLifetimeConversion;
2793 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2794 T1, T2, DerivedToBase,
2796 ObjCLifetimeConversion) &&
2797 "Must have incompatible references when binding via conversion");
2798 (void)DerivedToBase;
2799 (void)ObjCConversion;
2800 (void)ObjCLifetimeConversion;
2802 // Build the candidate set directly in the initialization sequence
2803 // structure, so that it will persist if we fail.
2804 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2805 CandidateSet.clear();
2807 // Determine whether we are allowed to call explicit constructors or
2808 // explicit conversion operators.
2809 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2811 const RecordType *T1RecordType = 0;
2812 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2813 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
2814 // The type we're converting to is a class type. Enumerate its constructors
2815 // to see if there is a suitable conversion.
2816 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2818 DeclContext::lookup_iterator Con, ConEnd;
2819 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
2820 Con != ConEnd; ++Con) {
2821 NamedDecl *D = *Con;
2822 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2824 // Find the constructor (which may be a template).
2825 CXXConstructorDecl *Constructor = 0;
2826 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2827 if (ConstructorTmpl)
2828 Constructor = cast<CXXConstructorDecl>(
2829 ConstructorTmpl->getTemplatedDecl());
2831 Constructor = cast<CXXConstructorDecl>(D);
2833 if (!Constructor->isInvalidDecl() &&
2834 Constructor->isConvertingConstructor(AllowExplicit)) {
2835 if (ConstructorTmpl)
2836 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2838 &Initializer, 1, CandidateSet,
2839 /*SuppressUserConversions=*/true);
2841 S.AddOverloadCandidate(Constructor, FoundDecl,
2842 &Initializer, 1, CandidateSet,
2843 /*SuppressUserConversions=*/true);
2847 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2848 return OR_No_Viable_Function;
2850 const RecordType *T2RecordType = 0;
2851 if ((T2RecordType = T2->getAs<RecordType>()) &&
2852 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
2853 // The type we're converting from is a class type, enumerate its conversion
2855 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2857 const UnresolvedSetImpl *Conversions
2858 = T2RecordDecl->getVisibleConversionFunctions();
2859 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2860 E = Conversions->end(); I != E; ++I) {
2862 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2863 if (isa<UsingShadowDecl>(D))
2864 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2866 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2867 CXXConversionDecl *Conv;
2869 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2871 Conv = cast<CXXConversionDecl>(D);
2873 // If the conversion function doesn't return a reference type,
2874 // it can't be considered for this conversion unless we're allowed to
2875 // consider rvalues.
2876 // FIXME: Do we need to make sure that we only consider conversion
2877 // candidates with reference-compatible results? That might be needed to
2879 if ((AllowExplicit || !Conv->isExplicit()) &&
2880 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2882 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
2883 ActingDC, Initializer,
2884 DestType, CandidateSet);
2886 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
2887 Initializer, DestType, CandidateSet);
2891 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2892 return OR_No_Viable_Function;
2894 SourceLocation DeclLoc = Initializer->getLocStart();
2896 // Perform overload resolution. If it fails, return the failed result.
2897 OverloadCandidateSet::iterator Best;
2898 if (OverloadingResult Result
2899 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
2902 FunctionDecl *Function = Best->Function;
2904 // This is the overload that will actually be used for the initialization, so
2906 S.MarkDeclarationReferenced(DeclLoc, Function);
2908 // Compute the returned type of the conversion.
2909 if (isa<CXXConversionDecl>(Function))
2910 T2 = Function->getResultType();
2914 // Add the user-defined conversion step.
2915 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
2916 T2.getNonLValueExprType(S.Context));
2918 // Determine whether we need to perform derived-to-base or
2919 // cv-qualification adjustments.
2920 ExprValueKind VK = VK_RValue;
2921 if (T2->isLValueReferenceType())
2923 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
2924 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
2926 bool NewDerivedToBase = false;
2927 bool NewObjCConversion = false;
2928 bool NewObjCLifetimeConversion = false;
2929 Sema::ReferenceCompareResult NewRefRelationship
2930 = S.CompareReferenceRelationship(DeclLoc, T1,
2931 T2.getNonLValueExprType(S.Context),
2932 NewDerivedToBase, NewObjCConversion,
2933 NewObjCLifetimeConversion);
2934 if (NewRefRelationship == Sema::Ref_Incompatible) {
2935 // If the type we've converted to is not reference-related to the
2936 // type we're looking for, then there is another conversion step
2937 // we need to perform to produce a temporary of the right type
2938 // that we'll be binding to.
2939 ImplicitConversionSequence ICS;
2941 ICS.Standard = Best->FinalConversion;
2942 T2 = ICS.Standard.getToType(2);
2943 Sequence.AddConversionSequenceStep(ICS, T2);
2944 } else if (NewDerivedToBase)
2945 Sequence.AddDerivedToBaseCastStep(
2946 S.Context.getQualifiedType(T1,
2947 T2.getNonReferenceType().getQualifiers()),
2949 else if (NewObjCConversion)
2950 Sequence.AddObjCObjectConversionStep(
2951 S.Context.getQualifiedType(T1,
2952 T2.getNonReferenceType().getQualifiers()));
2954 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2955 Sequence.AddQualificationConversionStep(cv1T1, VK);
2957 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2961 /// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2962 static void TryReferenceInitialization(Sema &S,
2963 const InitializedEntity &Entity,
2964 const InitializationKind &Kind,
2966 InitializationSequence &Sequence) {
2967 QualType DestType = Entity.getType();
2968 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2970 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
2971 QualType cv2T2 = Initializer->getType();
2973 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
2974 SourceLocation DeclLoc = Initializer->getLocStart();
2976 // If the initializer is the address of an overloaded function, try
2977 // to resolve the overloaded function. If all goes well, T2 is the
2978 // type of the resulting function.
2979 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2980 DeclAccessPair Found;
2981 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2985 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2986 cv2T2 = Fn->getType();
2987 T2 = cv2T2.getUnqualifiedType();
2988 } else if (!T1->isRecordType()) {
2989 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2994 // Compute some basic properties of the types and the initializer.
2995 bool isLValueRef = DestType->isLValueReferenceType();
2996 bool isRValueRef = !isLValueRef;
2997 bool DerivedToBase = false;
2998 bool ObjCConversion = false;
2999 bool ObjCLifetimeConversion = false;
3000 Expr::Classification InitCategory = Initializer->Classify(S.Context);
3001 Sema::ReferenceCompareResult RefRelationship
3002 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
3003 ObjCConversion, ObjCLifetimeConversion);
3005 // C++0x [dcl.init.ref]p5:
3006 // A reference to type "cv1 T1" is initialized by an expression of type
3007 // "cv2 T2" as follows:
3009 // - If the reference is an lvalue reference and the initializer
3011 // Note the analogous bullet points for rvlaue refs to functions. Because
3012 // there are no function rvalues in C++, rvalue refs to functions are treated
3013 // like lvalue refs.
3014 OverloadingResult ConvOvlResult = OR_Success;
3015 bool T1Function = T1->isFunctionType();
3016 if (isLValueRef || T1Function) {
3017 if (InitCategory.isLValue() &&
3018 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
3019 (Kind.isCStyleOrFunctionalCast() &&
3020 RefRelationship == Sema::Ref_Related))) {
3021 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
3022 // reference-compatible with "cv2 T2," or
3024 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
3025 // bit-field when we're determining whether the reference initialization
3026 // can occur. However, we do pay attention to whether it is a bit-field
3027 // to decide whether we're actually binding to a temporary created from
3030 Sequence.AddDerivedToBaseCastStep(
3031 S.Context.getQualifiedType(T1, T2Quals),
3033 else if (ObjCConversion)
3034 Sequence.AddObjCObjectConversionStep(
3035 S.Context.getQualifiedType(T1, T2Quals));
3037 if (T1Quals != T2Quals)
3038 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
3039 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
3040 (Initializer->getBitField() || Initializer->refersToVectorElement());
3041 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
3045 // - has a class type (i.e., T2 is a class type), where T1 is not
3046 // reference-related to T2, and can be implicitly converted to an
3047 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3048 // with "cv3 T3" (this conversion is selected by enumerating the
3049 // applicable conversion functions (13.3.1.6) and choosing the best
3050 // one through overload resolution (13.3)),
3051 // If we have an rvalue ref to function type here, the rhs must be
3053 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3054 (isLValueRef || InitCategory.isRValue())) {
3055 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
3057 /*AllowRValues=*/isRValueRef,
3059 if (ConvOvlResult == OR_Success)
3061 if (ConvOvlResult != OR_No_Viable_Function) {
3062 Sequence.SetOverloadFailure(
3063 InitializationSequence::FK_ReferenceInitOverloadFailed,
3069 // - Otherwise, the reference shall be an lvalue reference to a
3070 // non-volatile const type (i.e., cv1 shall be const), or the reference
3071 // shall be an rvalue reference.
3072 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
3073 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3074 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3075 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3076 Sequence.SetOverloadFailure(
3077 InitializationSequence::FK_ReferenceInitOverloadFailed,
3080 Sequence.SetFailed(InitCategory.isLValue()
3081 ? (RefRelationship == Sema::Ref_Related
3082 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3083 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3084 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3089 // - If the initializer expression
3090 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3091 // "cv1 T1" is reference-compatible with "cv2 T2"
3092 // Note: functions are handled below.
3094 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
3095 (Kind.isCStyleOrFunctionalCast() &&
3096 RefRelationship == Sema::Ref_Related)) &&
3097 (InitCategory.isXValue() ||
3098 (InitCategory.isPRValue() && T2->isRecordType()) ||
3099 (InitCategory.isPRValue() && T2->isArrayType()))) {
3100 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3101 if (InitCategory.isPRValue() && T2->isRecordType()) {
3102 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3103 // compiler the freedom to perform a copy here or bind to the
3104 // object, while C++0x requires that we bind directly to the
3105 // object. Hence, we always bind to the object without making an
3106 // extra copy. However, in C++03 requires that we check for the
3107 // presence of a suitable copy constructor:
3109 // The constructor that would be used to make the copy shall
3110 // be callable whether or not the copy is actually done.
3111 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
3112 Sequence.AddExtraneousCopyToTemporary(cv2T2);
3116 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3118 else if (ObjCConversion)
3119 Sequence.AddObjCObjectConversionStep(
3120 S.Context.getQualifiedType(T1, T2Quals));
3122 if (T1Quals != T2Quals)
3123 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
3124 Sequence.AddReferenceBindingStep(cv1T1,
3125 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
3129 // - has a class type (i.e., T2 is a class type), where T1 is not
3130 // reference-related to T2, and can be implicitly converted to an
3131 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3132 // where "cv1 T1" is reference-compatible with "cv3 T3",
3133 if (T2->isRecordType()) {
3134 if (RefRelationship == Sema::Ref_Incompatible) {
3135 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3137 /*AllowRValues=*/true,
3140 Sequence.SetOverloadFailure(
3141 InitializationSequence::FK_ReferenceInitOverloadFailed,
3147 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3151 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
3152 // from the initializer expression using the rules for a non-reference
3153 // copy initialization (8.5). The reference is then bound to the
3156 // Determine whether we are allowed to call explicit constructors or
3157 // explicit conversion operators.
3158 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
3160 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3162 ImplicitConversionSequence ICS
3163 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
3164 /*SuppressUserConversions*/ false,
3166 /*FIXME:InOverloadResolution=*/false,
3167 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3168 /*AllowObjCWritebackConversion=*/false);
3171 // FIXME: Use the conversion function set stored in ICS to turn
3172 // this into an overloading ambiguity diagnostic. However, we need
3173 // to keep that set as an OverloadCandidateSet rather than as some
3174 // other kind of set.
3175 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3176 Sequence.SetOverloadFailure(
3177 InitializationSequence::FK_ReferenceInitOverloadFailed,
3179 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3180 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3182 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
3185 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
3188 // [...] If T1 is reference-related to T2, cv1 must be the
3189 // same cv-qualification as, or greater cv-qualification
3190 // than, cv2; otherwise, the program is ill-formed.
3191 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3192 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
3193 if (RefRelationship == Sema::Ref_Related &&
3194 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
3195 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3199 // [...] If T1 is reference-related to T2 and the reference is an rvalue
3200 // reference, the initializer expression shall not be an lvalue.
3201 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
3202 InitCategory.isLValue()) {
3204 InitializationSequence::FK_RValueReferenceBindingToLValue);
3208 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3212 /// \brief Attempt character array initialization from a string literal
3213 /// (C++ [dcl.init.string], C99 6.7.8).
3214 static void TryStringLiteralInitialization(Sema &S,
3215 const InitializedEntity &Entity,
3216 const InitializationKind &Kind,
3218 InitializationSequence &Sequence) {
3219 Sequence.AddStringInitStep(Entity.getType());
3222 /// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3223 /// enumerates the constructors of the initialized entity and performs overload
3224 /// resolution to select the best.
3225 static void TryConstructorInitialization(Sema &S,
3226 const InitializedEntity &Entity,
3227 const InitializationKind &Kind,
3228 Expr **Args, unsigned NumArgs,
3230 InitializationSequence &Sequence) {
3231 // Check constructor arguments for self reference.
3232 if (DeclaratorDecl *DD = Entity.getDecl())
3233 // Parameters arguments are occassionially constructed with itself,
3234 // for instance, in recursive functions. Skip them.
3235 if (!isa<ParmVarDecl>(DD))
3236 for (unsigned i = 0; i < NumArgs; ++i)
3237 S.CheckSelfReference(DD, Args[i]);
3239 // Build the candidate set directly in the initialization sequence
3240 // structure, so that it will persist if we fail.
3241 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3242 CandidateSet.clear();
3244 // Determine whether we are allowed to call explicit constructors or
3245 // explicit conversion operators.
3246 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
3247 Kind.getKind() == InitializationKind::IK_Value ||
3248 Kind.getKind() == InitializationKind::IK_Default);
3250 // The type we're constructing needs to be complete.
3251 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
3252 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
3256 // The type we're converting to is a class type. Enumerate its constructors
3257 // to see if one is suitable.
3258 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3259 assert(DestRecordType && "Constructor initialization requires record type");
3260 CXXRecordDecl *DestRecordDecl
3261 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3263 DeclContext::lookup_iterator Con, ConEnd;
3264 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
3265 Con != ConEnd; ++Con) {
3266 NamedDecl *D = *Con;
3267 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3268 bool SuppressUserConversions = false;
3270 // Find the constructor (which may be a template).
3271 CXXConstructorDecl *Constructor = 0;
3272 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3273 if (ConstructorTmpl)
3274 Constructor = cast<CXXConstructorDecl>(
3275 ConstructorTmpl->getTemplatedDecl());
3277 Constructor = cast<CXXConstructorDecl>(D);
3279 // If we're performing copy initialization using a copy constructor, we
3280 // suppress user-defined conversions on the arguments.
3281 // FIXME: Move constructors?
3282 if (Kind.getKind() == InitializationKind::IK_Copy &&
3283 Constructor->isCopyConstructor())
3284 SuppressUserConversions = true;
3287 if (!Constructor->isInvalidDecl() &&
3288 (AllowExplicit || !Constructor->isExplicit())) {
3289 if (ConstructorTmpl)
3290 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3292 Args, NumArgs, CandidateSet,
3293 SuppressUserConversions);
3295 S.AddOverloadCandidate(Constructor, FoundDecl,
3296 Args, NumArgs, CandidateSet,
3297 SuppressUserConversions);
3301 SourceLocation DeclLoc = Kind.getLocation();
3303 // Perform overload resolution. If it fails, return the failed result.
3304 OverloadCandidateSet::iterator Best;
3305 if (OverloadingResult Result
3306 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
3307 Sequence.SetOverloadFailure(
3308 InitializationSequence::FK_ConstructorOverloadFailed,
3313 // C++0x [dcl.init]p6:
3314 // If a program calls for the default initialization of an object
3315 // of a const-qualified type T, T shall be a class type with a
3316 // user-provided default constructor.
3317 if (Kind.getKind() == InitializationKind::IK_Default &&
3318 Entity.getType().isConstQualified() &&
3319 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
3320 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3324 // Add the constructor initialization step. Any cv-qualification conversion is
3325 // subsumed by the initialization.
3326 Sequence.AddConstructorInitializationStep(
3327 cast<CXXConstructorDecl>(Best->Function),
3328 Best->FoundDecl.getAccess(),
3332 /// \brief Attempt value initialization (C++ [dcl.init]p7).
3333 static void TryValueInitialization(Sema &S,
3334 const InitializedEntity &Entity,
3335 const InitializationKind &Kind,
3336 InitializationSequence &Sequence) {
3337 // C++ [dcl.init]p5:
3339 // To value-initialize an object of type T means:
3340 QualType T = Entity.getType();
3342 // -- if T is an array type, then each element is value-initialized;
3343 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3344 T = AT->getElementType();
3346 if (const RecordType *RT = T->getAs<RecordType>()) {
3347 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3348 // -- if T is a class type (clause 9) with a user-declared
3349 // constructor (12.1), then the default constructor for T is
3350 // called (and the initialization is ill-formed if T has no
3351 // accessible default constructor);
3353 // FIXME: we really want to refer to a single subobject of the array,
3354 // but Entity doesn't have a way to capture that (yet).
3355 if (ClassDecl->hasUserDeclaredConstructor())
3356 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
3358 // -- if T is a (possibly cv-qualified) non-union class type
3359 // without a user-provided constructor, then the object is
3360 // zero-initialized and, if T's implicitly-declared default
3361 // constructor is non-trivial, that constructor is called.
3362 if ((ClassDecl->getTagKind() == TTK_Class ||
3363 ClassDecl->getTagKind() == TTK_Struct)) {
3364 Sequence.AddZeroInitializationStep(Entity.getType());
3365 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
3370 Sequence.AddZeroInitializationStep(Entity.getType());
3373 /// \brief Attempt default initialization (C++ [dcl.init]p6).
3374 static void TryDefaultInitialization(Sema &S,
3375 const InitializedEntity &Entity,
3376 const InitializationKind &Kind,
3377 InitializationSequence &Sequence) {
3378 assert(Kind.getKind() == InitializationKind::IK_Default);
3380 // C++ [dcl.init]p6:
3381 // To default-initialize an object of type T means:
3382 // - if T is an array type, each element is default-initialized;
3383 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3385 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3386 // constructor for T is called (and the initialization is ill-formed if
3387 // T has no accessible default constructor);
3388 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
3389 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3393 // - otherwise, no initialization is performed.
3395 // If a program calls for the default initialization of an object of
3396 // a const-qualified type T, T shall be a class type with a user-provided
3397 // default constructor.
3398 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
3399 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3403 // If the destination type has a lifetime property, zero-initialize it.
3404 if (DestType.getQualifiers().hasObjCLifetime()) {
3405 Sequence.AddZeroInitializationStep(Entity.getType());
3410 /// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3411 /// which enumerates all conversion functions and performs overload resolution
3412 /// to select the best.
3413 static void TryUserDefinedConversion(Sema &S,
3414 const InitializedEntity &Entity,
3415 const InitializationKind &Kind,
3417 InitializationSequence &Sequence) {
3418 QualType DestType = Entity.getType();
3419 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3420 QualType SourceType = Initializer->getType();
3421 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3422 "Must have a class type to perform a user-defined conversion");
3424 // Build the candidate set directly in the initialization sequence
3425 // structure, so that it will persist if we fail.
3426 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3427 CandidateSet.clear();
3429 // Determine whether we are allowed to call explicit constructors or
3430 // explicit conversion operators.
3431 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
3433 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3434 // The type we're converting to is a class type. Enumerate its constructors
3435 // to see if there is a suitable conversion.
3436 CXXRecordDecl *DestRecordDecl
3437 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3439 // Try to complete the type we're converting to.
3440 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
3441 DeclContext::lookup_iterator Con, ConEnd;
3442 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
3443 Con != ConEnd; ++Con) {
3444 NamedDecl *D = *Con;
3445 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3447 // Find the constructor (which may be a template).
3448 CXXConstructorDecl *Constructor = 0;
3449 FunctionTemplateDecl *ConstructorTmpl
3450 = dyn_cast<FunctionTemplateDecl>(D);
3451 if (ConstructorTmpl)
3452 Constructor = cast<CXXConstructorDecl>(
3453 ConstructorTmpl->getTemplatedDecl());
3455 Constructor = cast<CXXConstructorDecl>(D);
3457 if (!Constructor->isInvalidDecl() &&
3458 Constructor->isConvertingConstructor(AllowExplicit)) {
3459 if (ConstructorTmpl)
3460 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3462 &Initializer, 1, CandidateSet,
3463 /*SuppressUserConversions=*/true);
3465 S.AddOverloadCandidate(Constructor, FoundDecl,
3466 &Initializer, 1, CandidateSet,
3467 /*SuppressUserConversions=*/true);
3473 SourceLocation DeclLoc = Initializer->getLocStart();
3475 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3476 // The type we're converting from is a class type, enumerate its conversion
3479 // We can only enumerate the conversion functions for a complete type; if
3480 // the type isn't complete, simply skip this step.
3481 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3482 CXXRecordDecl *SourceRecordDecl
3483 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
3485 const UnresolvedSetImpl *Conversions
3486 = SourceRecordDecl->getVisibleConversionFunctions();
3487 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
3488 E = Conversions->end();
3491 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3492 if (isa<UsingShadowDecl>(D))
3493 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3495 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3496 CXXConversionDecl *Conv;
3498 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3500 Conv = cast<CXXConversionDecl>(D);
3502 if (AllowExplicit || !Conv->isExplicit()) {
3504 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3505 ActingDC, Initializer, DestType,
3508 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
3509 Initializer, DestType, CandidateSet);
3515 // Perform overload resolution. If it fails, return the failed result.
3516 OverloadCandidateSet::iterator Best;
3517 if (OverloadingResult Result
3518 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
3519 Sequence.SetOverloadFailure(
3520 InitializationSequence::FK_UserConversionOverloadFailed,
3525 FunctionDecl *Function = Best->Function;
3526 S.MarkDeclarationReferenced(DeclLoc, Function);
3528 if (isa<CXXConstructorDecl>(Function)) {
3529 // Add the user-defined conversion step. Any cv-qualification conversion is
3530 // subsumed by the initialization.
3531 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3535 // Add the user-defined conversion step that calls the conversion function.
3536 QualType ConvType = Function->getCallResultType();
3537 if (ConvType->getAs<RecordType>()) {
3538 // If we're converting to a class type, there may be an copy if
3539 // the resulting temporary object (possible to create an object of
3540 // a base class type). That copy is not a separate conversion, so
3541 // we just make a note of the actual destination type (possibly a
3542 // base class of the type returned by the conversion function) and
3543 // let the user-defined conversion step handle the conversion.
3544 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3548 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
3550 // If the conversion following the call to the conversion function
3551 // is interesting, add it as a separate step.
3552 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3553 Best->FinalConversion.Third) {
3554 ImplicitConversionSequence ICS;
3556 ICS.Standard = Best->FinalConversion;
3557 Sequence.AddConversionSequenceStep(ICS, DestType);
3561 /// The non-zero enum values here are indexes into diagnostic alternatives.
3562 enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3564 /// Determines whether this expression is an acceptable ICR source.
3565 static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3568 e = e->IgnoreParens();
3570 // Skip address-of nodes.
3571 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3572 if (op->getOpcode() == UO_AddrOf)
3573 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
3575 // Skip certain casts.
3576 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3577 switch (ce->getCastKind()) {
3580 case CK_LValueBitCast:
3582 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
3584 case CK_ArrayToPointerDecay:
3585 return IIK_nonscalar;
3587 case CK_NullToPointer:
3594 // If we have a declaration reference, it had better be a local variable.
3595 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3596 if (!isAddressOf) return IIK_nonlocal;
3599 if (isa<DeclRefExpr>(e)) {
3600 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3601 if (!var) return IIK_nonlocal;
3603 var = cast<BlockDeclRefExpr>(e)->getDecl();
3606 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
3608 // If we have a conditional operator, check both sides.
3609 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
3610 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
3613 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
3615 // These are never scalar.
3616 } else if (isa<ArraySubscriptExpr>(e)) {
3617 return IIK_nonscalar;
3619 // Otherwise, it needs to be a null pointer constant.
3621 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3622 ? IIK_okay : IIK_nonlocal);
3625 return IIK_nonlocal;
3628 /// Check whether the given expression is a valid operand for an
3629 /// indirect copy/restore.
3630 static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3631 assert(src->isRValue());
3633 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
3634 if (iik == IIK_okay) return;
3636 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3637 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3638 << src->getSourceRange();
3641 /// \brief Determine whether we have compatible array types for the
3642 /// purposes of GNU by-copy array initialization.
3643 static bool hasCompatibleArrayTypes(ASTContext &Context,
3644 const ArrayType *Dest,
3645 const ArrayType *Source) {
3646 // If the source and destination array types are equivalent, we're
3648 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3651 // Make sure that the element types are the same.
3652 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3655 // The only mismatch we allow is when the destination is an
3656 // incomplete array type and the source is a constant array type.
3657 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3660 static bool tryObjCWritebackConversion(Sema &S,
3661 InitializationSequence &Sequence,
3662 const InitializedEntity &Entity,
3663 Expr *Initializer) {
3664 bool ArrayDecay = false;
3665 QualType ArgType = Initializer->getType();
3666 QualType ArgPointee;
3667 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3669 ArgPointee = ArgArrayType->getElementType();
3670 ArgType = S.Context.getPointerType(ArgPointee);
3673 // Handle write-back conversion.
3674 QualType ConvertedArgType;
3675 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3679 // We should copy unless we're passing to an argument explicitly
3681 bool ShouldCopy = true;
3682 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3683 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3685 // Do we need an lvalue conversion?
3686 if (ArrayDecay || Initializer->isGLValue()) {
3687 ImplicitConversionSequence ICS;
3689 ICS.Standard.setAsIdentityConversion();
3691 QualType ResultType;
3693 ICS.Standard.First = ICK_Array_To_Pointer;
3694 ResultType = S.Context.getPointerType(ArgPointee);
3696 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3697 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3700 Sequence.AddConversionSequenceStep(ICS, ResultType);
3703 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3707 InitializationSequence::InitializationSequence(Sema &S,
3708 const InitializedEntity &Entity,
3709 const InitializationKind &Kind,
3712 : FailedCandidateSet(Kind.getLocation()) {
3713 ASTContext &Context = S.Context;
3715 // C++0x [dcl.init]p16:
3716 // The semantics of initializers are as follows. The destination type is
3717 // the type of the object or reference being initialized and the source
3718 // type is the type of the initializer expression. The source type is not
3719 // defined when the initializer is a braced-init-list or when it is a
3720 // parenthesized list of expressions.
3721 QualType DestType = Entity.getType();
3723 if (DestType->isDependentType() ||
3724 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3725 SequenceKind = DependentSequence;
3729 // Almost everything is a normal sequence.
3730 setSequenceKind(NormalSequence);
3732 for (unsigned I = 0; I != NumArgs; ++I)
3733 if (Args[I]->getObjectKind() == OK_ObjCProperty) {
3734 ExprResult Result = S.ConvertPropertyForRValue(Args[I]);
3735 if (Result.isInvalid()) {
3736 SetFailed(FK_ConversionFromPropertyFailed);
3739 Args[I] = Result.take();
3742 QualType SourceType;
3743 Expr *Initializer = 0;
3745 Initializer = Args[0];
3746 if (!isa<InitListExpr>(Initializer))
3747 SourceType = Initializer->getType();
3750 // - If the initializer is a braced-init-list, the object is
3751 // list-initialized (8.5.4).
3752 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3753 TryListInitialization(S, Entity, Kind, InitList, *this);
3757 // - If the destination type is a reference type, see 8.5.3.
3758 if (DestType->isReferenceType()) {
3759 // C++0x [dcl.init.ref]p1:
3760 // A variable declared to be a T& or T&&, that is, "reference to type T"
3761 // (8.3.2), shall be initialized by an object, or function, of type T or
3762 // by an object that can be converted into a T.
3763 // (Therefore, multiple arguments are not permitted.)
3765 SetFailed(FK_TooManyInitsForReference);
3767 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3771 // - If the initializer is (), the object is value-initialized.
3772 if (Kind.getKind() == InitializationKind::IK_Value ||
3773 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
3774 TryValueInitialization(S, Entity, Kind, *this);
3778 // Handle default initialization.
3779 if (Kind.getKind() == InitializationKind::IK_Default) {
3780 TryDefaultInitialization(S, Entity, Kind, *this);
3784 // - If the destination type is an array of characters, an array of
3785 // char16_t, an array of char32_t, or an array of wchar_t, and the
3786 // initializer is a string literal, see 8.5.2.
3787 // - Otherwise, if the destination type is an array, the program is
3789 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3790 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
3791 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3795 // Note: as an GNU C extension, we allow initialization of an
3796 // array from a compound literal that creates an array of the same
3797 // type, so long as the initializer has no side effects.
3798 if (!S.getLangOptions().CPlusPlus && Initializer &&
3799 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3800 Initializer->getType()->isArrayType()) {
3801 const ArrayType *SourceAT
3802 = Context.getAsArrayType(Initializer->getType());
3803 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
3804 SetFailed(FK_ArrayTypeMismatch);
3805 else if (Initializer->HasSideEffects(S.Context))
3806 SetFailed(FK_NonConstantArrayInit);
3808 AddArrayInitStep(DestType);
3810 } else if (DestAT->getElementType()->isAnyCharacterType())
3811 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3813 SetFailed(FK_ArrayNeedsInitList);
3818 // Determine whether we should consider writeback conversions for
3820 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
3821 Entity.getKind() == InitializedEntity::EK_Parameter;
3823 // We're at the end of the line for C: it's either a write-back conversion
3824 // or it's a C assignment. There's no need to check anything else.
3825 if (!S.getLangOptions().CPlusPlus) {
3826 // If allowed, check whether this is an Objective-C writeback conversion.
3827 if (allowObjCWritebackConversion &&
3828 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
3832 // Handle initialization in C
3833 AddCAssignmentStep(DestType);
3834 MaybeProduceObjCObject(S, *this, Entity);
3838 assert(S.getLangOptions().CPlusPlus);
3840 // - If the destination type is a (possibly cv-qualified) class type:
3841 if (DestType->isRecordType()) {
3842 // - If the initialization is direct-initialization, or if it is
3843 // copy-initialization where the cv-unqualified version of the
3844 // source type is the same class as, or a derived class of, the
3845 // class of the destination, constructors are considered. [...]
3846 if (Kind.getKind() == InitializationKind::IK_Direct ||
3847 (Kind.getKind() == InitializationKind::IK_Copy &&
3848 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3849 S.IsDerivedFrom(SourceType, DestType))))
3850 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
3851 Entity.getType(), *this);
3852 // - Otherwise (i.e., for the remaining copy-initialization cases),
3853 // user-defined conversion sequences that can convert from the source
3854 // type to the destination type or (when a conversion function is
3855 // used) to a derived class thereof are enumerated as described in
3856 // 13.3.1.4, and the best one is chosen through overload resolution
3859 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3864 SetFailed(FK_TooManyInitsForScalar);
3867 assert(NumArgs == 1 && "Zero-argument case handled above");
3869 // - Otherwise, if the source type is a (possibly cv-qualified) class
3870 // type, conversion functions are considered.
3871 if (!SourceType.isNull() && SourceType->isRecordType()) {
3872 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3873 MaybeProduceObjCObject(S, *this, Entity);
3877 // - Otherwise, the initial value of the object being initialized is the
3878 // (possibly converted) value of the initializer expression. Standard
3879 // conversions (Clause 4) will be used, if necessary, to convert the
3880 // initializer expression to the cv-unqualified version of the
3881 // destination type; no user-defined conversions are considered.
3883 ImplicitConversionSequence ICS
3884 = S.TryImplicitConversion(Initializer, Entity.getType(),
3885 /*SuppressUserConversions*/true,
3886 /*AllowExplicitConversions*/ false,
3887 /*InOverloadResolution*/ false,
3888 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3889 allowObjCWritebackConversion);
3891 if (ICS.isStandard() &&
3892 ICS.Standard.Second == ICK_Writeback_Conversion) {
3893 // Objective-C ARC writeback conversion.
3895 // We should copy unless we're passing to an argument explicitly
3897 bool ShouldCopy = true;
3898 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3899 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3901 // If there was an lvalue adjustment, add it as a separate conversion.
3902 if (ICS.Standard.First == ICK_Array_To_Pointer ||
3903 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
3904 ImplicitConversionSequence LvalueICS;
3905 LvalueICS.setStandard();
3906 LvalueICS.Standard.setAsIdentityConversion();
3907 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
3908 LvalueICS.Standard.First = ICS.Standard.First;
3909 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
3912 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3913 } else if (ICS.isBad()) {
3915 if (Initializer->getType() == Context.OverloadTy &&
3916 !S.ResolveAddressOfOverloadedFunction(Initializer
3917 , DestType, false, dap))
3918 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3920 SetFailed(InitializationSequence::FK_ConversionFailed);
3922 AddConversionSequenceStep(ICS, Entity.getType());
3924 MaybeProduceObjCObject(S, *this, Entity);
3928 InitializationSequence::~InitializationSequence() {
3929 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3930 StepEnd = Steps.end();
3931 Step != StepEnd; ++Step)
3935 //===----------------------------------------------------------------------===//
3936 // Perform initialization
3937 //===----------------------------------------------------------------------===//
3938 static Sema::AssignmentAction
3939 getAssignmentAction(const InitializedEntity &Entity) {
3940 switch(Entity.getKind()) {
3941 case InitializedEntity::EK_Variable:
3942 case InitializedEntity::EK_New:
3943 case InitializedEntity::EK_Exception:
3944 case InitializedEntity::EK_Base:
3945 case InitializedEntity::EK_Delegating:
3946 return Sema::AA_Initializing;
3948 case InitializedEntity::EK_Parameter:
3949 if (Entity.getDecl() &&
3950 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3951 return Sema::AA_Sending;
3953 return Sema::AA_Passing;
3955 case InitializedEntity::EK_Result:
3956 return Sema::AA_Returning;
3958 case InitializedEntity::EK_Temporary:
3959 // FIXME: Can we tell apart casting vs. converting?
3960 return Sema::AA_Casting;
3962 case InitializedEntity::EK_Member:
3963 case InitializedEntity::EK_ArrayElement:
3964 case InitializedEntity::EK_VectorElement:
3965 case InitializedEntity::EK_ComplexElement:
3966 case InitializedEntity::EK_BlockElement:
3967 return Sema::AA_Initializing;
3970 return Sema::AA_Converting;
3973 /// \brief Whether we should binding a created object as a temporary when
3974 /// initializing the given entity.
3975 static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
3976 switch (Entity.getKind()) {
3977 case InitializedEntity::EK_ArrayElement:
3978 case InitializedEntity::EK_Member:
3979 case InitializedEntity::EK_Result:
3980 case InitializedEntity::EK_New:
3981 case InitializedEntity::EK_Variable:
3982 case InitializedEntity::EK_Base:
3983 case InitializedEntity::EK_Delegating:
3984 case InitializedEntity::EK_VectorElement:
3985 case InitializedEntity::EK_ComplexElement:
3986 case InitializedEntity::EK_Exception:
3987 case InitializedEntity::EK_BlockElement:
3990 case InitializedEntity::EK_Parameter:
3991 case InitializedEntity::EK_Temporary:
3995 llvm_unreachable("missed an InitializedEntity kind?");
3998 /// \brief Whether the given entity, when initialized with an object
3999 /// created for that initialization, requires destruction.
4000 static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4001 switch (Entity.getKind()) {
4002 case InitializedEntity::EK_Member:
4003 case InitializedEntity::EK_Result:
4004 case InitializedEntity::EK_New:
4005 case InitializedEntity::EK_Base:
4006 case InitializedEntity::EK_Delegating:
4007 case InitializedEntity::EK_VectorElement:
4008 case InitializedEntity::EK_ComplexElement:
4009 case InitializedEntity::EK_BlockElement:
4012 case InitializedEntity::EK_Variable:
4013 case InitializedEntity::EK_Parameter:
4014 case InitializedEntity::EK_Temporary:
4015 case InitializedEntity::EK_ArrayElement:
4016 case InitializedEntity::EK_Exception:
4020 llvm_unreachable("missed an InitializedEntity kind?");
4023 /// \brief Make a (potentially elidable) temporary copy of the object
4024 /// provided by the given initializer by calling the appropriate copy
4027 /// \param S The Sema object used for type-checking.
4029 /// \param T The type of the temporary object, which must either be
4030 /// the type of the initializer expression or a superclass thereof.
4032 /// \param Enter The entity being initialized.
4034 /// \param CurInit The initializer expression.
4036 /// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4037 /// is permitted in C++03 (but not C++0x) when binding a reference to
4040 /// \returns An expression that copies the initializer expression into
4041 /// a temporary object, or an error expression if a copy could not be
4043 static ExprResult CopyObject(Sema &S,
4045 const InitializedEntity &Entity,
4047 bool IsExtraneousCopy) {
4048 // Determine which class type we're copying to.
4049 Expr *CurInitExpr = (Expr *)CurInit.get();
4050 CXXRecordDecl *Class = 0;
4051 if (const RecordType *Record = T->getAs<RecordType>())
4052 Class = cast<CXXRecordDecl>(Record->getDecl());
4054 return move(CurInit);
4056 // C++0x [class.copy]p32:
4057 // When certain criteria are met, an implementation is allowed to
4058 // omit the copy/move construction of a class object, even if the
4059 // copy/move constructor and/or destructor for the object have
4060 // side effects. [...]
4061 // - when a temporary class object that has not been bound to a
4062 // reference (12.2) would be copied/moved to a class object
4063 // with the same cv-unqualified type, the copy/move operation
4064 // can be omitted by constructing the temporary object
4065 // directly into the target of the omitted copy/move
4067 // Note that the other three bullets are handled elsewhere. Copy
4068 // elision for return statements and throw expressions are handled as part
4069 // of constructor initialization, while copy elision for exception handlers
4070 // is handled by the run-time.
4071 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
4073 switch (Entity.getKind()) {
4074 case InitializedEntity::EK_Result:
4075 Loc = Entity.getReturnLoc();
4078 case InitializedEntity::EK_Exception:
4079 Loc = Entity.getThrowLoc();
4082 case InitializedEntity::EK_Variable:
4083 Loc = Entity.getDecl()->getLocation();
4086 case InitializedEntity::EK_ArrayElement:
4087 case InitializedEntity::EK_Member:
4088 case InitializedEntity::EK_Parameter:
4089 case InitializedEntity::EK_Temporary:
4090 case InitializedEntity::EK_New:
4091 case InitializedEntity::EK_Base:
4092 case InitializedEntity::EK_Delegating:
4093 case InitializedEntity::EK_VectorElement:
4094 case InitializedEntity::EK_ComplexElement:
4095 case InitializedEntity::EK_BlockElement:
4096 Loc = CurInitExpr->getLocStart();
4100 // Make sure that the type we are copying is complete.
4101 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4102 return move(CurInit);
4104 // Perform overload resolution using the class's copy/move constructors.
4105 DeclContext::lookup_iterator Con, ConEnd;
4106 OverloadCandidateSet CandidateSet(Loc);
4107 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
4108 Con != ConEnd; ++Con) {
4109 // Only consider copy/move constructors and constructor templates. Per
4110 // C++0x [dcl.init]p16, second bullet to class types, this
4111 // initialization is direct-initialization.
4112 CXXConstructorDecl *Constructor = 0;
4114 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
4115 // Handle copy/moveconstructors, only.
4116 if (!Constructor || Constructor->isInvalidDecl() ||
4117 !Constructor->isCopyOrMoveConstructor() ||
4118 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4121 DeclAccessPair FoundDecl
4122 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4123 S.AddOverloadCandidate(Constructor, FoundDecl,
4124 &CurInitExpr, 1, CandidateSet);
4128 // Handle constructor templates.
4129 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4130 if (ConstructorTmpl->isInvalidDecl())
4133 Constructor = cast<CXXConstructorDecl>(
4134 ConstructorTmpl->getTemplatedDecl());
4135 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4138 // FIXME: Do we need to limit this to copy-constructor-like
4140 DeclAccessPair FoundDecl
4141 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4142 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4143 &CurInitExpr, 1, CandidateSet, true);
4146 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4148 OverloadCandidateSet::iterator Best;
4149 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
4153 case OR_No_Viable_Function:
4154 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4155 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4156 : diag::err_temp_copy_no_viable)
4157 << (int)Entity.getKind() << CurInitExpr->getType()
4158 << CurInitExpr->getSourceRange();
4159 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
4160 if (!IsExtraneousCopy || S.isSFINAEContext())
4162 return move(CurInit);
4165 S.Diag(Loc, diag::err_temp_copy_ambiguous)
4166 << (int)Entity.getKind() << CurInitExpr->getType()
4167 << CurInitExpr->getSourceRange();
4168 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
4172 S.Diag(Loc, diag::err_temp_copy_deleted)
4173 << (int)Entity.getKind() << CurInitExpr->getType()
4174 << CurInitExpr->getSourceRange();
4175 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4176 << 1 << Best->Function->isDeleted();
4180 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
4181 ASTOwningVector<Expr*> ConstructorArgs(S);
4182 CurInit.release(); // Ownership transferred into MultiExprArg, below.
4184 S.CheckConstructorAccess(Loc, Constructor, Entity,
4185 Best->FoundDecl.getAccess(), IsExtraneousCopy);
4187 if (IsExtraneousCopy) {
4188 // If this is a totally extraneous copy for C++03 reference
4189 // binding purposes, just return the original initialization
4190 // expression. We don't generate an (elided) copy operation here
4191 // because doing so would require us to pass down a flag to avoid
4192 // infinite recursion, where each step adds another extraneous,
4195 // Instantiate the default arguments of any extra parameters in
4196 // the selected copy constructor, as if we were going to create a
4197 // proper call to the copy constructor.
4198 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4199 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4200 if (S.RequireCompleteType(Loc, Parm->getType(),
4201 S.PDiag(diag::err_call_incomplete_argument)))
4204 // Build the default argument expression; we don't actually care
4205 // if this succeeds or not, because this routine will complain
4206 // if there was a problem.
4207 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4210 return S.Owned(CurInitExpr);
4213 S.MarkDeclarationReferenced(Loc, Constructor);
4215 // Determine the arguments required to actually perform the
4216 // constructor call (we might have derived-to-base conversions, or
4217 // the copy constructor may have default arguments).
4218 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
4219 Loc, ConstructorArgs))
4222 // Actually perform the constructor call.
4223 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
4224 move_arg(ConstructorArgs),
4225 HadMultipleCandidates,
4227 CXXConstructExpr::CK_Complete,
4230 // If we're supposed to bind temporaries, do so.
4231 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4232 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4233 return move(CurInit);
4236 void InitializationSequence::PrintInitLocationNote(Sema &S,
4237 const InitializedEntity &Entity) {
4238 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4239 if (Entity.getDecl()->getLocation().isInvalid())
4242 if (Entity.getDecl()->getDeclName())
4243 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4244 << Entity.getDecl()->getDeclName();
4246 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4250 static bool isReferenceBinding(const InitializationSequence::Step &s) {
4251 return s.Kind == InitializationSequence::SK_BindReference ||
4252 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4256 InitializationSequence::Perform(Sema &S,
4257 const InitializedEntity &Entity,
4258 const InitializationKind &Kind,
4260 QualType *ResultType) {
4262 unsigned NumArgs = Args.size();
4263 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
4267 if (getKind() == DependentSequence) {
4268 // If the declaration is a non-dependent, incomplete array type
4269 // that has an initializer, then its type will be completed once
4270 // the initializer is instantiated.
4271 if (ResultType && !Entity.getType()->isDependentType() &&
4273 QualType DeclType = Entity.getType();
4274 if (const IncompleteArrayType *ArrayT
4275 = S.Context.getAsIncompleteArrayType(DeclType)) {
4276 // FIXME: We don't currently have the ability to accurately
4277 // compute the length of an initializer list without
4278 // performing full type-checking of the initializer list
4279 // (since we have to determine where braces are implicitly
4280 // introduced and such). So, we fall back to making the array
4281 // type a dependently-sized array type with no specified
4283 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4284 SourceRange Brackets;
4286 // Scavange the location of the brackets from the entity, if we can.
4287 if (DeclaratorDecl *DD = Entity.getDecl()) {
4288 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4289 TypeLoc TL = TInfo->getTypeLoc();
4290 if (IncompleteArrayTypeLoc *ArrayLoc
4291 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4292 Brackets = ArrayLoc->getBracketsRange();
4297 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4299 ArrayT->getSizeModifier(),
4300 ArrayT->getIndexTypeCVRQualifiers(),
4306 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4307 Kind.isExplicitCast());
4308 return ExprResult(Args.release()[0]);
4311 // No steps means no initialization.
4313 return S.Owned((Expr *)0);
4315 QualType DestType = Entity.getType().getNonReferenceType();
4316 // FIXME: Ugly hack around the fact that Entity.getType() is not
4317 // the same as Entity.getDecl()->getType() in cases involving type merging,
4318 // and we want latter when it makes sense.
4320 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
4323 ExprResult CurInit = S.Owned((Expr *)0);
4325 // For initialization steps that start with a single initializer,
4326 // grab the only argument out the Args and place it into the "current"
4328 switch (Steps.front().Kind) {
4329 case SK_ResolveAddressOfOverloadedFunction:
4330 case SK_CastDerivedToBaseRValue:
4331 case SK_CastDerivedToBaseXValue:
4332 case SK_CastDerivedToBaseLValue:
4333 case SK_BindReference:
4334 case SK_BindReferenceToTemporary:
4335 case SK_ExtraneousCopyToTemporary:
4336 case SK_UserConversion:
4337 case SK_QualificationConversionLValue:
4338 case SK_QualificationConversionXValue:
4339 case SK_QualificationConversionRValue:
4340 case SK_ConversionSequence:
4341 case SK_ListConstructorCall:
4342 case SK_ListInitialization:
4343 case SK_CAssignment:
4345 case SK_ObjCObjectConversion:
4347 case SK_PassByIndirectCopyRestore:
4348 case SK_PassByIndirectRestore:
4349 case SK_ProduceObjCObject: {
4350 assert(Args.size() == 1);
4351 CurInit = Args.get()[0];
4352 if (!CurInit.get()) return ExprError();
4354 // Read from a property when initializing something with it.
4355 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
4356 CurInit = S.ConvertPropertyForRValue(CurInit.take());
4357 if (CurInit.isInvalid())
4363 case SK_ConstructorInitialization:
4364 case SK_ZeroInitialization:
4368 // Walk through the computed steps for the initialization sequence,
4369 // performing the specified conversions along the way.
4370 bool ConstructorInitRequiresZeroInit = false;
4371 for (step_iterator Step = step_begin(), StepEnd = step_end();
4372 Step != StepEnd; ++Step) {
4373 if (CurInit.isInvalid())
4376 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
4378 switch (Step->Kind) {
4379 case SK_ResolveAddressOfOverloadedFunction:
4380 // Overload resolution determined which function invoke; update the
4381 // initializer to reflect that choice.
4382 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
4383 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
4384 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
4385 Step->Function.FoundDecl,
4386 Step->Function.Function);
4389 case SK_CastDerivedToBaseRValue:
4390 case SK_CastDerivedToBaseXValue:
4391 case SK_CastDerivedToBaseLValue: {
4392 // We have a derived-to-base cast that produces either an rvalue or an
4393 // lvalue. Perform that cast.
4395 CXXCastPath BasePath;
4397 // Casts to inaccessible base classes are allowed with C-style casts.
4398 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4399 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
4400 CurInit.get()->getLocStart(),
4401 CurInit.get()->getSourceRange(),
4402 &BasePath, IgnoreBaseAccess))
4405 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4406 QualType T = SourceType;
4407 if (const PointerType *Pointer = T->getAs<PointerType>())
4408 T = Pointer->getPointeeType();
4409 if (const RecordType *RecordTy = T->getAs<RecordType>())
4410 S.MarkVTableUsed(CurInit.get()->getLocStart(),
4411 cast<CXXRecordDecl>(RecordTy->getDecl()));
4415 Step->Kind == SK_CastDerivedToBaseLValue ?
4417 (Step->Kind == SK_CastDerivedToBaseXValue ?
4420 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4428 case SK_BindReference:
4429 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
4430 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4431 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
4432 << Entity.getType().isVolatileQualified()
4433 << BitField->getDeclName()
4434 << CurInit.get()->getSourceRange();
4435 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
4439 if (CurInit.get()->refersToVectorElement()) {
4440 // References cannot bind to vector elements.
4441 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4442 << Entity.getType().isVolatileQualified()
4443 << CurInit.get()->getSourceRange();
4444 PrintInitLocationNote(S, Entity);
4448 // Reference binding does not have any corresponding ASTs.
4450 // Check exception specifications
4451 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
4456 case SK_BindReferenceToTemporary:
4457 // Check exception specifications
4458 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
4461 // Materialize the temporary into memory.
4462 CurInit = new (S.Context) MaterializeTemporaryExpr(
4463 Entity.getType().getNonReferenceType(),
4465 Entity.getType()->isLValueReferenceType());
4467 // If we're binding to an Objective-C object that has lifetime, we
4469 if (S.getLangOptions().ObjCAutoRefCount &&
4470 CurInit.get()->getType()->isObjCLifetimeType())
4471 S.ExprNeedsCleanups = true;
4475 case SK_ExtraneousCopyToTemporary:
4476 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
4477 /*IsExtraneousCopy=*/true);
4480 case SK_UserConversion: {
4481 // We have a user-defined conversion that invokes either a constructor
4482 // or a conversion function.
4484 bool IsCopy = false;
4485 FunctionDecl *Fn = Step->Function.Function;
4486 DeclAccessPair FoundFn = Step->Function.FoundDecl;
4487 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
4488 bool CreatedObject = false;
4489 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
4490 // Build a call to the selected constructor.
4491 ASTOwningVector<Expr*> ConstructorArgs(S);
4492 SourceLocation Loc = CurInit.get()->getLocStart();
4493 CurInit.release(); // Ownership transferred into MultiExprArg, below.
4495 // Determine the arguments required to actually perform the constructor
4497 Expr *Arg = CurInit.get();
4498 if (S.CompleteConstructorCall(Constructor,
4499 MultiExprArg(&Arg, 1),
4500 Loc, ConstructorArgs))
4503 // Build the an expression that constructs a temporary.
4504 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
4505 move_arg(ConstructorArgs),
4506 HadMultipleCandidates,
4508 CXXConstructExpr::CK_Complete,
4510 if (CurInit.isInvalid())
4513 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
4514 FoundFn.getAccess());
4515 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
4517 CastKind = CK_ConstructorConversion;
4518 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4519 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4520 S.IsDerivedFrom(SourceType, Class))
4523 CreatedObject = true;
4525 // Build a call to the conversion function.
4526 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
4527 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
4529 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
4531 // FIXME: Should we move this initialization into a separate
4532 // derived-to-base conversion? I believe the answer is "no", because
4533 // we don't want to turn off access control here for c-style casts.
4534 ExprResult CurInitExprRes =
4535 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4536 FoundFn, Conversion);
4537 if(CurInitExprRes.isInvalid())
4539 CurInit = move(CurInitExprRes);
4541 // Build the actual call to the conversion function.
4542 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
4543 HadMultipleCandidates);
4544 if (CurInit.isInvalid() || !CurInit.get())
4547 CastKind = CK_UserDefinedConversion;
4549 CreatedObject = Conversion->getResultType()->isRecordType();
4552 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
4553 if (RequiresCopy || shouldBindAsTemporary(Entity))
4554 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4555 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
4556 QualType T = CurInit.get()->getType();
4557 if (const RecordType *Record = T->getAs<RecordType>()) {
4558 CXXDestructorDecl *Destructor
4559 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
4560 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
4561 S.PDiag(diag::err_access_dtor_temp) << T);
4562 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
4563 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
4567 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4568 CurInit.get()->getType(),
4569 CastKind, CurInit.get(), 0,
4570 CurInit.get()->getValueKind()));
4573 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4574 move(CurInit), /*IsExtraneousCopy=*/false);
4579 case SK_QualificationConversionLValue:
4580 case SK_QualificationConversionXValue:
4581 case SK_QualificationConversionRValue: {
4582 // Perform a qualification conversion; these can never go wrong.
4584 Step->Kind == SK_QualificationConversionLValue ?
4586 (Step->Kind == SK_QualificationConversionXValue ?
4589 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
4593 case SK_ConversionSequence: {
4594 Sema::CheckedConversionKind CCK
4595 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4596 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
4597 : Kind.isExplicitCast()? Sema::CCK_OtherCast
4598 : Sema::CCK_ImplicitConversion;
4599 ExprResult CurInitExprRes =
4600 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
4601 getAssignmentAction(Entity), CCK);
4602 if (CurInitExprRes.isInvalid())
4604 CurInit = move(CurInitExprRes);
4608 case SK_ListInitialization: {
4609 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
4610 QualType Ty = Step->Type;
4611 InitListChecker PerformInitList(S, Entity, InitList,
4612 ResultType ? *ResultType : Ty, /*VerifyOnly=*/false);
4613 if (PerformInitList.HadError())
4617 CurInit = S.Owned(PerformInitList.getFullyStructuredList());
4621 case SK_ListConstructorCall:
4622 assert(false && "List constructor calls not yet supported.");
4624 case SK_ConstructorInitialization: {
4625 unsigned NumArgs = Args.size();
4626 CXXConstructorDecl *Constructor
4627 = cast<CXXConstructorDecl>(Step->Function.Function);
4628 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
4630 // Build a call to the selected constructor.
4631 ASTOwningVector<Expr*> ConstructorArgs(S);
4632 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4633 ? Kind.getEqualLoc()
4634 : Kind.getLocation();
4636 if (Kind.getKind() == InitializationKind::IK_Default) {
4637 // Force even a trivial, implicit default constructor to be
4638 // semantically checked. We do this explicitly because we don't build
4639 // the definition for completely trivial constructors.
4640 CXXRecordDecl *ClassDecl = Constructor->getParent();
4641 assert(ClassDecl && "No parent class for constructor.");
4642 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
4643 ClassDecl->hasTrivialDefaultConstructor() &&
4644 !Constructor->isUsed(false))
4645 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4648 // Determine the arguments required to actually perform the constructor
4650 if (S.CompleteConstructorCall(Constructor, move(Args),
4651 Loc, ConstructorArgs))
4655 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
4656 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4657 (Kind.getKind() == InitializationKind::IK_Direct ||
4658 Kind.getKind() == InitializationKind::IK_Value)) {
4659 // An explicitly-constructed temporary, e.g., X(1, 2).
4660 unsigned NumExprs = ConstructorArgs.size();
4661 Expr **Exprs = (Expr **)ConstructorArgs.take();
4662 S.MarkDeclarationReferenced(Loc, Constructor);
4663 S.DiagnoseUseOfDecl(Constructor, Loc);
4665 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4667 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
4669 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4674 Kind.getParenRange(),
4675 HadMultipleCandidates,
4676 ConstructorInitRequiresZeroInit));
4678 CXXConstructExpr::ConstructionKind ConstructKind =
4679 CXXConstructExpr::CK_Complete;
4681 if (Entity.getKind() == InitializedEntity::EK_Base) {
4682 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4683 CXXConstructExpr::CK_VirtualBase :
4684 CXXConstructExpr::CK_NonVirtualBase;
4685 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4686 ConstructKind = CXXConstructExpr::CK_Delegating;
4689 // Only get the parenthesis range if it is a direct construction.
4690 SourceRange parenRange =
4691 Kind.getKind() == InitializationKind::IK_Direct ?
4692 Kind.getParenRange() : SourceRange();
4694 // If the entity allows NRVO, mark the construction as elidable
4696 if (Entity.allowsNRVO())
4697 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4698 Constructor, /*Elidable=*/true,
4699 move_arg(ConstructorArgs),
4700 HadMultipleCandidates,
4701 ConstructorInitRequiresZeroInit,
4705 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4707 move_arg(ConstructorArgs),
4708 HadMultipleCandidates,
4709 ConstructorInitRequiresZeroInit,
4713 if (CurInit.isInvalid())
4716 // Only check access if all of that succeeded.
4717 S.CheckConstructorAccess(Loc, Constructor, Entity,
4718 Step->Function.FoundDecl.getAccess());
4719 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
4721 if (shouldBindAsTemporary(Entity))
4722 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4727 case SK_ZeroInitialization: {
4728 step_iterator NextStep = Step;
4730 if (NextStep != StepEnd &&
4731 NextStep->Kind == SK_ConstructorInitialization) {
4732 // The need for zero-initialization is recorded directly into
4733 // the call to the object's constructor within the next step.
4734 ConstructorInitRequiresZeroInit = true;
4735 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4736 S.getLangOptions().CPlusPlus &&
4737 !Kind.isImplicitValueInit()) {
4738 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4740 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
4741 Kind.getRange().getBegin());
4743 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4744 TSInfo->getType().getNonLValueExprType(S.Context),
4746 Kind.getRange().getEnd()));
4748 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
4753 case SK_CAssignment: {
4754 QualType SourceType = CurInit.get()->getType();
4755 ExprResult Result = move(CurInit);
4756 Sema::AssignConvertType ConvTy =
4757 S.CheckSingleAssignmentConstraints(Step->Type, Result);
4758 if (Result.isInvalid())
4760 CurInit = move(Result);
4762 // If this is a call, allow conversion to a transparent union.
4763 ExprResult CurInitExprRes = move(CurInit);
4764 if (ConvTy != Sema::Compatible &&
4765 Entity.getKind() == InitializedEntity::EK_Parameter &&
4766 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
4767 == Sema::Compatible)
4768 ConvTy = Sema::Compatible;
4769 if (CurInitExprRes.isInvalid())
4771 CurInit = move(CurInitExprRes);
4774 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4775 Step->Type, SourceType,
4777 getAssignmentAction(Entity),
4779 PrintInitLocationNote(S, Entity);
4781 } else if (Complained)
4782 PrintInitLocationNote(S, Entity);
4786 case SK_StringInit: {
4787 QualType Ty = Step->Type;
4788 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
4789 S.Context.getAsArrayType(Ty), S);
4793 case SK_ObjCObjectConversion:
4794 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
4795 CK_ObjCObjectLValueCast,
4796 CurInit.get()->getValueKind());
4800 // Okay: we checked everything before creating this step. Note that
4801 // this is a GNU extension.
4802 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
4803 << Step->Type << CurInit.get()->getType()
4804 << CurInit.get()->getSourceRange();
4806 // If the destination type is an incomplete array type, update the
4807 // type accordingly.
4809 if (const IncompleteArrayType *IncompleteDest
4810 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4811 if (const ConstantArrayType *ConstantSource
4812 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
4813 *ResultType = S.Context.getConstantArrayType(
4814 IncompleteDest->getElementType(),
4815 ConstantSource->getSize(),
4816 ArrayType::Normal, 0);
4822 case SK_PassByIndirectCopyRestore:
4823 case SK_PassByIndirectRestore:
4824 checkIndirectCopyRestoreSource(S, CurInit.get());
4825 CurInit = S.Owned(new (S.Context)
4826 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
4827 Step->Kind == SK_PassByIndirectCopyRestore));
4830 case SK_ProduceObjCObject:
4831 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
4832 CK_ARCProduceObject,
4833 CurInit.take(), 0, VK_RValue));
4838 // Diagnose non-fatal problems with the completed initialization.
4839 if (Entity.getKind() == InitializedEntity::EK_Member &&
4840 cast<FieldDecl>(Entity.getDecl())->isBitField())
4841 S.CheckBitFieldInitialization(Kind.getLocation(),
4842 cast<FieldDecl>(Entity.getDecl()),
4845 return move(CurInit);
4848 //===----------------------------------------------------------------------===//
4849 // Diagnose initialization failures
4850 //===----------------------------------------------------------------------===//
4851 bool InitializationSequence::Diagnose(Sema &S,
4852 const InitializedEntity &Entity,
4853 const InitializationKind &Kind,
4854 Expr **Args, unsigned NumArgs) {
4858 QualType DestType = Entity.getType();
4860 case FK_TooManyInitsForReference:
4861 // FIXME: Customize for the initialized entity?
4863 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4864 << DestType.getNonReferenceType();
4865 else // FIXME: diagnostic below could be better!
4866 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4867 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
4870 case FK_ArrayNeedsInitList:
4871 case FK_ArrayNeedsInitListOrStringLiteral:
4872 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4873 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4876 case FK_ArrayTypeMismatch:
4877 case FK_NonConstantArrayInit:
4878 S.Diag(Kind.getLocation(),
4879 (Failure == FK_ArrayTypeMismatch
4880 ? diag::err_array_init_different_type
4881 : diag::err_array_init_non_constant_array))
4882 << DestType.getNonReferenceType()
4883 << Args[0]->getType()
4884 << Args[0]->getSourceRange();
4887 case FK_AddressOfOverloadFailed: {
4888 DeclAccessPair Found;
4889 S.ResolveAddressOfOverloadedFunction(Args[0],
4890 DestType.getNonReferenceType(),
4896 case FK_ReferenceInitOverloadFailed:
4897 case FK_UserConversionOverloadFailed:
4898 switch (FailedOverloadResult) {
4900 if (Failure == FK_UserConversionOverloadFailed)
4901 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4902 << Args[0]->getType() << DestType
4903 << Args[0]->getSourceRange();
4905 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4906 << DestType << Args[0]->getType()
4907 << Args[0]->getSourceRange();
4909 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
4912 case OR_No_Viable_Function:
4913 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4914 << Args[0]->getType() << DestType.getNonReferenceType()
4915 << Args[0]->getSourceRange();
4916 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
4920 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4921 << Args[0]->getType() << DestType.getNonReferenceType()
4922 << Args[0]->getSourceRange();
4923 OverloadCandidateSet::iterator Best;
4924 OverloadingResult Ovl
4925 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4927 if (Ovl == OR_Deleted) {
4928 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4929 << 1 << Best->Function->isDeleted();
4931 llvm_unreachable("Inconsistent overload resolution?");
4937 llvm_unreachable("Conversion did not fail!");
4942 case FK_NonConstLValueReferenceBindingToTemporary:
4943 case FK_NonConstLValueReferenceBindingToUnrelated:
4944 S.Diag(Kind.getLocation(),
4945 Failure == FK_NonConstLValueReferenceBindingToTemporary
4946 ? diag::err_lvalue_reference_bind_to_temporary
4947 : diag::err_lvalue_reference_bind_to_unrelated)
4948 << DestType.getNonReferenceType().isVolatileQualified()
4949 << DestType.getNonReferenceType()
4950 << Args[0]->getType()
4951 << Args[0]->getSourceRange();
4954 case FK_RValueReferenceBindingToLValue:
4955 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
4956 << DestType.getNonReferenceType() << Args[0]->getType()
4957 << Args[0]->getSourceRange();
4960 case FK_ReferenceInitDropsQualifiers:
4961 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4962 << DestType.getNonReferenceType()
4963 << Args[0]->getType()
4964 << Args[0]->getSourceRange();
4967 case FK_ReferenceInitFailed:
4968 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4969 << DestType.getNonReferenceType()
4970 << Args[0]->isLValue()
4971 << Args[0]->getType()
4972 << Args[0]->getSourceRange();
4973 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4974 Args[0]->getType()->isObjCObjectPointerType())
4975 S.EmitRelatedResultTypeNote(Args[0]);
4978 case FK_ConversionFailed: {
4979 QualType FromType = Args[0]->getType();
4980 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4981 << (int)Entity.getKind()
4983 << Args[0]->isLValue()
4985 << Args[0]->getSourceRange();
4986 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4987 Args[0]->getType()->isObjCObjectPointerType())
4988 S.EmitRelatedResultTypeNote(Args[0]);
4992 case FK_ConversionFromPropertyFailed:
4993 // No-op. This error has already been reported.
4996 case FK_TooManyInitsForScalar: {
4999 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
5000 R = SourceRange(InitList->getInit(0)->getLocEnd(),
5001 InitList->getLocEnd());
5003 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
5005 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5006 if (Kind.isCStyleOrFunctionalCast())
5007 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5010 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5011 << /*scalar=*/2 << R;
5015 case FK_ReferenceBindingToInitList:
5016 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5017 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5020 case FK_InitListBadDestinationType:
5021 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5022 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5025 case FK_ConstructorOverloadFailed: {
5026 SourceRange ArgsRange;
5028 ArgsRange = SourceRange(Args[0]->getLocStart(),
5029 Args[NumArgs - 1]->getLocEnd());
5031 // FIXME: Using "DestType" for the entity we're printing is probably
5033 switch (FailedOverloadResult) {
5035 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5036 << DestType << ArgsRange;
5037 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5041 case OR_No_Viable_Function:
5042 if (Kind.getKind() == InitializationKind::IK_Default &&
5043 (Entity.getKind() == InitializedEntity::EK_Base ||
5044 Entity.getKind() == InitializedEntity::EK_Member) &&
5045 isa<CXXConstructorDecl>(S.CurContext)) {
5046 // This is implicit default initialization of a member or
5047 // base within a constructor. If no viable function was
5048 // found, notify the user that she needs to explicitly
5049 // initialize this base/member.
5050 CXXConstructorDecl *Constructor
5051 = cast<CXXConstructorDecl>(S.CurContext);
5052 if (Entity.getKind() == InitializedEntity::EK_Base) {
5053 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5054 << Constructor->isImplicit()
5055 << S.Context.getTypeDeclType(Constructor->getParent())
5057 << Entity.getType();
5059 RecordDecl *BaseDecl
5060 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5062 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5063 << S.Context.getTagDeclType(BaseDecl);
5065 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5066 << Constructor->isImplicit()
5067 << S.Context.getTypeDeclType(Constructor->getParent())
5069 << Entity.getName();
5070 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5072 if (const RecordType *Record
5073 = Entity.getType()->getAs<RecordType>())
5074 S.Diag(Record->getDecl()->getLocation(),
5075 diag::note_previous_decl)
5076 << S.Context.getTagDeclType(Record->getDecl());
5081 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5082 << DestType << ArgsRange;
5083 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
5087 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5088 << true << DestType << ArgsRange;
5089 OverloadCandidateSet::iterator Best;
5090 OverloadingResult Ovl
5091 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
5092 if (Ovl == OR_Deleted) {
5093 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
5094 << 1 << Best->Function->isDeleted();
5096 llvm_unreachable("Inconsistent overload resolution?");
5102 llvm_unreachable("Conversion did not fail!");
5108 case FK_DefaultInitOfConst:
5109 if (Entity.getKind() == InitializedEntity::EK_Member &&
5110 isa<CXXConstructorDecl>(S.CurContext)) {
5111 // This is implicit default-initialization of a const member in
5112 // a constructor. Complain that it needs to be explicitly
5114 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5115 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5116 << Constructor->isImplicit()
5117 << S.Context.getTypeDeclType(Constructor->getParent())
5119 << Entity.getName();
5120 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5121 << Entity.getName();
5123 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5124 << DestType << (bool)DestType->getAs<RecordType>();
5129 S.RequireCompleteType(Kind.getLocation(), DestType,
5130 diag::err_init_incomplete_type);
5133 case FK_ListInitializationFailed: {
5134 // Run the init list checker again to emit diagnostics.
5135 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5136 QualType DestType = Entity.getType();
5137 InitListChecker DiagnoseInitList(S, Entity, InitList,
5138 DestType, /*VerifyOnly=*/false);
5139 assert(DiagnoseInitList.HadError() &&
5140 "Inconsistent init list check result.");
5145 PrintInitLocationNote(S, Entity);
5149 void InitializationSequence::dump(raw_ostream &OS) const {
5150 switch (SequenceKind) {
5151 case FailedSequence: {
5152 OS << "Failed sequence: ";
5154 case FK_TooManyInitsForReference:
5155 OS << "too many initializers for reference";
5158 case FK_ArrayNeedsInitList:
5159 OS << "array requires initializer list";
5162 case FK_ArrayNeedsInitListOrStringLiteral:
5163 OS << "array requires initializer list or string literal";
5166 case FK_ArrayTypeMismatch:
5167 OS << "array type mismatch";
5170 case FK_NonConstantArrayInit:
5171 OS << "non-constant array initializer";
5174 case FK_AddressOfOverloadFailed:
5175 OS << "address of overloaded function failed";
5178 case FK_ReferenceInitOverloadFailed:
5179 OS << "overload resolution for reference initialization failed";
5182 case FK_NonConstLValueReferenceBindingToTemporary:
5183 OS << "non-const lvalue reference bound to temporary";
5186 case FK_NonConstLValueReferenceBindingToUnrelated:
5187 OS << "non-const lvalue reference bound to unrelated type";
5190 case FK_RValueReferenceBindingToLValue:
5191 OS << "rvalue reference bound to an lvalue";
5194 case FK_ReferenceInitDropsQualifiers:
5195 OS << "reference initialization drops qualifiers";
5198 case FK_ReferenceInitFailed:
5199 OS << "reference initialization failed";
5202 case FK_ConversionFailed:
5203 OS << "conversion failed";
5206 case FK_ConversionFromPropertyFailed:
5207 OS << "conversion from property failed";
5210 case FK_TooManyInitsForScalar:
5211 OS << "too many initializers for scalar";
5214 case FK_ReferenceBindingToInitList:
5215 OS << "referencing binding to initializer list";
5218 case FK_InitListBadDestinationType:
5219 OS << "initializer list for non-aggregate, non-scalar type";
5222 case FK_UserConversionOverloadFailed:
5223 OS << "overloading failed for user-defined conversion";
5226 case FK_ConstructorOverloadFailed:
5227 OS << "constructor overloading failed";
5230 case FK_DefaultInitOfConst:
5231 OS << "default initialization of a const variable";
5235 OS << "initialization of incomplete type";
5238 case FK_ListInitializationFailed:
5239 OS << "list initialization checker failure";
5245 case DependentSequence:
5246 OS << "Dependent sequence\n";
5249 case NormalSequence:
5250 OS << "Normal sequence: ";
5254 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5255 if (S != step_begin()) {
5260 case SK_ResolveAddressOfOverloadedFunction:
5261 OS << "resolve address of overloaded function";
5264 case SK_CastDerivedToBaseRValue:
5265 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5268 case SK_CastDerivedToBaseXValue:
5269 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5272 case SK_CastDerivedToBaseLValue:
5273 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5276 case SK_BindReference:
5277 OS << "bind reference to lvalue";
5280 case SK_BindReferenceToTemporary:
5281 OS << "bind reference to a temporary";
5284 case SK_ExtraneousCopyToTemporary:
5285 OS << "extraneous C++03 copy to temporary";
5288 case SK_UserConversion:
5289 OS << "user-defined conversion via " << *S->Function.Function;
5292 case SK_QualificationConversionRValue:
5293 OS << "qualification conversion (rvalue)";
5295 case SK_QualificationConversionXValue:
5296 OS << "qualification conversion (xvalue)";
5298 case SK_QualificationConversionLValue:
5299 OS << "qualification conversion (lvalue)";
5302 case SK_ConversionSequence:
5303 OS << "implicit conversion sequence (";
5304 S->ICS->DebugPrint(); // FIXME: use OS
5308 case SK_ListInitialization:
5309 OS << "list aggregate initialization";
5312 case SK_ListConstructorCall:
5313 OS << "list initialization via constructor";
5316 case SK_ConstructorInitialization:
5317 OS << "constructor initialization";
5320 case SK_ZeroInitialization:
5321 OS << "zero initialization";
5324 case SK_CAssignment:
5325 OS << "C assignment";
5329 OS << "string initialization";
5332 case SK_ObjCObjectConversion:
5333 OS << "Objective-C object conversion";
5337 OS << "array initialization";
5340 case SK_PassByIndirectCopyRestore:
5341 OS << "pass by indirect copy and restore";
5344 case SK_PassByIndirectRestore:
5345 OS << "pass by indirect restore";
5348 case SK_ProduceObjCObject:
5349 OS << "Objective-C object retension";
5355 void InitializationSequence::dump() const {
5359 static void DiagnoseNarrowingInInitList(
5360 Sema& S, QualType EntityType, const Expr *InitE,
5361 bool Constant, const APValue &ConstantValue) {
5363 S.Diag(InitE->getLocStart(),
5364 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
5365 ? diag::err_init_list_constant_narrowing
5366 : diag::warn_init_list_constant_narrowing)
5367 << InitE->getSourceRange()
5369 << EntityType.getLocalUnqualifiedType();
5371 S.Diag(InitE->getLocStart(),
5372 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
5373 ? diag::err_init_list_variable_narrowing
5374 : diag::warn_init_list_variable_narrowing)
5375 << InitE->getSourceRange()
5376 << InitE->getType().getLocalUnqualifiedType()
5377 << EntityType.getLocalUnqualifiedType();
5379 llvm::SmallString<128> StaticCast;
5380 llvm::raw_svector_ostream OS(StaticCast);
5381 OS << "static_cast<";
5382 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5383 // It's important to use the typedef's name if there is one so that the
5384 // fixit doesn't break code using types like int64_t.
5386 // FIXME: This will break if the typedef requires qualification. But
5387 // getQualifiedNameAsString() includes non-machine-parsable components.
5388 OS << *TT->getDecl();
5389 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5390 OS << BT->getName(S.getLangOptions());
5392 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5393 // with a broken cast.
5397 S.Diag(InitE->getLocStart(), diag::note_init_list_narrowing_override)
5398 << InitE->getSourceRange()
5399 << FixItHint::CreateInsertion(InitE->getLocStart(), OS.str())
5400 << FixItHint::CreateInsertion(
5401 S.getPreprocessor().getLocForEndOfToken(InitE->getLocEnd()), ")");
5404 //===----------------------------------------------------------------------===//
5405 // Initialization helper functions
5406 //===----------------------------------------------------------------------===//
5408 Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5410 if (Init.isInvalid())
5413 Expr *InitE = Init.get();
5414 assert(InitE && "No initialization expression");
5416 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5418 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5419 return !Seq.Failed();
5423 Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5424 SourceLocation EqualLoc,
5426 bool TopLevelOfInitList) {
5427 if (Init.isInvalid())
5430 Expr *InitE = Init.get();
5431 assert(InitE && "No initialization expression?");
5433 if (EqualLoc.isInvalid())
5434 EqualLoc = InitE->getLocStart();
5436 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5438 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5441 bool Constant = false;
5443 if (TopLevelOfInitList &&
5444 Seq.endsWithNarrowing(Context, InitE, &Constant, &Result)) {
5445 DiagnoseNarrowingInInitList(*this, Entity.getType(), InitE,
5448 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));