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/ADT/APInt.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
29 using namespace clang;
31 //===----------------------------------------------------------------------===//
32 // Sema Initialization Checking
33 //===----------------------------------------------------------------------===//
35 static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
36 ASTContext &Context) {
37 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
40 // See if this is a string literal or @encode.
41 Init = Init->IgnoreParens();
43 // Handle @encode, which is a narrow string.
44 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
47 // Otherwise we can only handle string literals.
48 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
49 if (SL == 0) return 0;
51 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
53 switch (SL->getKind()) {
54 case StringLiteral::Ascii:
55 case StringLiteral::UTF8:
56 // char array can be initialized with a narrow string.
57 // Only allow char x[] = "foo"; not char x[] = L"foo";
58 return ElemTy->isCharType() ? Init : 0;
59 case StringLiteral::UTF16:
60 return ElemTy->isChar16Type() ? Init : 0;
61 case StringLiteral::UTF32:
62 return ElemTy->isChar32Type() ? Init : 0;
63 case StringLiteral::Wide:
64 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
65 // correction from DR343): "An array with element type compatible with a
66 // qualified or unqualified version of wchar_t may be initialized by a wide
67 // string literal, optionally enclosed in braces."
68 if (Context.typesAreCompatible(Context.getWCharType(),
69 ElemTy.getUnqualifiedType()))
75 llvm_unreachable("missed a StringLiteral kind?");
78 static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
79 const ArrayType *arrayType = Context.getAsArrayType(declType);
80 if (!arrayType) return 0;
82 return IsStringInit(init, arrayType, Context);
85 static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
87 // Get the length of the string as parsed.
89 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
92 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
93 // C99 6.7.8p14. We have an array of character type with unknown size
94 // being initialized to a string literal.
95 llvm::APInt ConstVal(32, StrLength);
96 // Return a new array type (C99 6.7.8p22).
97 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
99 ArrayType::Normal, 0);
103 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
105 // We have an array of character type with known size. However,
106 // the size may be smaller or larger than the string we are initializing.
107 // FIXME: Avoid truncation for 64-bit length strings.
108 if (S.getLangOpts().CPlusPlus) {
109 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
110 // For Pascal strings it's OK to strip off the terminating null character,
111 // so the example below is valid:
113 // unsigned char a[2] = "\pa";
118 // [dcl.init.string]p2
119 if (StrLength > CAT->getSize().getZExtValue())
120 S.Diag(Str->getLocStart(),
121 diag::err_initializer_string_for_char_array_too_long)
122 << Str->getSourceRange();
125 if (StrLength-1 > CAT->getSize().getZExtValue())
126 S.Diag(Str->getLocStart(),
127 diag::warn_initializer_string_for_char_array_too_long)
128 << Str->getSourceRange();
131 // Set the type to the actual size that we are initializing. If we have
133 // char x[1] = "foo";
134 // then this will set the string literal's type to char[1].
138 //===----------------------------------------------------------------------===//
139 // Semantic checking for initializer lists.
140 //===----------------------------------------------------------------------===//
142 /// @brief Semantic checking for initializer lists.
144 /// The InitListChecker class contains a set of routines that each
145 /// handle the initialization of a certain kind of entity, e.g.,
146 /// arrays, vectors, struct/union types, scalars, etc. The
147 /// InitListChecker itself performs a recursive walk of the subobject
148 /// structure of the type to be initialized, while stepping through
149 /// the initializer list one element at a time. The IList and Index
150 /// parameters to each of the Check* routines contain the active
151 /// (syntactic) initializer list and the index into that initializer
152 /// list that represents the current initializer. Each routine is
153 /// responsible for moving that Index forward as it consumes elements.
155 /// Each Check* routine also has a StructuredList/StructuredIndex
156 /// arguments, which contains the current "structured" (semantic)
157 /// initializer list and the index into that initializer list where we
158 /// are copying initializers as we map them over to the semantic
159 /// list. Once we have completed our recursive walk of the subobject
160 /// structure, we will have constructed a full semantic initializer
163 /// C99 designators cause changes in the initializer list traversal,
164 /// because they make the initialization "jump" into a specific
165 /// subobject and then continue the initialization from that
166 /// point. CheckDesignatedInitializer() recursively steps into the
167 /// designated subobject and manages backing out the recursion to
168 /// initialize the subobjects after the one designated.
170 class InitListChecker {
173 bool VerifyOnly; // no diagnostics, no structure building
174 bool AllowBraceElision;
175 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
176 InitListExpr *FullyStructuredList;
178 void CheckImplicitInitList(const InitializedEntity &Entity,
179 InitListExpr *ParentIList, QualType T,
180 unsigned &Index, InitListExpr *StructuredList,
181 unsigned &StructuredIndex);
182 void CheckExplicitInitList(const InitializedEntity &Entity,
183 InitListExpr *IList, QualType &T,
184 unsigned &Index, InitListExpr *StructuredList,
185 unsigned &StructuredIndex,
186 bool TopLevelObject = false);
187 void CheckListElementTypes(const InitializedEntity &Entity,
188 InitListExpr *IList, QualType &DeclType,
189 bool SubobjectIsDesignatorContext,
191 InitListExpr *StructuredList,
192 unsigned &StructuredIndex,
193 bool TopLevelObject = false);
194 void CheckSubElementType(const InitializedEntity &Entity,
195 InitListExpr *IList, QualType ElemType,
197 InitListExpr *StructuredList,
198 unsigned &StructuredIndex);
199 void CheckComplexType(const InitializedEntity &Entity,
200 InitListExpr *IList, QualType DeclType,
202 InitListExpr *StructuredList,
203 unsigned &StructuredIndex);
204 void CheckScalarType(const InitializedEntity &Entity,
205 InitListExpr *IList, QualType DeclType,
207 InitListExpr *StructuredList,
208 unsigned &StructuredIndex);
209 void CheckReferenceType(const InitializedEntity &Entity,
210 InitListExpr *IList, QualType DeclType,
212 InitListExpr *StructuredList,
213 unsigned &StructuredIndex);
214 void CheckVectorType(const InitializedEntity &Entity,
215 InitListExpr *IList, QualType DeclType, unsigned &Index,
216 InitListExpr *StructuredList,
217 unsigned &StructuredIndex);
218 void CheckStructUnionTypes(const InitializedEntity &Entity,
219 InitListExpr *IList, QualType DeclType,
220 RecordDecl::field_iterator Field,
221 bool SubobjectIsDesignatorContext, unsigned &Index,
222 InitListExpr *StructuredList,
223 unsigned &StructuredIndex,
224 bool TopLevelObject = false);
225 void CheckArrayType(const InitializedEntity &Entity,
226 InitListExpr *IList, QualType &DeclType,
227 llvm::APSInt elementIndex,
228 bool SubobjectIsDesignatorContext, unsigned &Index,
229 InitListExpr *StructuredList,
230 unsigned &StructuredIndex);
231 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
232 InitListExpr *IList, DesignatedInitExpr *DIE,
234 QualType &CurrentObjectType,
235 RecordDecl::field_iterator *NextField,
236 llvm::APSInt *NextElementIndex,
238 InitListExpr *StructuredList,
239 unsigned &StructuredIndex,
240 bool FinishSubobjectInit,
241 bool TopLevelObject);
242 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
243 QualType CurrentObjectType,
244 InitListExpr *StructuredList,
245 unsigned StructuredIndex,
246 SourceRange InitRange);
247 void UpdateStructuredListElement(InitListExpr *StructuredList,
248 unsigned &StructuredIndex,
250 int numArrayElements(QualType DeclType);
251 int numStructUnionElements(QualType DeclType);
253 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
254 const InitializedEntity &ParentEntity,
255 InitListExpr *ILE, bool &RequiresSecondPass);
256 void FillInValueInitializations(const InitializedEntity &Entity,
257 InitListExpr *ILE, bool &RequiresSecondPass);
258 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
259 Expr *InitExpr, FieldDecl *Field,
260 bool TopLevelObject);
261 void CheckValueInitializable(const InitializedEntity &Entity);
264 InitListChecker(Sema &S, const InitializedEntity &Entity,
265 InitListExpr *IL, QualType &T, bool VerifyOnly,
266 bool AllowBraceElision);
267 bool HadError() { return hadError; }
269 // @brief Retrieves the fully-structured initializer list used for
270 // semantic analysis and code generation.
271 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
273 } // end anonymous namespace
275 void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
277 "CheckValueInitializable is only inteded for verification mode.");
280 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
282 InitializationSequence InitSeq(SemaRef, Entity, Kind, 0, 0);
283 if (InitSeq.Failed())
287 void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
288 const InitializedEntity &ParentEntity,
290 bool &RequiresSecondPass) {
291 SourceLocation Loc = ILE->getLocStart();
292 unsigned NumInits = ILE->getNumInits();
293 InitializedEntity MemberEntity
294 = InitializedEntity::InitializeMember(Field, &ParentEntity);
295 if (Init >= NumInits || !ILE->getInit(Init)) {
296 // FIXME: We probably don't need to handle references
297 // specially here, since value-initialization of references is
298 // handled in InitializationSequence.
299 if (Field->getType()->isReferenceType()) {
300 // C++ [dcl.init.aggr]p9:
301 // If an incomplete or empty initializer-list leaves a
302 // member of reference type uninitialized, the program is
304 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
306 << ILE->getSyntacticForm()->getSourceRange();
307 SemaRef.Diag(Field->getLocation(),
308 diag::note_uninit_reference_member);
313 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
315 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
317 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
322 ExprResult MemberInit
323 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
324 if (MemberInit.isInvalid()) {
331 } else if (Init < NumInits) {
332 ILE->setInit(Init, MemberInit.takeAs<Expr>());
333 } else if (InitSeq.isConstructorInitialization()) {
334 // Value-initialization requires a constructor call, so
335 // extend the initializer list to include the constructor
336 // call and make a note that we'll need to take another pass
337 // through the initializer list.
338 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
339 RequiresSecondPass = true;
341 } else if (InitListExpr *InnerILE
342 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
343 FillInValueInitializations(MemberEntity, InnerILE,
347 /// Recursively replaces NULL values within the given initializer list
348 /// with expressions that perform value-initialization of the
349 /// appropriate type.
351 InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
353 bool &RequiresSecondPass) {
354 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
355 "Should not have void type");
356 SourceLocation Loc = ILE->getLocStart();
357 if (ILE->getSyntacticForm())
358 Loc = ILE->getSyntacticForm()->getLocStart();
360 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
361 if (RType->getDecl()->isUnion() &&
362 ILE->getInitializedFieldInUnion())
363 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
364 Entity, ILE, RequiresSecondPass);
367 for (RecordDecl::field_iterator
368 Field = RType->getDecl()->field_begin(),
369 FieldEnd = RType->getDecl()->field_end();
370 Field != FieldEnd; ++Field) {
371 if (Field->isUnnamedBitfield())
377 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
383 // Only look at the first initialization of a union.
384 if (RType->getDecl()->isUnion())
392 QualType ElementType;
394 InitializedEntity ElementEntity = Entity;
395 unsigned NumInits = ILE->getNumInits();
396 unsigned NumElements = NumInits;
397 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
398 ElementType = AType->getElementType();
399 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
400 NumElements = CAType->getSize().getZExtValue();
401 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
403 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
404 ElementType = VType->getElementType();
405 NumElements = VType->getNumElements();
406 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
409 ElementType = ILE->getType();
412 for (unsigned Init = 0; Init != NumElements; ++Init) {
416 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
417 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
418 ElementEntity.setElementIndex(Init);
420 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
421 if (!InitExpr && !ILE->hasArrayFiller()) {
422 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
424 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
426 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
431 ExprResult ElementInit
432 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
433 if (ElementInit.isInvalid()) {
440 } else if (Init < NumInits) {
441 // For arrays, just set the expression used for value-initialization
442 // of the "holes" in the array.
443 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
444 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
446 ILE->setInit(Init, ElementInit.takeAs<Expr>());
448 // For arrays, just set the expression used for value-initialization
449 // of the rest of elements and exit.
450 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
451 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
455 if (InitSeq.isConstructorInitialization()) {
456 // Value-initialization requires a constructor call, so
457 // extend the initializer list to include the constructor
458 // call and make a note that we'll need to take another pass
459 // through the initializer list.
460 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
461 RequiresSecondPass = true;
464 } else if (InitListExpr *InnerILE
465 = dyn_cast_or_null<InitListExpr>(InitExpr))
466 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
471 InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
472 InitListExpr *IL, QualType &T,
473 bool VerifyOnly, bool AllowBraceElision)
474 : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
477 unsigned newIndex = 0;
478 unsigned newStructuredIndex = 0;
480 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
481 CheckExplicitInitList(Entity, IL, T, newIndex,
482 FullyStructuredList, newStructuredIndex,
483 /*TopLevelObject=*/true);
485 if (!hadError && !VerifyOnly) {
486 bool RequiresSecondPass = false;
487 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
488 if (RequiresSecondPass && !hadError)
489 FillInValueInitializations(Entity, FullyStructuredList,
494 int InitListChecker::numArrayElements(QualType DeclType) {
495 // FIXME: use a proper constant
496 int maxElements = 0x7FFFFFFF;
497 if (const ConstantArrayType *CAT =
498 SemaRef.Context.getAsConstantArrayType(DeclType)) {
499 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
504 int InitListChecker::numStructUnionElements(QualType DeclType) {
505 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
506 int InitializableMembers = 0;
507 for (RecordDecl::field_iterator
508 Field = structDecl->field_begin(),
509 FieldEnd = structDecl->field_end();
510 Field != FieldEnd; ++Field) {
511 if (!Field->isUnnamedBitfield())
512 ++InitializableMembers;
514 if (structDecl->isUnion())
515 return std::min(InitializableMembers, 1);
516 return InitializableMembers - structDecl->hasFlexibleArrayMember();
519 void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
520 InitListExpr *ParentIList,
521 QualType T, unsigned &Index,
522 InitListExpr *StructuredList,
523 unsigned &StructuredIndex) {
526 if (T->isArrayType())
527 maxElements = numArrayElements(T);
528 else if (T->isRecordType())
529 maxElements = numStructUnionElements(T);
530 else if (T->isVectorType())
531 maxElements = T->getAs<VectorType>()->getNumElements();
533 llvm_unreachable("CheckImplicitInitList(): Illegal type");
535 if (maxElements == 0) {
537 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
538 diag::err_implicit_empty_initializer);
544 // Build a structured initializer list corresponding to this subobject.
545 InitListExpr *StructuredSubobjectInitList
546 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
548 SourceRange(ParentIList->getInit(Index)->getLocStart(),
549 ParentIList->getSourceRange().getEnd()));
550 unsigned StructuredSubobjectInitIndex = 0;
552 // Check the element types and build the structural subobject.
553 unsigned StartIndex = Index;
554 CheckListElementTypes(Entity, ParentIList, T,
555 /*SubobjectIsDesignatorContext=*/false, Index,
556 StructuredSubobjectInitList,
557 StructuredSubobjectInitIndex);
560 if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
563 StructuredSubobjectInitList->setType(T);
565 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
566 // Update the structured sub-object initializer so that it's ending
567 // range corresponds with the end of the last initializer it used.
568 if (EndIndex < ParentIList->getNumInits()) {
569 SourceLocation EndLoc
570 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
571 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
574 // Complain about missing braces.
575 if (T->isArrayType() || T->isRecordType()) {
576 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
577 AllowBraceElision ? diag::warn_missing_braces :
578 diag::err_missing_braces)
579 << StructuredSubobjectInitList->getSourceRange()
580 << FixItHint::CreateInsertion(
581 StructuredSubobjectInitList->getLocStart(), "{")
582 << FixItHint::CreateInsertion(
583 SemaRef.PP.getLocForEndOfToken(
584 StructuredSubobjectInitList->getLocEnd()),
586 if (!AllowBraceElision)
592 void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
593 InitListExpr *IList, QualType &T,
595 InitListExpr *StructuredList,
596 unsigned &StructuredIndex,
597 bool TopLevelObject) {
598 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
600 SyntacticToSemantic[IList] = StructuredList;
601 StructuredList->setSyntacticForm(IList);
603 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
604 Index, StructuredList, StructuredIndex, TopLevelObject);
607 if (!ExprTy->isArrayType())
608 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
609 IList->setType(ExprTy);
610 StructuredList->setType(ExprTy);
615 if (Index < IList->getNumInits()) {
616 // We have leftover initializers
618 if (SemaRef.getLangOpts().CPlusPlus ||
619 (SemaRef.getLangOpts().OpenCL &&
620 IList->getType()->isVectorType())) {
626 if (StructuredIndex == 1 &&
627 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
628 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
629 if (SemaRef.getLangOpts().CPlusPlus) {
630 DK = diag::err_excess_initializers_in_char_array_initializer;
634 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
635 << IList->getInit(Index)->getSourceRange();
636 } else if (!T->isIncompleteType()) {
637 // Don't complain for incomplete types, since we'll get an error
639 QualType CurrentObjectType = StructuredList->getType();
641 CurrentObjectType->isArrayType()? 0 :
642 CurrentObjectType->isVectorType()? 1 :
643 CurrentObjectType->isScalarType()? 2 :
644 CurrentObjectType->isUnionType()? 3 :
647 unsigned DK = diag::warn_excess_initializers;
648 if (SemaRef.getLangOpts().CPlusPlus) {
649 DK = diag::err_excess_initializers;
652 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
653 DK = diag::err_excess_initializers;
657 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
658 << initKind << IList->getInit(Index)->getSourceRange();
662 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
664 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
665 << IList->getSourceRange()
666 << FixItHint::CreateRemoval(IList->getLocStart())
667 << FixItHint::CreateRemoval(IList->getLocEnd());
670 void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
673 bool SubobjectIsDesignatorContext,
675 InitListExpr *StructuredList,
676 unsigned &StructuredIndex,
677 bool TopLevelObject) {
678 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
679 // Explicitly braced initializer for complex type can be real+imaginary
681 CheckComplexType(Entity, IList, DeclType, Index,
682 StructuredList, StructuredIndex);
683 } else if (DeclType->isScalarType()) {
684 CheckScalarType(Entity, IList, DeclType, Index,
685 StructuredList, StructuredIndex);
686 } else if (DeclType->isVectorType()) {
687 CheckVectorType(Entity, IList, DeclType, Index,
688 StructuredList, StructuredIndex);
689 } else if (DeclType->isRecordType()) {
690 assert(DeclType->isAggregateType() &&
691 "non-aggregate records should be handed in CheckSubElementType");
692 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
693 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
694 SubobjectIsDesignatorContext, Index,
695 StructuredList, StructuredIndex,
697 } else if (DeclType->isArrayType()) {
699 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
701 CheckArrayType(Entity, IList, DeclType, Zero,
702 SubobjectIsDesignatorContext, Index,
703 StructuredList, StructuredIndex);
704 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
705 // This type is invalid, issue a diagnostic.
708 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
711 } else if (DeclType->isReferenceType()) {
712 CheckReferenceType(Entity, IList, DeclType, Index,
713 StructuredList, StructuredIndex);
714 } else if (DeclType->isObjCObjectType()) {
716 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
721 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
727 void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
731 InitListExpr *StructuredList,
732 unsigned &StructuredIndex) {
733 Expr *expr = IList->getInit(Index);
734 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
735 if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
736 unsigned newIndex = 0;
737 unsigned newStructuredIndex = 0;
738 InitListExpr *newStructuredList
739 = getStructuredSubobjectInit(IList, Index, ElemType,
740 StructuredList, StructuredIndex,
741 SubInitList->getSourceRange());
742 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
743 newStructuredList, newStructuredIndex);
748 assert(SemaRef.getLangOpts().CPlusPlus &&
749 "non-aggregate records are only possible in C++");
750 // C++ initialization is handled later.
753 if (ElemType->isScalarType()) {
754 return CheckScalarType(Entity, IList, ElemType, Index,
755 StructuredList, StructuredIndex);
756 } else if (ElemType->isReferenceType()) {
757 return CheckReferenceType(Entity, IList, ElemType, Index,
758 StructuredList, StructuredIndex);
761 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
762 // arrayType can be incomplete if we're initializing a flexible
763 // array member. There's nothing we can do with the completed
764 // type here, though.
766 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
768 CheckStringInit(Str, ElemType, arrayType, SemaRef);
769 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
775 // Fall through for subaggregate initialization.
777 } else if (SemaRef.getLangOpts().CPlusPlus) {
778 // C++ [dcl.init.aggr]p12:
779 // All implicit type conversions (clause 4) are considered when
780 // initializing the aggregate member with an initializer from
781 // an initializer-list. If the initializer can initialize a
782 // member, the member is initialized. [...]
784 // FIXME: Better EqualLoc?
785 InitializationKind Kind =
786 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
787 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
792 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
793 if (Result.isInvalid())
796 UpdateStructuredListElement(StructuredList, StructuredIndex,
797 Result.takeAs<Expr>());
803 // Fall through for subaggregate initialization
807 // The initializer for a structure or union object that has
808 // automatic storage duration shall be either an initializer
809 // list as described below, or a single expression that has
810 // compatible structure or union type. In the latter case, the
811 // initial value of the object, including unnamed members, is
812 // that of the expression.
813 ExprResult ExprRes = SemaRef.Owned(expr);
814 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
815 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
817 == Sema::Compatible) {
818 if (ExprRes.isInvalid())
821 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
822 if (ExprRes.isInvalid())
825 UpdateStructuredListElement(StructuredList, StructuredIndex,
826 ExprRes.takeAs<Expr>());
831 // Fall through for subaggregate initialization
834 // C++ [dcl.init.aggr]p12:
836 // [...] Otherwise, if the member is itself a non-empty
837 // subaggregate, brace elision is assumed and the initializer is
838 // considered for the initialization of the first member of
840 if (!SemaRef.getLangOpts().OpenCL &&
841 (ElemType->isAggregateType() || ElemType->isVectorType())) {
842 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
847 // We cannot initialize this element, so let
848 // PerformCopyInitialization produce the appropriate diagnostic.
849 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
851 /*TopLevelOfInitList=*/true);
859 void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
860 InitListExpr *IList, QualType DeclType,
862 InitListExpr *StructuredList,
863 unsigned &StructuredIndex) {
864 assert(Index == 0 && "Index in explicit init list must be zero");
866 // As an extension, clang supports complex initializers, which initialize
867 // a complex number component-wise. When an explicit initializer list for
868 // a complex number contains two two initializers, this extension kicks in:
869 // it exepcts the initializer list to contain two elements convertible to
870 // the element type of the complex type. The first element initializes
871 // the real part, and the second element intitializes the imaginary part.
873 if (IList->getNumInits() != 2)
874 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
877 // This is an extension in C. (The builtin _Complex type does not exist
878 // in the C++ standard.)
879 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
880 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
881 << IList->getSourceRange();
883 // Initialize the complex number.
884 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
885 InitializedEntity ElementEntity =
886 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
888 for (unsigned i = 0; i < 2; ++i) {
889 ElementEntity.setElementIndex(Index);
890 CheckSubElementType(ElementEntity, IList, elementType, Index,
891 StructuredList, StructuredIndex);
896 void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
897 InitListExpr *IList, QualType DeclType,
899 InitListExpr *StructuredList,
900 unsigned &StructuredIndex) {
901 if (Index >= IList->getNumInits()) {
903 SemaRef.Diag(IList->getLocStart(),
904 SemaRef.getLangOpts().CPlusPlus0x ?
905 diag::warn_cxx98_compat_empty_scalar_initializer :
906 diag::err_empty_scalar_initializer)
907 << IList->getSourceRange();
908 hadError = !SemaRef.getLangOpts().CPlusPlus0x;
914 Expr *expr = IList->getInit(Index);
915 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
917 SemaRef.Diag(SubIList->getLocStart(),
918 diag::warn_many_braces_around_scalar_init)
919 << SubIList->getSourceRange();
921 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
924 } else if (isa<DesignatedInitExpr>(expr)) {
926 SemaRef.Diag(expr->getLocStart(),
927 diag::err_designator_for_scalar_init)
928 << DeclType << expr->getSourceRange();
936 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
943 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
945 /*TopLevelOfInitList=*/true);
947 Expr *ResultExpr = 0;
949 if (Result.isInvalid())
950 hadError = true; // types weren't compatible.
952 ResultExpr = Result.takeAs<Expr>();
954 if (ResultExpr != expr) {
955 // The type was promoted, update initializer list.
956 IList->setInit(Index, ResultExpr);
962 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
966 void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
967 InitListExpr *IList, QualType DeclType,
969 InitListExpr *StructuredList,
970 unsigned &StructuredIndex) {
971 if (Index >= IList->getNumInits()) {
972 // FIXME: It would be wonderful if we could point at the actual member. In
973 // general, it would be useful to pass location information down the stack,
974 // so that we know the location (or decl) of the "current object" being
977 SemaRef.Diag(IList->getLocStart(),
978 diag::err_init_reference_member_uninitialized)
980 << IList->getSourceRange();
987 Expr *expr = IList->getInit(Index);
988 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus0x) {
990 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
991 << DeclType << IList->getSourceRange();
999 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1006 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1007 SemaRef.Owned(expr),
1008 /*TopLevelOfInitList=*/true);
1010 if (Result.isInvalid())
1013 expr = Result.takeAs<Expr>();
1014 IList->setInit(Index, expr);
1019 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1023 void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1024 InitListExpr *IList, QualType DeclType,
1026 InitListExpr *StructuredList,
1027 unsigned &StructuredIndex) {
1028 const VectorType *VT = DeclType->getAs<VectorType>();
1029 unsigned maxElements = VT->getNumElements();
1030 unsigned numEltsInit = 0;
1031 QualType elementType = VT->getElementType();
1033 if (Index >= IList->getNumInits()) {
1034 // Make sure the element type can be value-initialized.
1036 CheckValueInitializable(
1037 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1041 if (!SemaRef.getLangOpts().OpenCL) {
1042 // If the initializing element is a vector, try to copy-initialize
1043 // instead of breaking it apart (which is doomed to failure anyway).
1044 Expr *Init = IList->getInit(Index);
1045 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1047 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1054 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
1055 SemaRef.Owned(Init),
1056 /*TopLevelOfInitList=*/true);
1058 Expr *ResultExpr = 0;
1059 if (Result.isInvalid())
1060 hadError = true; // types weren't compatible.
1062 ResultExpr = Result.takeAs<Expr>();
1064 if (ResultExpr != Init) {
1065 // The type was promoted, update initializer list.
1066 IList->setInit(Index, ResultExpr);
1072 UpdateStructuredListElement(StructuredList, StructuredIndex,
1078 InitializedEntity ElementEntity =
1079 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1081 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1082 // Don't attempt to go past the end of the init list
1083 if (Index >= IList->getNumInits()) {
1085 CheckValueInitializable(ElementEntity);
1089 ElementEntity.setElementIndex(Index);
1090 CheckSubElementType(ElementEntity, IList, elementType, Index,
1091 StructuredList, StructuredIndex);
1096 InitializedEntity ElementEntity =
1097 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1099 // OpenCL initializers allows vectors to be constructed from vectors.
1100 for (unsigned i = 0; i < maxElements; ++i) {
1101 // Don't attempt to go past the end of the init list
1102 if (Index >= IList->getNumInits())
1105 ElementEntity.setElementIndex(Index);
1107 QualType IType = IList->getInit(Index)->getType();
1108 if (!IType->isVectorType()) {
1109 CheckSubElementType(ElementEntity, IList, elementType, Index,
1110 StructuredList, StructuredIndex);
1114 const VectorType *IVT = IType->getAs<VectorType>();
1115 unsigned numIElts = IVT->getNumElements();
1117 if (IType->isExtVectorType())
1118 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1120 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1121 IVT->getVectorKind());
1122 CheckSubElementType(ElementEntity, IList, VecType, Index,
1123 StructuredList, StructuredIndex);
1124 numEltsInit += numIElts;
1128 // OpenCL requires all elements to be initialized.
1129 if (numEltsInit != maxElements) {
1131 SemaRef.Diag(IList->getLocStart(),
1132 diag::err_vector_incorrect_num_initializers)
1133 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1138 void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1139 InitListExpr *IList, QualType &DeclType,
1140 llvm::APSInt elementIndex,
1141 bool SubobjectIsDesignatorContext,
1143 InitListExpr *StructuredList,
1144 unsigned &StructuredIndex) {
1145 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1147 // Check for the special-case of initializing an array with a string.
1148 if (Index < IList->getNumInits()) {
1149 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
1151 // We place the string literal directly into the resulting
1152 // initializer list. This is the only place where the structure
1153 // of the structured initializer list doesn't match exactly,
1154 // because doing so would involve allocating one character
1155 // constant for each string.
1157 CheckStringInit(Str, DeclType, arrayType, SemaRef);
1158 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1159 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1165 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1166 // Check for VLAs; in standard C it would be possible to check this
1167 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1168 // them in all sorts of strange places).
1170 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1171 diag::err_variable_object_no_init)
1172 << VAT->getSizeExpr()->getSourceRange();
1179 // We might know the maximum number of elements in advance.
1180 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1181 elementIndex.isUnsigned());
1182 bool maxElementsKnown = false;
1183 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
1184 maxElements = CAT->getSize();
1185 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
1186 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1187 maxElementsKnown = true;
1190 QualType elementType = arrayType->getElementType();
1191 while (Index < IList->getNumInits()) {
1192 Expr *Init = IList->getInit(Index);
1193 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1194 // If we're not the subobject that matches up with the '{' for
1195 // the designator, we shouldn't be handling the
1196 // designator. Return immediately.
1197 if (!SubobjectIsDesignatorContext)
1200 // Handle this designated initializer. elementIndex will be
1201 // updated to be the next array element we'll initialize.
1202 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1203 DeclType, 0, &elementIndex, Index,
1204 StructuredList, StructuredIndex, true,
1210 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1211 maxElements = maxElements.extend(elementIndex.getBitWidth());
1212 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1213 elementIndex = elementIndex.extend(maxElements.getBitWidth());
1214 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1216 // If the array is of incomplete type, keep track of the number of
1217 // elements in the initializer.
1218 if (!maxElementsKnown && elementIndex > maxElements)
1219 maxElements = elementIndex;
1224 // If we know the maximum number of elements, and we've already
1225 // hit it, stop consuming elements in the initializer list.
1226 if (maxElementsKnown && elementIndex == maxElements)
1229 InitializedEntity ElementEntity =
1230 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1232 // Check this element.
1233 CheckSubElementType(ElementEntity, IList, elementType, Index,
1234 StructuredList, StructuredIndex);
1237 // If the array is of incomplete type, keep track of the number of
1238 // elements in the initializer.
1239 if (!maxElementsKnown && elementIndex > maxElements)
1240 maxElements = elementIndex;
1242 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
1243 // If this is an incomplete array type, the actual type needs to
1244 // be calculated here.
1245 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
1246 if (maxElements == Zero) {
1247 // Sizing an array implicitly to zero is not allowed by ISO C,
1248 // but is supported by GNU.
1249 SemaRef.Diag(IList->getLocStart(),
1250 diag::ext_typecheck_zero_array_size);
1253 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
1254 ArrayType::Normal, 0);
1256 if (!hadError && VerifyOnly) {
1257 // Check if there are any members of the array that get value-initialized.
1258 // If so, check if doing that is possible.
1259 // FIXME: This needs to detect holes left by designated initializers too.
1260 if (maxElementsKnown && elementIndex < maxElements)
1261 CheckValueInitializable(InitializedEntity::InitializeElement(
1262 SemaRef.Context, 0, Entity));
1266 bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1269 bool TopLevelObject) {
1270 // Handle GNU flexible array initializers.
1271 unsigned FlexArrayDiag;
1272 if (isa<InitListExpr>(InitExpr) &&
1273 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1274 // Empty flexible array init always allowed as an extension
1275 FlexArrayDiag = diag::ext_flexible_array_init;
1276 } else if (SemaRef.getLangOpts().CPlusPlus) {
1277 // Disallow flexible array init in C++; it is not required for gcc
1278 // compatibility, and it needs work to IRGen correctly in general.
1279 FlexArrayDiag = diag::err_flexible_array_init;
1280 } else if (!TopLevelObject) {
1281 // Disallow flexible array init on non-top-level object
1282 FlexArrayDiag = diag::err_flexible_array_init;
1283 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1284 // Disallow flexible array init on anything which is not a variable.
1285 FlexArrayDiag = diag::err_flexible_array_init;
1286 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1287 // Disallow flexible array init on local variables.
1288 FlexArrayDiag = diag::err_flexible_array_init;
1290 // Allow other cases.
1291 FlexArrayDiag = diag::ext_flexible_array_init;
1295 SemaRef.Diag(InitExpr->getLocStart(),
1297 << InitExpr->getLocStart();
1298 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1302 return FlexArrayDiag != diag::ext_flexible_array_init;
1305 void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
1306 InitListExpr *IList,
1308 RecordDecl::field_iterator Field,
1309 bool SubobjectIsDesignatorContext,
1311 InitListExpr *StructuredList,
1312 unsigned &StructuredIndex,
1313 bool TopLevelObject) {
1314 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
1316 // If the record is invalid, some of it's members are invalid. To avoid
1317 // confusion, we forgo checking the intializer for the entire record.
1318 if (structDecl->isInvalidDecl()) {
1319 // Assume it was supposed to consume a single initializer.
1325 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1326 // Value-initialize the first named member of the union.
1327 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1328 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1329 Field != FieldEnd; ++Field) {
1330 if (Field->getDeclName()) {
1332 CheckValueInitializable(
1333 InitializedEntity::InitializeMember(*Field, &Entity));
1335 StructuredList->setInitializedFieldInUnion(*Field);
1342 // If structDecl is a forward declaration, this loop won't do
1343 // anything except look at designated initializers; That's okay,
1344 // because an error should get printed out elsewhere. It might be
1345 // worthwhile to skip over the rest of the initializer, though.
1346 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1347 RecordDecl::field_iterator FieldEnd = RD->field_end();
1348 bool InitializedSomething = false;
1349 bool CheckForMissingFields = true;
1350 while (Index < IList->getNumInits()) {
1351 Expr *Init = IList->getInit(Index);
1353 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1354 // If we're not the subobject that matches up with the '{' for
1355 // the designator, we shouldn't be handling the
1356 // designator. Return immediately.
1357 if (!SubobjectIsDesignatorContext)
1360 // Handle this designated initializer. Field will be updated to
1361 // the next field that we'll be initializing.
1362 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1363 DeclType, &Field, 0, Index,
1364 StructuredList, StructuredIndex,
1365 true, TopLevelObject))
1368 InitializedSomething = true;
1370 // Disable check for missing fields when designators are used.
1371 // This matches gcc behaviour.
1372 CheckForMissingFields = false;
1376 if (Field == FieldEnd) {
1377 // We've run out of fields. We're done.
1381 // We've already initialized a member of a union. We're done.
1382 if (InitializedSomething && DeclType->isUnionType())
1385 // If we've hit the flexible array member at the end, we're done.
1386 if (Field->getType()->isIncompleteArrayType())
1389 if (Field->isUnnamedBitfield()) {
1390 // Don't initialize unnamed bitfields, e.g. "int : 20;"
1395 // Make sure we can use this declaration.
1398 InvalidUse = !SemaRef.CanUseDecl(*Field);
1400 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1401 IList->getInit(Index)->getLocStart());
1409 InitializedEntity MemberEntity =
1410 InitializedEntity::InitializeMember(*Field, &Entity);
1411 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1412 StructuredList, StructuredIndex);
1413 InitializedSomething = true;
1415 if (DeclType->isUnionType() && !VerifyOnly) {
1416 // Initialize the first field within the union.
1417 StructuredList->setInitializedFieldInUnion(*Field);
1423 // Emit warnings for missing struct field initializers.
1424 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1425 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1426 !DeclType->isUnionType()) {
1427 // It is possible we have one or more unnamed bitfields remaining.
1428 // Find first (if any) named field and emit warning.
1429 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1431 if (!it->isUnnamedBitfield()) {
1432 SemaRef.Diag(IList->getSourceRange().getEnd(),
1433 diag::warn_missing_field_initializers) << it->getName();
1439 // Check that any remaining fields can be value-initialized.
1440 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1441 !Field->getType()->isIncompleteArrayType()) {
1442 // FIXME: Should check for holes left by designated initializers too.
1443 for (; Field != FieldEnd && !hadError; ++Field) {
1444 if (!Field->isUnnamedBitfield())
1445 CheckValueInitializable(
1446 InitializedEntity::InitializeMember(*Field, &Entity));
1450 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
1451 Index >= IList->getNumInits())
1454 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1461 InitializedEntity MemberEntity =
1462 InitializedEntity::InitializeMember(*Field, &Entity);
1464 if (isa<InitListExpr>(IList->getInit(Index)))
1465 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1466 StructuredList, StructuredIndex);
1468 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
1469 StructuredList, StructuredIndex);
1472 /// \brief Expand a field designator that refers to a member of an
1473 /// anonymous struct or union into a series of field designators that
1474 /// refers to the field within the appropriate subobject.
1476 static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1477 DesignatedInitExpr *DIE,
1479 IndirectFieldDecl *IndirectField) {
1480 typedef DesignatedInitExpr::Designator Designator;
1482 // Build the replacement designators.
1483 SmallVector<Designator, 4> Replacements;
1484 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1485 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1487 Replacements.push_back(Designator((IdentifierInfo *)0,
1488 DIE->getDesignator(DesigIdx)->getDotLoc(),
1489 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1491 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1493 assert(isa<FieldDecl>(*PI));
1494 Replacements.back().setField(cast<FieldDecl>(*PI));
1497 // Expand the current designator into the set of replacement
1498 // designators, so we have a full subobject path down to where the
1499 // member of the anonymous struct/union is actually stored.
1500 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
1501 &Replacements[0] + Replacements.size());
1504 /// \brief Given an implicit anonymous field, search the IndirectField that
1505 /// corresponds to FieldName.
1506 static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1507 IdentifierInfo *FieldName) {
1511 assert(AnonField->isAnonymousStructOrUnion());
1512 Decl *NextDecl = AnonField->getNextDeclInContext();
1513 while (IndirectFieldDecl *IF =
1514 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
1515 if (FieldName == IF->getAnonField()->getIdentifier())
1517 NextDecl = NextDecl->getNextDeclInContext();
1522 static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1523 DesignatedInitExpr *DIE) {
1524 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1525 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1526 for (unsigned I = 0; I < NumIndexExprs; ++I)
1527 IndexExprs[I] = DIE->getSubExpr(I + 1);
1528 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1529 DIE->size(), IndexExprs,
1530 DIE->getEqualOrColonLoc(),
1531 DIE->usesGNUSyntax(), DIE->getInit());
1536 // Callback to only accept typo corrections that are for field members of
1537 // the given struct or union.
1538 class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1540 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1543 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1544 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1545 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1554 /// @brief Check the well-formedness of a C99 designated initializer.
1556 /// Determines whether the designated initializer @p DIE, which
1557 /// resides at the given @p Index within the initializer list @p
1558 /// IList, is well-formed for a current object of type @p DeclType
1559 /// (C99 6.7.8). The actual subobject that this designator refers to
1560 /// within the current subobject is returned in either
1561 /// @p NextField or @p NextElementIndex (whichever is appropriate).
1563 /// @param IList The initializer list in which this designated
1564 /// initializer occurs.
1566 /// @param DIE The designated initializer expression.
1568 /// @param DesigIdx The index of the current designator.
1570 /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
1571 /// into which the designation in @p DIE should refer.
1573 /// @param NextField If non-NULL and the first designator in @p DIE is
1574 /// a field, this will be set to the field declaration corresponding
1575 /// to the field named by the designator.
1577 /// @param NextElementIndex If non-NULL and the first designator in @p
1578 /// DIE is an array designator or GNU array-range designator, this
1579 /// will be set to the last index initialized by this designator.
1581 /// @param Index Index into @p IList where the designated initializer
1584 /// @param StructuredList The initializer list expression that
1585 /// describes all of the subobject initializers in the order they'll
1586 /// actually be initialized.
1588 /// @returns true if there was an error, false otherwise.
1590 InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
1591 InitListExpr *IList,
1592 DesignatedInitExpr *DIE,
1594 QualType &CurrentObjectType,
1595 RecordDecl::field_iterator *NextField,
1596 llvm::APSInt *NextElementIndex,
1598 InitListExpr *StructuredList,
1599 unsigned &StructuredIndex,
1600 bool FinishSubobjectInit,
1601 bool TopLevelObject) {
1602 if (DesigIdx == DIE->size()) {
1603 // Check the actual initialization for the designated object type.
1604 bool prevHadError = hadError;
1606 // Temporarily remove the designator expression from the
1607 // initializer list that the child calls see, so that we don't try
1608 // to re-process the designator.
1609 unsigned OldIndex = Index;
1610 IList->setInit(OldIndex, DIE->getInit());
1612 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
1613 StructuredList, StructuredIndex);
1615 // Restore the designated initializer expression in the syntactic
1616 // form of the initializer list.
1617 if (IList->getInit(OldIndex) != DIE->getInit())
1618 DIE->setInit(IList->getInit(OldIndex));
1619 IList->setInit(OldIndex, DIE);
1621 return hadError && !prevHadError;
1624 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
1625 bool IsFirstDesignator = (DesigIdx == 0);
1627 assert((IsFirstDesignator || StructuredList) &&
1628 "Need a non-designated initializer list to start from");
1630 // Determine the structural initializer list that corresponds to the
1631 // current subobject.
1632 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
1633 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1634 StructuredList, StructuredIndex,
1635 SourceRange(D->getStartLocation(),
1636 DIE->getSourceRange().getEnd()));
1637 assert(StructuredList && "Expected a structured initializer list");
1640 if (D->isFieldDesignator()) {
1643 // If a designator has the form
1647 // then the current object (defined below) shall have
1648 // structure or union type and the identifier shall be the
1649 // name of a member of that type.
1650 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
1652 SourceLocation Loc = D->getDotLoc();
1653 if (Loc.isInvalid())
1654 Loc = D->getFieldLoc();
1656 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1657 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
1662 // Note: we perform a linear search of the fields here, despite
1663 // the fact that we have a faster lookup method, because we always
1664 // need to compute the field's index.
1665 FieldDecl *KnownField = D->getField();
1666 IdentifierInfo *FieldName = D->getFieldName();
1667 unsigned FieldIndex = 0;
1668 RecordDecl::field_iterator
1669 Field = RT->getDecl()->field_begin(),
1670 FieldEnd = RT->getDecl()->field_end();
1671 for (; Field != FieldEnd; ++Field) {
1672 if (Field->isUnnamedBitfield())
1675 // If we find a field representing an anonymous field, look in the
1676 // IndirectFieldDecl that follow for the designated initializer.
1677 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1678 if (IndirectFieldDecl *IF =
1679 FindIndirectFieldDesignator(*Field, FieldName)) {
1680 // In verify mode, don't modify the original.
1682 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
1683 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1684 D = DIE->getDesignator(DesigIdx);
1688 if (KnownField && KnownField == *Field)
1690 if (FieldName && FieldName == Field->getIdentifier())
1696 if (Field == FieldEnd) {
1699 return true; // No typo correction when just trying this out.
1702 // There was no normal field in the struct with the designated
1703 // name. Perform another lookup for this name, which may find
1704 // something that we can't designate (e.g., a member function),
1705 // may find nothing, or may find a member of an anonymous
1707 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
1708 FieldDecl *ReplacementField = 0;
1709 if (Lookup.first == Lookup.second) {
1710 // Name lookup didn't find anything. Determine whether this
1711 // was a typo for another field name.
1712 FieldInitializerValidatorCCC Validator(RT->getDecl());
1713 TypoCorrection Corrected = SemaRef.CorrectTypo(
1714 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1715 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator,
1718 std::string CorrectedStr(
1719 Corrected.getAsString(SemaRef.getLangOpts()));
1720 std::string CorrectedQuotedStr(
1721 Corrected.getQuoted(SemaRef.getLangOpts()));
1722 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
1723 SemaRef.Diag(D->getFieldLoc(),
1724 diag::err_field_designator_unknown_suggest)
1725 << FieldName << CurrentObjectType << CorrectedQuotedStr
1726 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
1727 SemaRef.Diag(ReplacementField->getLocation(),
1728 diag::note_previous_decl) << CorrectedQuotedStr;
1731 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1732 << FieldName << CurrentObjectType;
1738 if (!ReplacementField) {
1739 // Name lookup found something, but it wasn't a field.
1740 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
1742 SemaRef.Diag((*Lookup.first)->getLocation(),
1743 diag::note_field_designator_found);
1749 // The replacement field comes from typo correction; find it
1750 // in the list of fields.
1752 Field = RT->getDecl()->field_begin();
1753 for (; Field != FieldEnd; ++Field) {
1754 if (Field->isUnnamedBitfield())
1757 if (ReplacementField == *Field ||
1758 Field->getIdentifier() == ReplacementField->getIdentifier())
1766 // All of the fields of a union are located at the same place in
1767 // the initializer list.
1768 if (RT->getDecl()->isUnion()) {
1771 StructuredList->setInitializedFieldInUnion(*Field);
1774 // Make sure we can use this declaration.
1777 InvalidUse = !SemaRef.CanUseDecl(*Field);
1779 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1786 // Update the designator with the field declaration.
1787 D->setField(*Field);
1789 // Make sure that our non-designated initializer list has space
1790 // for a subobject corresponding to this field.
1791 if (FieldIndex >= StructuredList->getNumInits())
1792 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1795 // This designator names a flexible array member.
1796 if (Field->getType()->isIncompleteArrayType()) {
1797 bool Invalid = false;
1798 if ((DesigIdx + 1) != DIE->size()) {
1799 // We can't designate an object within the flexible array
1800 // member (because GCC doesn't allow it).
1802 DesignatedInitExpr::Designator *NextD
1803 = DIE->getDesignator(DesigIdx + 1);
1804 SemaRef.Diag(NextD->getStartLocation(),
1805 diag::err_designator_into_flexible_array_member)
1806 << SourceRange(NextD->getStartLocation(),
1807 DIE->getSourceRange().getEnd());
1808 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1814 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1815 !isa<StringLiteral>(DIE->getInit())) {
1816 // The initializer is not an initializer list.
1818 SemaRef.Diag(DIE->getInit()->getLocStart(),
1819 diag::err_flexible_array_init_needs_braces)
1820 << DIE->getInit()->getSourceRange();
1821 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1827 // Check GNU flexible array initializer.
1828 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1837 // Initialize the array.
1838 bool prevHadError = hadError;
1839 unsigned newStructuredIndex = FieldIndex;
1840 unsigned OldIndex = Index;
1841 IList->setInit(Index, DIE->getInit());
1843 InitializedEntity MemberEntity =
1844 InitializedEntity::InitializeMember(*Field, &Entity);
1845 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1846 StructuredList, newStructuredIndex);
1848 IList->setInit(OldIndex, DIE);
1849 if (hadError && !prevHadError) {
1854 StructuredIndex = FieldIndex;
1858 // Recurse to check later designated subobjects.
1859 QualType FieldType = Field->getType();
1860 unsigned newStructuredIndex = FieldIndex;
1862 InitializedEntity MemberEntity =
1863 InitializedEntity::InitializeMember(*Field, &Entity);
1864 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1865 FieldType, 0, 0, Index,
1866 StructuredList, newStructuredIndex,
1871 // Find the position of the next field to be initialized in this
1876 // If this the first designator, our caller will continue checking
1877 // the rest of this struct/class/union subobject.
1878 if (IsFirstDesignator) {
1881 StructuredIndex = FieldIndex;
1885 if (!FinishSubobjectInit)
1888 // We've already initialized something in the union; we're done.
1889 if (RT->getDecl()->isUnion())
1892 // Check the remaining fields within this class/struct/union subobject.
1893 bool prevHadError = hadError;
1895 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
1896 StructuredList, FieldIndex);
1897 return hadError && !prevHadError;
1902 // If a designator has the form
1904 // [ constant-expression ]
1906 // then the current object (defined below) shall have array
1907 // type and the expression shall be an integer constant
1908 // expression. If the array is of unknown size, any
1909 // nonnegative value is valid.
1911 // Additionally, cope with the GNU extension that permits
1912 // designators of the form
1914 // [ constant-expression ... constant-expression ]
1915 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
1918 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1919 << CurrentObjectType;
1924 Expr *IndexExpr = 0;
1925 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1926 if (D->isArrayDesignator()) {
1927 IndexExpr = DIE->getArrayIndex(*D);
1928 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
1929 DesignatedEndIndex = DesignatedStartIndex;
1931 assert(D->isArrayRangeDesignator() && "Need array-range designator");
1933 DesignatedStartIndex =
1934 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
1935 DesignatedEndIndex =
1936 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
1937 IndexExpr = DIE->getArrayRangeEnd(*D);
1939 // Codegen can't handle evaluating array range designators that have side
1940 // effects, because we replicate the AST value for each initialized element.
1941 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1942 // elements with something that has a side effect, so codegen can emit an
1943 // "error unsupported" error instead of miscompiling the app.
1944 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
1945 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
1946 FullyStructuredList->sawArrayRangeDesignator();
1949 if (isa<ConstantArrayType>(AT)) {
1950 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
1951 DesignatedStartIndex
1952 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1953 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1955 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1956 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1957 if (DesignatedEndIndex >= MaxElements) {
1959 SemaRef.Diag(IndexExpr->getLocStart(),
1960 diag::err_array_designator_too_large)
1961 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1962 << IndexExpr->getSourceRange();
1967 // Make sure the bit-widths and signedness match.
1968 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1970 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
1971 else if (DesignatedStartIndex.getBitWidth() <
1972 DesignatedEndIndex.getBitWidth())
1973 DesignatedStartIndex
1974 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1975 DesignatedStartIndex.setIsUnsigned(true);
1976 DesignatedEndIndex.setIsUnsigned(true);
1979 // Make sure that our non-designated initializer list has space
1980 // for a subobject corresponding to this array element.
1982 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
1983 StructuredList->resizeInits(SemaRef.Context,
1984 DesignatedEndIndex.getZExtValue() + 1);
1986 // Repeatedly perform subobject initializations in the range
1987 // [DesignatedStartIndex, DesignatedEndIndex].
1989 // Move to the next designator
1990 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1991 unsigned OldIndex = Index;
1993 InitializedEntity ElementEntity =
1994 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1996 while (DesignatedStartIndex <= DesignatedEndIndex) {
1997 // Recurse to check later designated subobjects.
1998 QualType ElementType = AT->getElementType();
2001 ElementEntity.setElementIndex(ElementIndex);
2002 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2003 ElementType, 0, 0, Index,
2004 StructuredList, ElementIndex,
2005 (DesignatedStartIndex == DesignatedEndIndex),
2009 // Move to the next index in the array that we'll be initializing.
2010 ++DesignatedStartIndex;
2011 ElementIndex = DesignatedStartIndex.getZExtValue();
2014 // If this the first designator, our caller will continue checking
2015 // the rest of this array subobject.
2016 if (IsFirstDesignator) {
2017 if (NextElementIndex)
2018 *NextElementIndex = DesignatedStartIndex;
2019 StructuredIndex = ElementIndex;
2023 if (!FinishSubobjectInit)
2026 // Check the remaining elements within this array subobject.
2027 bool prevHadError = hadError;
2028 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
2029 /*SubobjectIsDesignatorContext=*/false, Index,
2030 StructuredList, ElementIndex);
2031 return hadError && !prevHadError;
2034 // Get the structured initializer list for a subobject of type
2035 // @p CurrentObjectType.
2037 InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2038 QualType CurrentObjectType,
2039 InitListExpr *StructuredList,
2040 unsigned StructuredIndex,
2041 SourceRange InitRange) {
2043 return 0; // No structured list in verification-only mode.
2044 Expr *ExistingInit = 0;
2045 if (!StructuredList)
2046 ExistingInit = SyntacticToSemantic.lookup(IList);
2047 else if (StructuredIndex < StructuredList->getNumInits())
2048 ExistingInit = StructuredList->getInit(StructuredIndex);
2050 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2054 // We are creating an initializer list that initializes the
2055 // subobjects of the current object, but there was already an
2056 // initialization that completely initialized the current
2057 // subobject, e.g., by a compound literal:
2059 // struct X { int a, b; };
2060 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2062 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2063 // designated initializer re-initializes the whole
2064 // subobject [0], overwriting previous initializers.
2065 SemaRef.Diag(InitRange.getBegin(),
2066 diag::warn_subobject_initializer_overrides)
2068 SemaRef.Diag(ExistingInit->getLocStart(),
2069 diag::note_previous_initializer)
2070 << /*FIXME:has side effects=*/0
2071 << ExistingInit->getSourceRange();
2074 InitListExpr *Result
2075 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2076 InitRange.getBegin(), MultiExprArg(),
2077 InitRange.getEnd());
2079 QualType ResultType = CurrentObjectType;
2080 if (!ResultType->isArrayType())
2081 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2082 Result->setType(ResultType);
2084 // Pre-allocate storage for the structured initializer list.
2085 unsigned NumElements = 0;
2086 unsigned NumInits = 0;
2087 bool GotNumInits = false;
2088 if (!StructuredList) {
2089 NumInits = IList->getNumInits();
2091 } else if (Index < IList->getNumInits()) {
2092 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
2093 NumInits = SubList->getNumInits();
2098 if (const ArrayType *AType
2099 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2100 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2101 NumElements = CAType->getSize().getZExtValue();
2102 // Simple heuristic so that we don't allocate a very large
2103 // initializer with many empty entries at the end.
2104 if (GotNumInits && NumElements > NumInits)
2107 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
2108 NumElements = VType->getNumElements();
2109 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
2110 RecordDecl *RDecl = RType->getDecl();
2111 if (RDecl->isUnion())
2114 NumElements = std::distance(RDecl->field_begin(),
2115 RDecl->field_end());
2118 Result->reserveInits(SemaRef.Context, NumElements);
2120 // Link this new initializer list into the structured initializer
2123 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
2125 Result->setSyntacticForm(IList);
2126 SyntacticToSemantic[IList] = Result;
2132 /// Update the initializer at index @p StructuredIndex within the
2133 /// structured initializer list to the value @p expr.
2134 void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2135 unsigned &StructuredIndex,
2137 // No structured initializer list to update
2138 if (!StructuredList)
2141 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2142 StructuredIndex, expr)) {
2143 // This initializer overwrites a previous initializer. Warn.
2144 SemaRef.Diag(expr->getLocStart(),
2145 diag::warn_initializer_overrides)
2146 << expr->getSourceRange();
2147 SemaRef.Diag(PrevInit->getLocStart(),
2148 diag::note_previous_initializer)
2149 << /*FIXME:has side effects=*/0
2150 << PrevInit->getSourceRange();
2156 /// Check that the given Index expression is a valid array designator
2157 /// value. This is essentially just a wrapper around
2158 /// VerifyIntegerConstantExpression that also checks for negative values
2159 /// and produces a reasonable diagnostic if there is a
2160 /// failure. Returns the index expression, possibly with an implicit cast
2161 /// added, on success. If everything went okay, Value will receive the
2162 /// value of the constant expression.
2164 CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
2165 SourceLocation Loc = Index->getLocStart();
2167 // Make sure this is an integer constant expression.
2168 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2169 if (Result.isInvalid())
2172 if (Value.isSigned() && Value.isNegative())
2173 return S.Diag(Loc, diag::err_array_designator_negative)
2174 << Value.toString(10) << Index->getSourceRange();
2176 Value.setIsUnsigned(true);
2180 ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
2184 typedef DesignatedInitExpr::Designator ASTDesignator;
2186 bool Invalid = false;
2187 SmallVector<ASTDesignator, 32> Designators;
2188 SmallVector<Expr *, 32> InitExpressions;
2190 // Build designators and check array designator expressions.
2191 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2192 const Designator &D = Desig.getDesignator(Idx);
2193 switch (D.getKind()) {
2194 case Designator::FieldDesignator:
2195 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
2199 case Designator::ArrayDesignator: {
2200 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2201 llvm::APSInt IndexValue;
2202 if (!Index->isTypeDependent() && !Index->isValueDependent())
2203 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2207 Designators.push_back(ASTDesignator(InitExpressions.size(),
2209 D.getRBracketLoc()));
2210 InitExpressions.push_back(Index);
2215 case Designator::ArrayRangeDesignator: {
2216 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2217 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2218 llvm::APSInt StartValue;
2219 llvm::APSInt EndValue;
2220 bool StartDependent = StartIndex->isTypeDependent() ||
2221 StartIndex->isValueDependent();
2222 bool EndDependent = EndIndex->isTypeDependent() ||
2223 EndIndex->isValueDependent();
2224 if (!StartDependent)
2226 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2228 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2230 if (!StartIndex || !EndIndex)
2233 // Make sure we're comparing values with the same bit width.
2234 if (StartDependent || EndDependent) {
2235 // Nothing to compute.
2236 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
2237 EndValue = EndValue.extend(StartValue.getBitWidth());
2238 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
2239 StartValue = StartValue.extend(EndValue.getBitWidth());
2241 if (!StartDependent && !EndDependent && EndValue < StartValue) {
2242 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
2243 << StartValue.toString(10) << EndValue.toString(10)
2244 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2247 Designators.push_back(ASTDesignator(InitExpressions.size(),
2250 D.getRBracketLoc()));
2251 InitExpressions.push_back(StartIndex);
2252 InitExpressions.push_back(EndIndex);
2260 if (Invalid || Init.isInvalid())
2263 // Clear out the expressions within the designation.
2264 Desig.ClearExprs(*this);
2266 DesignatedInitExpr *DIE
2267 = DesignatedInitExpr::Create(Context,
2268 Designators.data(), Designators.size(),
2269 InitExpressions, Loc, GNUSyntax,
2270 Init.takeAs<Expr>());
2272 if (!getLangOpts().C99)
2273 Diag(DIE->getLocStart(), diag::ext_designated_init)
2274 << DIE->getSourceRange();
2279 //===----------------------------------------------------------------------===//
2280 // Initialization entity
2281 //===----------------------------------------------------------------------===//
2283 InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
2284 const InitializedEntity &Parent)
2285 : Parent(&Parent), Index(Index)
2287 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2288 Kind = EK_ArrayElement;
2289 Type = AT->getElementType();
2290 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
2291 Kind = EK_VectorElement;
2292 Type = VT->getElementType();
2294 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2295 assert(CT && "Unexpected type");
2296 Kind = EK_ComplexElement;
2297 Type = CT->getElementType();
2301 InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
2302 CXXBaseSpecifier *Base,
2303 bool IsInheritedVirtualBase)
2305 InitializedEntity Result;
2306 Result.Kind = EK_Base;
2307 Result.Base = reinterpret_cast<uintptr_t>(Base);
2308 if (IsInheritedVirtualBase)
2309 Result.Base |= 0x01;
2311 Result.Type = Base->getType();
2315 DeclarationName InitializedEntity::getName() const {
2316 switch (getKind()) {
2317 case EK_Parameter: {
2318 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2319 return (D ? D->getDeclName() : DeclarationName());
2324 return VariableOrMember->getDeclName();
2326 case EK_LambdaCapture:
2327 return Capture.Var->getDeclName();
2335 case EK_ArrayElement:
2336 case EK_VectorElement:
2337 case EK_ComplexElement:
2338 case EK_BlockElement:
2339 return DeclarationName();
2342 llvm_unreachable("Invalid EntityKind!");
2345 DeclaratorDecl *InitializedEntity::getDecl() const {
2346 switch (getKind()) {
2349 return VariableOrMember;
2352 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2360 case EK_ArrayElement:
2361 case EK_VectorElement:
2362 case EK_ComplexElement:
2363 case EK_BlockElement:
2364 case EK_LambdaCapture:
2368 llvm_unreachable("Invalid EntityKind!");
2371 bool InitializedEntity::allowsNRVO() const {
2372 switch (getKind()) {
2375 return LocAndNRVO.NRVO;
2384 case EK_ArrayElement:
2385 case EK_VectorElement:
2386 case EK_ComplexElement:
2387 case EK_BlockElement:
2388 case EK_LambdaCapture:
2395 //===----------------------------------------------------------------------===//
2396 // Initialization sequence
2397 //===----------------------------------------------------------------------===//
2399 void InitializationSequence::Step::Destroy() {
2401 case SK_ResolveAddressOfOverloadedFunction:
2402 case SK_CastDerivedToBaseRValue:
2403 case SK_CastDerivedToBaseXValue:
2404 case SK_CastDerivedToBaseLValue:
2405 case SK_BindReference:
2406 case SK_BindReferenceToTemporary:
2407 case SK_ExtraneousCopyToTemporary:
2408 case SK_UserConversion:
2409 case SK_QualificationConversionRValue:
2410 case SK_QualificationConversionXValue:
2411 case SK_QualificationConversionLValue:
2412 case SK_ListInitialization:
2413 case SK_ListConstructorCall:
2414 case SK_UnwrapInitList:
2415 case SK_RewrapInitList:
2416 case SK_ConstructorInitialization:
2417 case SK_ZeroInitialization:
2418 case SK_CAssignment:
2420 case SK_ObjCObjectConversion:
2422 case SK_ParenthesizedArrayInit:
2423 case SK_PassByIndirectCopyRestore:
2424 case SK_PassByIndirectRestore:
2425 case SK_ProduceObjCObject:
2426 case SK_StdInitializerList:
2429 case SK_ConversionSequence:
2434 bool InitializationSequence::isDirectReferenceBinding() const {
2435 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
2438 bool InitializationSequence::isAmbiguous() const {
2442 switch (getFailureKind()) {
2443 case FK_TooManyInitsForReference:
2444 case FK_ArrayNeedsInitList:
2445 case FK_ArrayNeedsInitListOrStringLiteral:
2446 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2447 case FK_NonConstLValueReferenceBindingToTemporary:
2448 case FK_NonConstLValueReferenceBindingToUnrelated:
2449 case FK_RValueReferenceBindingToLValue:
2450 case FK_ReferenceInitDropsQualifiers:
2451 case FK_ReferenceInitFailed:
2452 case FK_ConversionFailed:
2453 case FK_ConversionFromPropertyFailed:
2454 case FK_TooManyInitsForScalar:
2455 case FK_ReferenceBindingToInitList:
2456 case FK_InitListBadDestinationType:
2457 case FK_DefaultInitOfConst:
2459 case FK_ArrayTypeMismatch:
2460 case FK_NonConstantArrayInit:
2461 case FK_ListInitializationFailed:
2462 case FK_VariableLengthArrayHasInitializer:
2463 case FK_PlaceholderType:
2464 case FK_InitListElementCopyFailure:
2465 case FK_ExplicitConstructor:
2468 case FK_ReferenceInitOverloadFailed:
2469 case FK_UserConversionOverloadFailed:
2470 case FK_ConstructorOverloadFailed:
2471 case FK_ListConstructorOverloadFailed:
2472 return FailedOverloadResult == OR_Ambiguous;
2475 llvm_unreachable("Invalid EntityKind!");
2478 bool InitializationSequence::isConstructorInitialization() const {
2479 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2483 InitializationSequence
2484 ::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2485 DeclAccessPair Found,
2486 bool HadMultipleCandidates) {
2488 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2489 S.Type = Function->getType();
2490 S.Function.HadMultipleCandidates = HadMultipleCandidates;
2491 S.Function.Function = Function;
2492 S.Function.FoundDecl = Found;
2496 void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2500 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2501 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2502 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
2508 void InitializationSequence::AddReferenceBindingStep(QualType T,
2509 bool BindingTemporary) {
2511 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2516 void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2518 S.Kind = SK_ExtraneousCopyToTemporary;
2524 InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2525 DeclAccessPair FoundDecl,
2527 bool HadMultipleCandidates) {
2529 S.Kind = SK_UserConversion;
2531 S.Function.HadMultipleCandidates = HadMultipleCandidates;
2532 S.Function.Function = Function;
2533 S.Function.FoundDecl = FoundDecl;
2537 void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2540 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
2543 S.Kind = SK_QualificationConversionRValue;
2546 S.Kind = SK_QualificationConversionXValue;
2549 S.Kind = SK_QualificationConversionLValue;
2556 void InitializationSequence::AddConversionSequenceStep(
2557 const ImplicitConversionSequence &ICS,
2560 S.Kind = SK_ConversionSequence;
2562 S.ICS = new ImplicitConversionSequence(ICS);
2566 void InitializationSequence::AddListInitializationStep(QualType T) {
2568 S.Kind = SK_ListInitialization;
2574 InitializationSequence
2575 ::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2576 AccessSpecifier Access,
2578 bool HadMultipleCandidates,
2579 bool FromInitList, bool AsInitList) {
2581 S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2582 : SK_ConstructorInitialization;
2584 S.Function.HadMultipleCandidates = HadMultipleCandidates;
2585 S.Function.Function = Constructor;
2586 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
2590 void InitializationSequence::AddZeroInitializationStep(QualType T) {
2592 S.Kind = SK_ZeroInitialization;
2597 void InitializationSequence::AddCAssignmentStep(QualType T) {
2599 S.Kind = SK_CAssignment;
2604 void InitializationSequence::AddStringInitStep(QualType T) {
2606 S.Kind = SK_StringInit;
2611 void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2613 S.Kind = SK_ObjCObjectConversion;
2618 void InitializationSequence::AddArrayInitStep(QualType T) {
2620 S.Kind = SK_ArrayInit;
2625 void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2627 S.Kind = SK_ParenthesizedArrayInit;
2632 void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2635 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2636 : SK_PassByIndirectRestore);
2641 void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2643 S.Kind = SK_ProduceObjCObject;
2648 void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2650 S.Kind = SK_StdInitializerList;
2655 void InitializationSequence::RewrapReferenceInitList(QualType T,
2656 InitListExpr *Syntactic) {
2657 assert(Syntactic->getNumInits() == 1 &&
2658 "Can only rewrap trivial init lists.");
2660 S.Kind = SK_UnwrapInitList;
2661 S.Type = Syntactic->getInit(0)->getType();
2662 Steps.insert(Steps.begin(), S);
2664 S.Kind = SK_RewrapInitList;
2666 S.WrappingSyntacticList = Syntactic;
2670 void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2671 OverloadingResult Result) {
2672 setSequenceKind(FailedSequence);
2673 this->Failure = Failure;
2674 this->FailedOverloadResult = Result;
2677 //===----------------------------------------------------------------------===//
2678 // Attempt initialization
2679 //===----------------------------------------------------------------------===//
2681 static void MaybeProduceObjCObject(Sema &S,
2682 InitializationSequence &Sequence,
2683 const InitializedEntity &Entity) {
2684 if (!S.getLangOpts().ObjCAutoRefCount) return;
2686 /// When initializing a parameter, produce the value if it's marked
2687 /// __attribute__((ns_consumed)).
2688 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2689 if (!Entity.isParameterConsumed())
2692 assert(Entity.getType()->isObjCRetainableType() &&
2693 "consuming an object of unretainable type?");
2694 Sequence.AddProduceObjCObjectStep(Entity.getType());
2696 /// When initializing a return value, if the return type is a
2697 /// retainable type, then returns need to immediately retain the
2698 /// object. If an autorelease is required, it will be done at the
2700 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2701 if (!Entity.getType()->isObjCRetainableType())
2704 Sequence.AddProduceObjCObjectStep(Entity.getType());
2708 /// \brief When initializing from init list via constructor, handle
2709 /// initialization of an object of type std::initializer_list<T>.
2711 /// \return true if we have handled initialization of an object of type
2712 /// std::initializer_list<T>, false otherwise.
2713 static bool TryInitializerListConstruction(Sema &S,
2716 InitializationSequence &Sequence) {
2718 if (!S.isStdInitializerList(DestType, &E))
2721 // Check that each individual element can be copy-constructed. But since we
2722 // have no place to store further information, we'll recalculate everything
2724 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2725 S.Context.getConstantArrayType(E,
2726 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2727 List->getNumInits()),
2728 ArrayType::Normal, 0));
2729 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2731 for (unsigned i = 0, n = List->getNumInits(); i < n; ++i) {
2732 Element.setElementIndex(i);
2733 if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) {
2735 InitializationSequence::FK_InitListElementCopyFailure);
2739 Sequence.AddStdInitializerListConstructionStep(DestType);
2743 static OverloadingResult
2744 ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
2745 Expr **Args, unsigned NumArgs,
2746 OverloadCandidateSet &CandidateSet,
2747 DeclContext::lookup_iterator Con,
2748 DeclContext::lookup_iterator ConEnd,
2749 OverloadCandidateSet::iterator &Best,
2750 bool CopyInitializing, bool AllowExplicit,
2751 bool OnlyListConstructors, bool InitListSyntax) {
2752 CandidateSet.clear();
2754 for (; Con != ConEnd; ++Con) {
2755 NamedDecl *D = *Con;
2756 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2757 bool SuppressUserConversions = false;
2759 // Find the constructor (which may be a template).
2760 CXXConstructorDecl *Constructor = 0;
2761 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2762 if (ConstructorTmpl)
2763 Constructor = cast<CXXConstructorDecl>(
2764 ConstructorTmpl->getTemplatedDecl());
2766 Constructor = cast<CXXConstructorDecl>(D);
2768 // If we're performing copy initialization using a copy constructor, we
2769 // suppress user-defined conversions on the arguments. We do the same for
2770 // move constructors.
2771 if ((CopyInitializing || (InitListSyntax && NumArgs == 1)) &&
2772 Constructor->isCopyOrMoveConstructor())
2773 SuppressUserConversions = true;
2776 if (!Constructor->isInvalidDecl() &&
2777 (AllowExplicit || !Constructor->isExplicit()) &&
2778 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
2779 if (ConstructorTmpl)
2780 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2782 llvm::makeArrayRef(Args, NumArgs),
2783 CandidateSet, SuppressUserConversions);
2785 // C++ [over.match.copy]p1:
2786 // - When initializing a temporary to be bound to the first parameter
2787 // of a constructor that takes a reference to possibly cv-qualified
2788 // T as its first argument, called with a single argument in the
2789 // context of direct-initialization, explicit conversion functions
2790 // are also considered.
2791 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
2793 Constructor->isCopyOrMoveConstructor();
2794 S.AddOverloadCandidate(Constructor, FoundDecl,
2795 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
2796 SuppressUserConversions,
2797 /*PartialOverloading=*/false,
2798 /*AllowExplicit=*/AllowExplicitConv);
2803 // Perform overload resolution and return the result.
2804 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
2807 /// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2808 /// enumerates the constructors of the initialized entity and performs overload
2809 /// resolution to select the best.
2810 /// If InitListSyntax is true, this is list-initialization of a non-aggregate
2812 static void TryConstructorInitialization(Sema &S,
2813 const InitializedEntity &Entity,
2814 const InitializationKind &Kind,
2815 Expr **Args, unsigned NumArgs,
2817 InitializationSequence &Sequence,
2818 bool InitListSyntax = false) {
2819 assert((!InitListSyntax || (NumArgs == 1 && isa<InitListExpr>(Args[0]))) &&
2820 "InitListSyntax must come with a single initializer list argument.");
2822 // The type we're constructing needs to be complete.
2823 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
2824 Sequence.setIncompleteTypeFailure(DestType);
2828 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2829 assert(DestRecordType && "Constructor initialization requires record type");
2830 CXXRecordDecl *DestRecordDecl
2831 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2833 // Build the candidate set directly in the initialization sequence
2834 // structure, so that it will persist if we fail.
2835 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2837 // Determine whether we are allowed to call explicit constructors or
2838 // explicit conversion operators.
2839 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
2840 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
2842 // - Otherwise, if T is a class type, constructors are considered. The
2843 // applicable constructors are enumerated, and the best one is chosen
2844 // through overload resolution.
2845 DeclContext::lookup_iterator ConStart, ConEnd;
2846 llvm::tie(ConStart, ConEnd) = S.LookupConstructors(DestRecordDecl);
2848 OverloadingResult Result = OR_No_Viable_Function;
2849 OverloadCandidateSet::iterator Best;
2850 bool AsInitializerList = false;
2852 // C++11 [over.match.list]p1:
2853 // When objects of non-aggregate type T are list-initialized, overload
2854 // resolution selects the constructor in two phases:
2855 // - Initially, the candidate functions are the initializer-list
2856 // constructors of the class T and the argument list consists of the
2857 // initializer list as a single argument.
2858 if (InitListSyntax) {
2859 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
2860 AsInitializerList = true;
2862 // If the initializer list has no elements and T has a default constructor,
2863 // the first phase is omitted.
2864 if (ILE->getNumInits() != 0 ||
2865 (!DestRecordDecl->hasDeclaredDefaultConstructor() &&
2866 !DestRecordDecl->needsImplicitDefaultConstructor()))
2867 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
2868 CandidateSet, ConStart, ConEnd, Best,
2869 CopyInitialization, AllowExplicit,
2870 /*OnlyListConstructor=*/true,
2873 // Time to unwrap the init list.
2874 Args = ILE->getInits();
2875 NumArgs = ILE->getNumInits();
2878 // C++11 [over.match.list]p1:
2879 // - If no viable initializer-list constructor is found, overload resolution
2880 // is performed again, where the candidate functions are all the
2881 // constructors of the class T and the argument list consists of the
2882 // elements of the initializer list.
2883 if (Result == OR_No_Viable_Function) {
2884 AsInitializerList = false;
2885 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
2886 CandidateSet, ConStart, ConEnd, Best,
2887 CopyInitialization, AllowExplicit,
2888 /*OnlyListConstructors=*/false,
2892 Sequence.SetOverloadFailure(InitListSyntax ?
2893 InitializationSequence::FK_ListConstructorOverloadFailed :
2894 InitializationSequence::FK_ConstructorOverloadFailed,
2899 // C++11 [dcl.init]p6:
2900 // If a program calls for the default initialization of an object
2901 // of a const-qualified type T, T shall be a class type with a
2902 // user-provided default constructor.
2903 if (Kind.getKind() == InitializationKind::IK_Default &&
2904 Entity.getType().isConstQualified() &&
2905 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
2906 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2910 // C++11 [over.match.list]p1:
2911 // In copy-list-initialization, if an explicit constructor is chosen, the
2912 // initializer is ill-formed.
2913 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
2914 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
2915 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
2919 // Add the constructor initialization step. Any cv-qualification conversion is
2920 // subsumed by the initialization.
2921 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2922 Sequence.AddConstructorInitializationStep(CtorDecl,
2923 Best->FoundDecl.getAccess(),
2924 DestType, HadMultipleCandidates,
2925 InitListSyntax, AsInitializerList);
2929 ResolveOverloadedFunctionForReferenceBinding(Sema &S,
2931 QualType &SourceType,
2932 QualType &UnqualifiedSourceType,
2933 QualType UnqualifiedTargetType,
2934 InitializationSequence &Sequence) {
2935 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
2936 S.Context.OverloadTy) {
2937 DeclAccessPair Found;
2938 bool HadMultipleCandidates = false;
2939 if (FunctionDecl *Fn
2940 = S.ResolveAddressOfOverloadedFunction(Initializer,
2941 UnqualifiedTargetType,
2943 &HadMultipleCandidates)) {
2944 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
2945 HadMultipleCandidates);
2946 SourceType = Fn->getType();
2947 UnqualifiedSourceType = SourceType.getUnqualifiedType();
2948 } else if (!UnqualifiedTargetType->isRecordType()) {
2949 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2956 static void TryReferenceInitializationCore(Sema &S,
2957 const InitializedEntity &Entity,
2958 const InitializationKind &Kind,
2960 QualType cv1T1, QualType T1,
2962 QualType cv2T2, QualType T2,
2964 InitializationSequence &Sequence);
2966 static void TryValueInitialization(Sema &S,
2967 const InitializedEntity &Entity,
2968 const InitializationKind &Kind,
2969 InitializationSequence &Sequence,
2970 InitListExpr *InitList = 0);
2972 static void TryListInitialization(Sema &S,
2973 const InitializedEntity &Entity,
2974 const InitializationKind &Kind,
2975 InitListExpr *InitList,
2976 InitializationSequence &Sequence);
2978 /// \brief Attempt list initialization of a reference.
2979 static void TryReferenceListInitialization(Sema &S,
2980 const InitializedEntity &Entity,
2981 const InitializationKind &Kind,
2982 InitListExpr *InitList,
2983 InitializationSequence &Sequence)
2985 // First, catch C++03 where this isn't possible.
2986 if (!S.getLangOpts().CPlusPlus0x) {
2987 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2991 QualType DestType = Entity.getType();
2992 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2994 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
2996 // Reference initialization via an initializer list works thus:
2997 // If the initializer list consists of a single element that is
2998 // reference-related to the referenced type, bind directly to that element
2999 // (possibly creating temporaries).
3000 // Otherwise, initialize a temporary with the initializer list and
3002 if (InitList->getNumInits() == 1) {
3003 Expr *Initializer = InitList->getInit(0);
3004 QualType cv2T2 = Initializer->getType();
3006 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3008 // If this fails, creating a temporary wouldn't work either.
3009 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3013 SourceLocation DeclLoc = Initializer->getLocStart();
3014 bool dummy1, dummy2, dummy3;
3015 Sema::ReferenceCompareResult RefRelationship
3016 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3018 if (RefRelationship >= Sema::Ref_Related) {
3019 // Try to bind the reference here.
3020 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3021 T1Quals, cv2T2, T2, T2Quals, Sequence);
3023 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3028 // Not reference-related. Create a temporary and bind to that.
3029 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3031 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3033 if (DestType->isRValueReferenceType() ||
3034 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3035 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3038 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3042 /// \brief Attempt list initialization (C++0x [dcl.init.list])
3043 static void TryListInitialization(Sema &S,
3044 const InitializedEntity &Entity,
3045 const InitializationKind &Kind,
3046 InitListExpr *InitList,
3047 InitializationSequence &Sequence) {
3048 QualType DestType = Entity.getType();
3050 // C++ doesn't allow scalar initialization with more than one argument.
3051 // But C99 complex numbers are scalars and it makes sense there.
3052 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
3053 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3054 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3057 if (DestType->isReferenceType()) {
3058 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
3061 if (DestType->isRecordType()) {
3062 if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
3063 Sequence.setIncompleteTypeFailure(DestType);
3067 // C++11 [dcl.init.list]p3:
3068 // - If T is an aggregate, aggregate initialization is performed.
3069 if (!DestType->isAggregateType()) {
3070 if (S.getLangOpts().CPlusPlus0x) {
3071 // - Otherwise, if the initializer list has no elements and T is a
3072 // class type with a default constructor, the object is
3073 // value-initialized.
3074 if (InitList->getNumInits() == 0) {
3075 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
3076 if (RD->hasDeclaredDefaultConstructor() ||
3077 RD->needsImplicitDefaultConstructor()) {
3078 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3083 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3084 // an initializer_list object constructed [...]
3085 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3088 // - Otherwise, if T is a class type, constructors are considered.
3089 Expr *Arg = InitList;
3090 TryConstructorInitialization(S, Entity, Kind, &Arg, 1, DestType,
3091 Sequence, /*InitListSyntax*/true);
3094 InitializationSequence::FK_InitListBadDestinationType);
3099 InitListChecker CheckInitList(S, Entity, InitList,
3100 DestType, /*VerifyOnly=*/true,
3101 Kind.getKind() != InitializationKind::IK_DirectList ||
3102 !S.getLangOpts().CPlusPlus0x);
3103 if (CheckInitList.HadError()) {
3104 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3108 // Add the list initialization step with the built init list.
3109 Sequence.AddListInitializationStep(DestType);
3112 /// \brief Try a reference initialization that involves calling a conversion
3114 static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3115 const InitializedEntity &Entity,
3116 const InitializationKind &Kind,
3119 InitializationSequence &Sequence) {
3120 QualType DestType = Entity.getType();
3121 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3122 QualType T1 = cv1T1.getUnqualifiedType();
3123 QualType cv2T2 = Initializer->getType();
3124 QualType T2 = cv2T2.getUnqualifiedType();
3127 bool ObjCConversion;
3128 bool ObjCLifetimeConversion;
3129 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
3130 T1, T2, DerivedToBase,
3132 ObjCLifetimeConversion) &&
3133 "Must have incompatible references when binding via conversion");
3134 (void)DerivedToBase;
3135 (void)ObjCConversion;
3136 (void)ObjCLifetimeConversion;
3138 // Build the candidate set directly in the initialization sequence
3139 // structure, so that it will persist if we fail.
3140 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3141 CandidateSet.clear();
3143 // Determine whether we are allowed to call explicit constructors or
3144 // explicit conversion operators.
3145 bool AllowExplicit = Kind.AllowExplicit();
3146 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctions();
3148 const RecordType *T1RecordType = 0;
3149 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3150 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
3151 // The type we're converting to is a class type. Enumerate its constructors
3152 // to see if there is a suitable conversion.
3153 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
3155 DeclContext::lookup_iterator Con, ConEnd;
3156 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
3157 Con != ConEnd; ++Con) {
3158 NamedDecl *D = *Con;
3159 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3161 // Find the constructor (which may be a template).
3162 CXXConstructorDecl *Constructor = 0;
3163 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3164 if (ConstructorTmpl)
3165 Constructor = cast<CXXConstructorDecl>(
3166 ConstructorTmpl->getTemplatedDecl());
3168 Constructor = cast<CXXConstructorDecl>(D);
3170 if (!Constructor->isInvalidDecl() &&
3171 Constructor->isConvertingConstructor(AllowExplicit)) {
3172 if (ConstructorTmpl)
3173 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3175 Initializer, CandidateSet,
3176 /*SuppressUserConversions=*/true);
3178 S.AddOverloadCandidate(Constructor, FoundDecl,
3179 Initializer, CandidateSet,
3180 /*SuppressUserConversions=*/true);
3184 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3185 return OR_No_Viable_Function;
3187 const RecordType *T2RecordType = 0;
3188 if ((T2RecordType = T2->getAs<RecordType>()) &&
3189 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
3190 // The type we're converting from is a class type, enumerate its conversion
3192 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3194 const UnresolvedSetImpl *Conversions
3195 = T2RecordDecl->getVisibleConversionFunctions();
3196 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
3197 E = Conversions->end(); I != E; ++I) {
3199 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3200 if (isa<UsingShadowDecl>(D))
3201 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3203 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3204 CXXConversionDecl *Conv;
3206 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3208 Conv = cast<CXXConversionDecl>(D);
3210 // If the conversion function doesn't return a reference type,
3211 // it can't be considered for this conversion unless we're allowed to
3212 // consider rvalues.
3213 // FIXME: Do we need to make sure that we only consider conversion
3214 // candidates with reference-compatible results? That might be needed to
3216 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
3217 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3219 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3220 ActingDC, Initializer,
3221 DestType, CandidateSet);
3223 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
3224 Initializer, DestType, CandidateSet);
3228 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3229 return OR_No_Viable_Function;
3231 SourceLocation DeclLoc = Initializer->getLocStart();
3233 // Perform overload resolution. If it fails, return the failed result.
3234 OverloadCandidateSet::iterator Best;
3235 if (OverloadingResult Result
3236 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
3239 FunctionDecl *Function = Best->Function;
3241 // This is the overload that will actually be used for the initialization, so
3243 S.MarkFunctionReferenced(DeclLoc, Function);
3245 // Compute the returned type of the conversion.
3246 if (isa<CXXConversionDecl>(Function))
3247 T2 = Function->getResultType();
3251 // Add the user-defined conversion step.
3252 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3253 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3254 T2.getNonLValueExprType(S.Context),
3255 HadMultipleCandidates);
3257 // Determine whether we need to perform derived-to-base or
3258 // cv-qualification adjustments.
3259 ExprValueKind VK = VK_RValue;
3260 if (T2->isLValueReferenceType())
3262 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
3263 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
3265 bool NewDerivedToBase = false;
3266 bool NewObjCConversion = false;
3267 bool NewObjCLifetimeConversion = false;
3268 Sema::ReferenceCompareResult NewRefRelationship
3269 = S.CompareReferenceRelationship(DeclLoc, T1,
3270 T2.getNonLValueExprType(S.Context),
3271 NewDerivedToBase, NewObjCConversion,
3272 NewObjCLifetimeConversion);
3273 if (NewRefRelationship == Sema::Ref_Incompatible) {
3274 // If the type we've converted to is not reference-related to the
3275 // type we're looking for, then there is another conversion step
3276 // we need to perform to produce a temporary of the right type
3277 // that we'll be binding to.
3278 ImplicitConversionSequence ICS;
3280 ICS.Standard = Best->FinalConversion;
3281 T2 = ICS.Standard.getToType(2);
3282 Sequence.AddConversionSequenceStep(ICS, T2);
3283 } else if (NewDerivedToBase)
3284 Sequence.AddDerivedToBaseCastStep(
3285 S.Context.getQualifiedType(T1,
3286 T2.getNonReferenceType().getQualifiers()),
3288 else if (NewObjCConversion)
3289 Sequence.AddObjCObjectConversionStep(
3290 S.Context.getQualifiedType(T1,
3291 T2.getNonReferenceType().getQualifiers()));
3293 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
3294 Sequence.AddQualificationConversionStep(cv1T1, VK);
3296 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3300 static void CheckCXX98CompatAccessibleCopy(Sema &S,
3301 const InitializedEntity &Entity,
3304 /// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3305 static void TryReferenceInitialization(Sema &S,
3306 const InitializedEntity &Entity,
3307 const InitializationKind &Kind,
3309 InitializationSequence &Sequence) {
3310 QualType DestType = Entity.getType();
3311 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3313 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3314 QualType cv2T2 = Initializer->getType();
3316 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3318 // If the initializer is the address of an overloaded function, try
3319 // to resolve the overloaded function. If all goes well, T2 is the
3320 // type of the resulting function.
3321 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3325 // Delegate everything else to a subfunction.
3326 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3327 T1Quals, cv2T2, T2, T2Quals, Sequence);
3330 /// \brief Reference initialization without resolving overloaded functions.
3331 static void TryReferenceInitializationCore(Sema &S,
3332 const InitializedEntity &Entity,
3333 const InitializationKind &Kind,
3335 QualType cv1T1, QualType T1,
3337 QualType cv2T2, QualType T2,
3339 InitializationSequence &Sequence) {
3340 QualType DestType = Entity.getType();
3341 SourceLocation DeclLoc = Initializer->getLocStart();
3342 // Compute some basic properties of the types and the initializer.
3343 bool isLValueRef = DestType->isLValueReferenceType();
3344 bool isRValueRef = !isLValueRef;
3345 bool DerivedToBase = false;
3346 bool ObjCConversion = false;
3347 bool ObjCLifetimeConversion = false;
3348 Expr::Classification InitCategory = Initializer->Classify(S.Context);
3349 Sema::ReferenceCompareResult RefRelationship
3350 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
3351 ObjCConversion, ObjCLifetimeConversion);
3353 // C++0x [dcl.init.ref]p5:
3354 // A reference to type "cv1 T1" is initialized by an expression of type
3355 // "cv2 T2" as follows:
3357 // - If the reference is an lvalue reference and the initializer
3359 // Note the analogous bullet points for rvlaue refs to functions. Because
3360 // there are no function rvalues in C++, rvalue refs to functions are treated
3361 // like lvalue refs.
3362 OverloadingResult ConvOvlResult = OR_Success;
3363 bool T1Function = T1->isFunctionType();
3364 if (isLValueRef || T1Function) {
3365 if (InitCategory.isLValue() &&
3366 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
3367 (Kind.isCStyleOrFunctionalCast() &&
3368 RefRelationship == Sema::Ref_Related))) {
3369 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
3370 // reference-compatible with "cv2 T2," or
3372 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
3373 // bit-field when we're determining whether the reference initialization
3374 // can occur. However, we do pay attention to whether it is a bit-field
3375 // to decide whether we're actually binding to a temporary created from
3378 Sequence.AddDerivedToBaseCastStep(
3379 S.Context.getQualifiedType(T1, T2Quals),
3381 else if (ObjCConversion)
3382 Sequence.AddObjCObjectConversionStep(
3383 S.Context.getQualifiedType(T1, T2Quals));
3385 if (T1Quals != T2Quals)
3386 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
3387 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
3388 (Initializer->getBitField() || Initializer->refersToVectorElement());
3389 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
3393 // - has a class type (i.e., T2 is a class type), where T1 is not
3394 // reference-related to T2, and can be implicitly converted to an
3395 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3396 // with "cv3 T3" (this conversion is selected by enumerating the
3397 // applicable conversion functions (13.3.1.6) and choosing the best
3398 // one through overload resolution (13.3)),
3399 // If we have an rvalue ref to function type here, the rhs must be
3401 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3402 (isLValueRef || InitCategory.isRValue())) {
3403 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
3405 /*AllowRValues=*/isRValueRef,
3407 if (ConvOvlResult == OR_Success)
3409 if (ConvOvlResult != OR_No_Viable_Function) {
3410 Sequence.SetOverloadFailure(
3411 InitializationSequence::FK_ReferenceInitOverloadFailed,
3417 // - Otherwise, the reference shall be an lvalue reference to a
3418 // non-volatile const type (i.e., cv1 shall be const), or the reference
3419 // shall be an rvalue reference.
3420 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
3421 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3422 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3423 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3424 Sequence.SetOverloadFailure(
3425 InitializationSequence::FK_ReferenceInitOverloadFailed,
3428 Sequence.SetFailed(InitCategory.isLValue()
3429 ? (RefRelationship == Sema::Ref_Related
3430 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3431 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3432 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3437 // - If the initializer expression
3438 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3439 // "cv1 T1" is reference-compatible with "cv2 T2"
3440 // Note: functions are handled below.
3442 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
3443 (Kind.isCStyleOrFunctionalCast() &&
3444 RefRelationship == Sema::Ref_Related)) &&
3445 (InitCategory.isXValue() ||
3446 (InitCategory.isPRValue() && T2->isRecordType()) ||
3447 (InitCategory.isPRValue() && T2->isArrayType()))) {
3448 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3449 if (InitCategory.isPRValue() && T2->isRecordType()) {
3450 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3451 // compiler the freedom to perform a copy here or bind to the
3452 // object, while C++0x requires that we bind directly to the
3453 // object. Hence, we always bind to the object without making an
3454 // extra copy. However, in C++03 requires that we check for the
3455 // presence of a suitable copy constructor:
3457 // The constructor that would be used to make the copy shall
3458 // be callable whether or not the copy is actually done.
3459 if (!S.getLangOpts().CPlusPlus0x && !S.getLangOpts().MicrosoftExt)
3460 Sequence.AddExtraneousCopyToTemporary(cv2T2);
3461 else if (S.getLangOpts().CPlusPlus0x)
3462 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
3466 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3468 else if (ObjCConversion)
3469 Sequence.AddObjCObjectConversionStep(
3470 S.Context.getQualifiedType(T1, T2Quals));
3472 if (T1Quals != T2Quals)
3473 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
3474 Sequence.AddReferenceBindingStep(cv1T1,
3475 /*bindingTemporary=*/InitCategory.isPRValue());
3479 // - has a class type (i.e., T2 is a class type), where T1 is not
3480 // reference-related to T2, and can be implicitly converted to an
3481 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3482 // where "cv1 T1" is reference-compatible with "cv3 T3",
3483 if (T2->isRecordType()) {
3484 if (RefRelationship == Sema::Ref_Incompatible) {
3485 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3487 /*AllowRValues=*/true,
3490 Sequence.SetOverloadFailure(
3491 InitializationSequence::FK_ReferenceInitOverloadFailed,
3497 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3501 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
3502 // from the initializer expression using the rules for a non-reference
3503 // copy initialization (8.5). The reference is then bound to the
3506 // Determine whether we are allowed to call explicit constructors or
3507 // explicit conversion operators.
3508 bool AllowExplicit = Kind.AllowExplicit();
3510 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3512 ImplicitConversionSequence ICS
3513 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
3514 /*SuppressUserConversions*/ false,
3516 /*FIXME:InOverloadResolution=*/false,
3517 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3518 /*AllowObjCWritebackConversion=*/false);
3521 // FIXME: Use the conversion function set stored in ICS to turn
3522 // this into an overloading ambiguity diagnostic. However, we need
3523 // to keep that set as an OverloadCandidateSet rather than as some
3524 // other kind of set.
3525 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3526 Sequence.SetOverloadFailure(
3527 InitializationSequence::FK_ReferenceInitOverloadFailed,
3529 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3530 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3532 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
3535 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
3538 // [...] If T1 is reference-related to T2, cv1 must be the
3539 // same cv-qualification as, or greater cv-qualification
3540 // than, cv2; otherwise, the program is ill-formed.
3541 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3542 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
3543 if (RefRelationship == Sema::Ref_Related &&
3544 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
3545 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3549 // [...] If T1 is reference-related to T2 and the reference is an rvalue
3550 // reference, the initializer expression shall not be an lvalue.
3551 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
3552 InitCategory.isLValue()) {
3554 InitializationSequence::FK_RValueReferenceBindingToLValue);
3558 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3562 /// \brief Attempt character array initialization from a string literal
3563 /// (C++ [dcl.init.string], C99 6.7.8).
3564 static void TryStringLiteralInitialization(Sema &S,
3565 const InitializedEntity &Entity,
3566 const InitializationKind &Kind,
3568 InitializationSequence &Sequence) {
3569 Sequence.AddStringInitStep(Entity.getType());
3572 /// \brief Attempt value initialization (C++ [dcl.init]p7).
3573 static void TryValueInitialization(Sema &S,
3574 const InitializedEntity &Entity,
3575 const InitializationKind &Kind,
3576 InitializationSequence &Sequence,
3577 InitListExpr *InitList) {
3578 assert((!InitList || InitList->getNumInits() == 0) &&
3579 "Shouldn't use value-init for non-empty init lists");
3581 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
3583 // To value-initialize an object of type T means:
3584 QualType T = Entity.getType();
3586 // -- if T is an array type, then each element is value-initialized;
3587 T = S.Context.getBaseElementType(T);
3589 if (const RecordType *RT = T->getAs<RecordType>()) {
3590 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3591 bool NeedZeroInitialization = true;
3592 if (!S.getLangOpts().CPlusPlus0x) {
3594 // -- if T is a class type (clause 9) with a user-declared constructor
3595 // (12.1), then the default constructor for T is called (and the
3596 // initialization is ill-formed if T has no accessible default
3598 if (ClassDecl->hasUserDeclaredConstructor())
3599 NeedZeroInitialization = false;
3602 // -- if T is a class type (clause 9) with either no default constructor
3603 // (12.1 [class.ctor]) or a default constructor that is user-provided
3604 // or deleted, then the object is default-initialized;
3605 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3606 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
3607 NeedZeroInitialization = false;
3610 // -- if T is a (possibly cv-qualified) non-union class type without a
3611 // user-provided or deleted default constructor, then the object is
3612 // zero-initialized and, if T has a non-trivial default constructor,
3613 // default-initialized;
3614 // The 'non-union' here was removed by DR1502. The 'non-trivial default
3615 // constructor' part was removed by DR1507.
3616 if (NeedZeroInitialization)
3617 Sequence.AddZeroInitializationStep(Entity.getType());
3619 // If this is list-value-initialization, pass the empty init list on when
3620 // building the constructor call. This affects the semantics of a few
3621 // things (such as whether an explicit default constructor can be called).
3622 Expr *InitListAsExpr = InitList;
3623 Expr **Args = InitList ? &InitListAsExpr : 0;
3624 unsigned NumArgs = InitList ? 1 : 0;
3625 bool InitListSyntax = InitList;
3627 return TryConstructorInitialization(S, Entity, Kind, Args, NumArgs, T,
3628 Sequence, InitListSyntax);
3632 Sequence.AddZeroInitializationStep(Entity.getType());
3635 /// \brief Attempt default initialization (C++ [dcl.init]p6).
3636 static void TryDefaultInitialization(Sema &S,
3637 const InitializedEntity &Entity,
3638 const InitializationKind &Kind,
3639 InitializationSequence &Sequence) {
3640 assert(Kind.getKind() == InitializationKind::IK_Default);
3642 // C++ [dcl.init]p6:
3643 // To default-initialize an object of type T means:
3644 // - if T is an array type, each element is default-initialized;
3645 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3647 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3648 // constructor for T is called (and the initialization is ill-formed if
3649 // T has no accessible default constructor);
3650 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
3651 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3655 // - otherwise, no initialization is performed.
3657 // If a program calls for the default initialization of an object of
3658 // a const-qualified type T, T shall be a class type with a user-provided
3659 // default constructor.
3660 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
3661 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3665 // If the destination type has a lifetime property, zero-initialize it.
3666 if (DestType.getQualifiers().hasObjCLifetime()) {
3667 Sequence.AddZeroInitializationStep(Entity.getType());
3672 /// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3673 /// which enumerates all conversion functions and performs overload resolution
3674 /// to select the best.
3675 static void TryUserDefinedConversion(Sema &S,
3676 const InitializedEntity &Entity,
3677 const InitializationKind &Kind,
3679 InitializationSequence &Sequence) {
3680 QualType DestType = Entity.getType();
3681 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3682 QualType SourceType = Initializer->getType();
3683 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3684 "Must have a class type to perform a user-defined conversion");
3686 // Build the candidate set directly in the initialization sequence
3687 // structure, so that it will persist if we fail.
3688 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3689 CandidateSet.clear();
3691 // Determine whether we are allowed to call explicit constructors or
3692 // explicit conversion operators.
3693 bool AllowExplicit = Kind.AllowExplicit();
3695 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3696 // The type we're converting to is a class type. Enumerate its constructors
3697 // to see if there is a suitable conversion.
3698 CXXRecordDecl *DestRecordDecl
3699 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3701 // Try to complete the type we're converting to.
3702 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
3703 DeclContext::lookup_iterator ConOrig, ConEndOrig;
3704 llvm::tie(ConOrig, ConEndOrig) = S.LookupConstructors(DestRecordDecl);
3705 // The container holding the constructors can under certain conditions
3706 // be changed while iterating. To be safe we copy the lookup results
3707 // to a new container.
3708 SmallVector<NamedDecl*, 8> CopyOfCon(ConOrig, ConEndOrig);
3709 for (SmallVector<NamedDecl*, 8>::iterator
3710 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
3711 Con != ConEnd; ++Con) {
3712 NamedDecl *D = *Con;
3713 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3715 // Find the constructor (which may be a template).
3716 CXXConstructorDecl *Constructor = 0;
3717 FunctionTemplateDecl *ConstructorTmpl
3718 = dyn_cast<FunctionTemplateDecl>(D);
3719 if (ConstructorTmpl)
3720 Constructor = cast<CXXConstructorDecl>(
3721 ConstructorTmpl->getTemplatedDecl());
3723 Constructor = cast<CXXConstructorDecl>(D);
3725 if (!Constructor->isInvalidDecl() &&
3726 Constructor->isConvertingConstructor(AllowExplicit)) {
3727 if (ConstructorTmpl)
3728 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3730 Initializer, CandidateSet,
3731 /*SuppressUserConversions=*/true);
3733 S.AddOverloadCandidate(Constructor, FoundDecl,
3734 Initializer, CandidateSet,
3735 /*SuppressUserConversions=*/true);
3741 SourceLocation DeclLoc = Initializer->getLocStart();
3743 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3744 // The type we're converting from is a class type, enumerate its conversion
3747 // We can only enumerate the conversion functions for a complete type; if
3748 // the type isn't complete, simply skip this step.
3749 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3750 CXXRecordDecl *SourceRecordDecl
3751 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
3753 const UnresolvedSetImpl *Conversions
3754 = SourceRecordDecl->getVisibleConversionFunctions();
3755 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
3756 E = Conversions->end();
3759 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3760 if (isa<UsingShadowDecl>(D))
3761 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3763 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3764 CXXConversionDecl *Conv;
3766 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3768 Conv = cast<CXXConversionDecl>(D);
3770 if (AllowExplicit || !Conv->isExplicit()) {
3772 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3773 ActingDC, Initializer, DestType,
3776 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
3777 Initializer, DestType, CandidateSet);
3783 // Perform overload resolution. If it fails, return the failed result.
3784 OverloadCandidateSet::iterator Best;
3785 if (OverloadingResult Result
3786 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
3787 Sequence.SetOverloadFailure(
3788 InitializationSequence::FK_UserConversionOverloadFailed,
3793 FunctionDecl *Function = Best->Function;
3794 S.MarkFunctionReferenced(DeclLoc, Function);
3795 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3797 if (isa<CXXConstructorDecl>(Function)) {
3798 // Add the user-defined conversion step. Any cv-qualification conversion is
3799 // subsumed by the initialization. Per DR5, the created temporary is of the
3800 // cv-unqualified type of the destination.
3801 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3802 DestType.getUnqualifiedType(),
3803 HadMultipleCandidates);
3807 // Add the user-defined conversion step that calls the conversion function.
3808 QualType ConvType = Function->getCallResultType();
3809 if (ConvType->getAs<RecordType>()) {
3810 // If we're converting to a class type, there may be an copy of
3811 // the resulting temporary object (possible to create an object of
3812 // a base class type). That copy is not a separate conversion, so
3813 // we just make a note of the actual destination type (possibly a
3814 // base class of the type returned by the conversion function) and
3815 // let the user-defined conversion step handle the conversion.
3816 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3817 HadMultipleCandidates);
3821 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3822 HadMultipleCandidates);
3824 // If the conversion following the call to the conversion function
3825 // is interesting, add it as a separate step.
3826 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3827 Best->FinalConversion.Third) {
3828 ImplicitConversionSequence ICS;
3830 ICS.Standard = Best->FinalConversion;
3831 Sequence.AddConversionSequenceStep(ICS, DestType);
3835 /// The non-zero enum values here are indexes into diagnostic alternatives.
3836 enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3838 /// Determines whether this expression is an acceptable ICR source.
3839 static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3842 e = e->IgnoreParens();
3844 // Skip address-of nodes.
3845 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3846 if (op->getOpcode() == UO_AddrOf)
3847 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
3849 // Skip certain casts.
3850 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3851 switch (ce->getCastKind()) {
3854 case CK_LValueBitCast:
3856 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
3858 case CK_ArrayToPointerDecay:
3859 return IIK_nonscalar;
3861 case CK_NullToPointer:
3868 // If we have a declaration reference, it had better be a local variable.
3869 } else if (isa<DeclRefExpr>(e)) {
3870 if (!isAddressOf) return IIK_nonlocal;
3872 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3873 if (!var) return IIK_nonlocal;
3875 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
3877 // If we have a conditional operator, check both sides.
3878 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
3879 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
3882 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
3884 // These are never scalar.
3885 } else if (isa<ArraySubscriptExpr>(e)) {
3886 return IIK_nonscalar;
3888 // Otherwise, it needs to be a null pointer constant.
3890 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3891 ? IIK_okay : IIK_nonlocal);
3894 return IIK_nonlocal;
3897 /// Check whether the given expression is a valid operand for an
3898 /// indirect copy/restore.
3899 static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3900 assert(src->isRValue());
3902 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
3903 if (iik == IIK_okay) return;
3905 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3906 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3907 << src->getSourceRange();
3910 /// \brief Determine whether we have compatible array types for the
3911 /// purposes of GNU by-copy array initialization.
3912 static bool hasCompatibleArrayTypes(ASTContext &Context,
3913 const ArrayType *Dest,
3914 const ArrayType *Source) {
3915 // If the source and destination array types are equivalent, we're
3917 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3920 // Make sure that the element types are the same.
3921 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3924 // The only mismatch we allow is when the destination is an
3925 // incomplete array type and the source is a constant array type.
3926 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3929 static bool tryObjCWritebackConversion(Sema &S,
3930 InitializationSequence &Sequence,
3931 const InitializedEntity &Entity,
3932 Expr *Initializer) {
3933 bool ArrayDecay = false;
3934 QualType ArgType = Initializer->getType();
3935 QualType ArgPointee;
3936 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3938 ArgPointee = ArgArrayType->getElementType();
3939 ArgType = S.Context.getPointerType(ArgPointee);
3942 // Handle write-back conversion.
3943 QualType ConvertedArgType;
3944 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3948 // We should copy unless we're passing to an argument explicitly
3950 bool ShouldCopy = true;
3951 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3952 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3954 // Do we need an lvalue conversion?
3955 if (ArrayDecay || Initializer->isGLValue()) {
3956 ImplicitConversionSequence ICS;
3958 ICS.Standard.setAsIdentityConversion();
3960 QualType ResultType;
3962 ICS.Standard.First = ICK_Array_To_Pointer;
3963 ResultType = S.Context.getPointerType(ArgPointee);
3965 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3966 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3969 Sequence.AddConversionSequenceStep(ICS, ResultType);
3972 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3976 InitializationSequence::InitializationSequence(Sema &S,
3977 const InitializedEntity &Entity,
3978 const InitializationKind &Kind,
3981 : FailedCandidateSet(Kind.getLocation()) {
3982 ASTContext &Context = S.Context;
3984 // C++0x [dcl.init]p16:
3985 // The semantics of initializers are as follows. The destination type is
3986 // the type of the object or reference being initialized and the source
3987 // type is the type of the initializer expression. The source type is not
3988 // defined when the initializer is a braced-init-list or when it is a
3989 // parenthesized list of expressions.
3990 QualType DestType = Entity.getType();
3992 if (DestType->isDependentType() ||
3993 Expr::hasAnyTypeDependentArguments(llvm::makeArrayRef(Args, NumArgs))) {
3994 SequenceKind = DependentSequence;
3998 // Almost everything is a normal sequence.
3999 setSequenceKind(NormalSequence);
4001 for (unsigned I = 0; I != NumArgs; ++I)
4002 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4003 // FIXME: should we be doing this here?
4004 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4005 if (result.isInvalid()) {
4006 SetFailed(FK_PlaceholderType);
4009 Args[I] = result.take();
4013 QualType SourceType;
4014 Expr *Initializer = 0;
4016 Initializer = Args[0];
4017 if (!isa<InitListExpr>(Initializer))
4018 SourceType = Initializer->getType();
4021 // - If the initializer is a (non-parenthesized) braced-init-list, the
4022 // object is list-initialized (8.5.4).
4023 if (Kind.getKind() != InitializationKind::IK_Direct) {
4024 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4025 TryListInitialization(S, Entity, Kind, InitList, *this);
4030 // - If the destination type is a reference type, see 8.5.3.
4031 if (DestType->isReferenceType()) {
4032 // C++0x [dcl.init.ref]p1:
4033 // A variable declared to be a T& or T&&, that is, "reference to type T"
4034 // (8.3.2), shall be initialized by an object, or function, of type T or
4035 // by an object that can be converted into a T.
4036 // (Therefore, multiple arguments are not permitted.)
4038 SetFailed(FK_TooManyInitsForReference);
4040 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
4044 // - If the initializer is (), the object is value-initialized.
4045 if (Kind.getKind() == InitializationKind::IK_Value ||
4046 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
4047 TryValueInitialization(S, Entity, Kind, *this);
4051 // Handle default initialization.
4052 if (Kind.getKind() == InitializationKind::IK_Default) {
4053 TryDefaultInitialization(S, Entity, Kind, *this);
4057 // - If the destination type is an array of characters, an array of
4058 // char16_t, an array of char32_t, or an array of wchar_t, and the
4059 // initializer is a string literal, see 8.5.2.
4060 // - Otherwise, if the destination type is an array, the program is
4062 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
4063 if (Initializer && isa<VariableArrayType>(DestAT)) {
4064 SetFailed(FK_VariableLengthArrayHasInitializer);
4068 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
4069 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4073 // Note: as an GNU C extension, we allow initialization of an
4074 // array from a compound literal that creates an array of the same
4075 // type, so long as the initializer has no side effects.
4076 if (!S.getLangOpts().CPlusPlus && Initializer &&
4077 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4078 Initializer->getType()->isArrayType()) {
4079 const ArrayType *SourceAT
4080 = Context.getAsArrayType(Initializer->getType());
4081 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
4082 SetFailed(FK_ArrayTypeMismatch);
4083 else if (Initializer->HasSideEffects(S.Context))
4084 SetFailed(FK_NonConstantArrayInit);
4086 AddArrayInitStep(DestType);
4089 // Note: as a GNU C++ extension, we allow list-initialization of a
4090 // class member of array type from a parenthesized initializer list.
4091 else if (S.getLangOpts().CPlusPlus &&
4092 Entity.getKind() == InitializedEntity::EK_Member &&
4093 Initializer && isa<InitListExpr>(Initializer)) {
4094 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4096 AddParenthesizedArrayInitStep(DestType);
4097 } else if (DestAT->getElementType()->isAnyCharacterType())
4098 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
4100 SetFailed(FK_ArrayNeedsInitList);
4105 // Determine whether we should consider writeback conversions for
4107 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
4108 Entity.getKind() == InitializedEntity::EK_Parameter;
4110 // We're at the end of the line for C: it's either a write-back conversion
4111 // or it's a C assignment. There's no need to check anything else.
4112 if (!S.getLangOpts().CPlusPlus) {
4113 // If allowed, check whether this is an Objective-C writeback conversion.
4114 if (allowObjCWritebackConversion &&
4115 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
4119 // Handle initialization in C
4120 AddCAssignmentStep(DestType);
4121 MaybeProduceObjCObject(S, *this, Entity);
4125 assert(S.getLangOpts().CPlusPlus);
4127 // - If the destination type is a (possibly cv-qualified) class type:
4128 if (DestType->isRecordType()) {
4129 // - If the initialization is direct-initialization, or if it is
4130 // copy-initialization where the cv-unqualified version of the
4131 // source type is the same class as, or a derived class of, the
4132 // class of the destination, constructors are considered. [...]
4133 if (Kind.getKind() == InitializationKind::IK_Direct ||
4134 (Kind.getKind() == InitializationKind::IK_Copy &&
4135 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4136 S.IsDerivedFrom(SourceType, DestType))))
4137 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
4138 Entity.getType(), *this);
4139 // - Otherwise (i.e., for the remaining copy-initialization cases),
4140 // user-defined conversion sequences that can convert from the source
4141 // type to the destination type or (when a conversion function is
4142 // used) to a derived class thereof are enumerated as described in
4143 // 13.3.1.4, and the best one is chosen through overload resolution
4146 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4151 SetFailed(FK_TooManyInitsForScalar);
4154 assert(NumArgs == 1 && "Zero-argument case handled above");
4156 // - Otherwise, if the source type is a (possibly cv-qualified) class
4157 // type, conversion functions are considered.
4158 if (!SourceType.isNull() && SourceType->isRecordType()) {
4159 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4160 MaybeProduceObjCObject(S, *this, Entity);
4164 // - Otherwise, the initial value of the object being initialized is the
4165 // (possibly converted) value of the initializer expression. Standard
4166 // conversions (Clause 4) will be used, if necessary, to convert the
4167 // initializer expression to the cv-unqualified version of the
4168 // destination type; no user-defined conversions are considered.
4170 ImplicitConversionSequence ICS
4171 = S.TryImplicitConversion(Initializer, Entity.getType(),
4172 /*SuppressUserConversions*/true,
4173 /*AllowExplicitConversions*/ false,
4174 /*InOverloadResolution*/ false,
4175 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4176 allowObjCWritebackConversion);
4178 if (ICS.isStandard() &&
4179 ICS.Standard.Second == ICK_Writeback_Conversion) {
4180 // Objective-C ARC writeback conversion.
4182 // We should copy unless we're passing to an argument explicitly
4184 bool ShouldCopy = true;
4185 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4186 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4188 // If there was an lvalue adjustment, add it as a separate conversion.
4189 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4190 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4191 ImplicitConversionSequence LvalueICS;
4192 LvalueICS.setStandard();
4193 LvalueICS.Standard.setAsIdentityConversion();
4194 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4195 LvalueICS.Standard.First = ICS.Standard.First;
4196 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
4199 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4200 } else if (ICS.isBad()) {
4202 if (Initializer->getType() == Context.OverloadTy &&
4203 !S.ResolveAddressOfOverloadedFunction(Initializer
4204 , DestType, false, dap))
4205 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4207 SetFailed(InitializationSequence::FK_ConversionFailed);
4209 AddConversionSequenceStep(ICS, Entity.getType());
4211 MaybeProduceObjCObject(S, *this, Entity);
4215 InitializationSequence::~InitializationSequence() {
4216 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
4217 StepEnd = Steps.end();
4218 Step != StepEnd; ++Step)
4222 //===----------------------------------------------------------------------===//
4223 // Perform initialization
4224 //===----------------------------------------------------------------------===//
4225 static Sema::AssignmentAction
4226 getAssignmentAction(const InitializedEntity &Entity) {
4227 switch(Entity.getKind()) {
4228 case InitializedEntity::EK_Variable:
4229 case InitializedEntity::EK_New:
4230 case InitializedEntity::EK_Exception:
4231 case InitializedEntity::EK_Base:
4232 case InitializedEntity::EK_Delegating:
4233 return Sema::AA_Initializing;
4235 case InitializedEntity::EK_Parameter:
4236 if (Entity.getDecl() &&
4237 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4238 return Sema::AA_Sending;
4240 return Sema::AA_Passing;
4242 case InitializedEntity::EK_Result:
4243 return Sema::AA_Returning;
4245 case InitializedEntity::EK_Temporary:
4246 // FIXME: Can we tell apart casting vs. converting?
4247 return Sema::AA_Casting;
4249 case InitializedEntity::EK_Member:
4250 case InitializedEntity::EK_ArrayElement:
4251 case InitializedEntity::EK_VectorElement:
4252 case InitializedEntity::EK_ComplexElement:
4253 case InitializedEntity::EK_BlockElement:
4254 case InitializedEntity::EK_LambdaCapture:
4255 return Sema::AA_Initializing;
4258 llvm_unreachable("Invalid EntityKind!");
4261 /// \brief Whether we should binding a created object as a temporary when
4262 /// initializing the given entity.
4263 static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
4264 switch (Entity.getKind()) {
4265 case InitializedEntity::EK_ArrayElement:
4266 case InitializedEntity::EK_Member:
4267 case InitializedEntity::EK_Result:
4268 case InitializedEntity::EK_New:
4269 case InitializedEntity::EK_Variable:
4270 case InitializedEntity::EK_Base:
4271 case InitializedEntity::EK_Delegating:
4272 case InitializedEntity::EK_VectorElement:
4273 case InitializedEntity::EK_ComplexElement:
4274 case InitializedEntity::EK_Exception:
4275 case InitializedEntity::EK_BlockElement:
4276 case InitializedEntity::EK_LambdaCapture:
4279 case InitializedEntity::EK_Parameter:
4280 case InitializedEntity::EK_Temporary:
4284 llvm_unreachable("missed an InitializedEntity kind?");
4287 /// \brief Whether the given entity, when initialized with an object
4288 /// created for that initialization, requires destruction.
4289 static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4290 switch (Entity.getKind()) {
4291 case InitializedEntity::EK_Member:
4292 case InitializedEntity::EK_Result:
4293 case InitializedEntity::EK_New:
4294 case InitializedEntity::EK_Base:
4295 case InitializedEntity::EK_Delegating:
4296 case InitializedEntity::EK_VectorElement:
4297 case InitializedEntity::EK_ComplexElement:
4298 case InitializedEntity::EK_BlockElement:
4299 case InitializedEntity::EK_LambdaCapture:
4302 case InitializedEntity::EK_Variable:
4303 case InitializedEntity::EK_Parameter:
4304 case InitializedEntity::EK_Temporary:
4305 case InitializedEntity::EK_ArrayElement:
4306 case InitializedEntity::EK_Exception:
4310 llvm_unreachable("missed an InitializedEntity kind?");
4313 /// \brief Look for copy and move constructors and constructor templates, for
4314 /// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4315 static void LookupCopyAndMoveConstructors(Sema &S,
4316 OverloadCandidateSet &CandidateSet,
4317 CXXRecordDecl *Class,
4318 Expr *CurInitExpr) {
4319 DeclContext::lookup_iterator Con, ConEnd;
4320 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
4321 Con != ConEnd; ++Con) {
4322 CXXConstructorDecl *Constructor = 0;
4324 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
4325 // Handle copy/moveconstructors, only.
4326 if (!Constructor || Constructor->isInvalidDecl() ||
4327 !Constructor->isCopyOrMoveConstructor() ||
4328 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4331 DeclAccessPair FoundDecl
4332 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4333 S.AddOverloadCandidate(Constructor, FoundDecl,
4334 CurInitExpr, CandidateSet);
4338 // Handle constructor templates.
4339 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4340 if (ConstructorTmpl->isInvalidDecl())
4343 Constructor = cast<CXXConstructorDecl>(
4344 ConstructorTmpl->getTemplatedDecl());
4345 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4348 // FIXME: Do we need to limit this to copy-constructor-like
4350 DeclAccessPair FoundDecl
4351 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4352 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4353 CurInitExpr, CandidateSet, true);
4357 /// \brief Get the location at which initialization diagnostics should appear.
4358 static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4359 Expr *Initializer) {
4360 switch (Entity.getKind()) {
4361 case InitializedEntity::EK_Result:
4362 return Entity.getReturnLoc();
4364 case InitializedEntity::EK_Exception:
4365 return Entity.getThrowLoc();
4367 case InitializedEntity::EK_Variable:
4368 return Entity.getDecl()->getLocation();
4370 case InitializedEntity::EK_LambdaCapture:
4371 return Entity.getCaptureLoc();
4373 case InitializedEntity::EK_ArrayElement:
4374 case InitializedEntity::EK_Member:
4375 case InitializedEntity::EK_Parameter:
4376 case InitializedEntity::EK_Temporary:
4377 case InitializedEntity::EK_New:
4378 case InitializedEntity::EK_Base:
4379 case InitializedEntity::EK_Delegating:
4380 case InitializedEntity::EK_VectorElement:
4381 case InitializedEntity::EK_ComplexElement:
4382 case InitializedEntity::EK_BlockElement:
4383 return Initializer->getLocStart();
4385 llvm_unreachable("missed an InitializedEntity kind?");
4388 /// \brief Make a (potentially elidable) temporary copy of the object
4389 /// provided by the given initializer by calling the appropriate copy
4392 /// \param S The Sema object used for type-checking.
4394 /// \param T The type of the temporary object, which must either be
4395 /// the type of the initializer expression or a superclass thereof.
4397 /// \param Entity The entity being initialized.
4399 /// \param CurInit The initializer expression.
4401 /// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4402 /// is permitted in C++03 (but not C++0x) when binding a reference to
4405 /// \returns An expression that copies the initializer expression into
4406 /// a temporary object, or an error expression if a copy could not be
4408 static ExprResult CopyObject(Sema &S,
4410 const InitializedEntity &Entity,
4412 bool IsExtraneousCopy) {
4413 // Determine which class type we're copying to.
4414 Expr *CurInitExpr = (Expr *)CurInit.get();
4415 CXXRecordDecl *Class = 0;
4416 if (const RecordType *Record = T->getAs<RecordType>())
4417 Class = cast<CXXRecordDecl>(Record->getDecl());
4421 // C++0x [class.copy]p32:
4422 // When certain criteria are met, an implementation is allowed to
4423 // omit the copy/move construction of a class object, even if the
4424 // copy/move constructor and/or destructor for the object have
4425 // side effects. [...]
4426 // - when a temporary class object that has not been bound to a
4427 // reference (12.2) would be copied/moved to a class object
4428 // with the same cv-unqualified type, the copy/move operation
4429 // can be omitted by constructing the temporary object
4430 // directly into the target of the omitted copy/move
4432 // Note that the other three bullets are handled elsewhere. Copy
4433 // elision for return statements and throw expressions are handled as part
4434 // of constructor initialization, while copy elision for exception handlers
4435 // is handled by the run-time.
4436 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
4437 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
4439 // Make sure that the type we are copying is complete.
4440 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
4443 // Perform overload resolution using the class's copy/move constructors.
4444 // Only consider constructors and constructor templates. Per
4445 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4446 // is direct-initialization.
4447 OverloadCandidateSet CandidateSet(Loc);
4448 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
4450 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4452 OverloadCandidateSet::iterator Best;
4453 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
4457 case OR_No_Viable_Function:
4458 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4459 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4460 : diag::err_temp_copy_no_viable)
4461 << (int)Entity.getKind() << CurInitExpr->getType()
4462 << CurInitExpr->getSourceRange();
4463 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
4464 if (!IsExtraneousCopy || S.isSFINAEContext())
4469 S.Diag(Loc, diag::err_temp_copy_ambiguous)
4470 << (int)Entity.getKind() << CurInitExpr->getType()
4471 << CurInitExpr->getSourceRange();
4472 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
4476 S.Diag(Loc, diag::err_temp_copy_deleted)
4477 << (int)Entity.getKind() << CurInitExpr->getType()
4478 << CurInitExpr->getSourceRange();
4479 S.NoteDeletedFunction(Best->Function);
4483 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
4484 SmallVector<Expr*, 8> ConstructorArgs;
4485 CurInit.release(); // Ownership transferred into MultiExprArg, below.
4487 S.CheckConstructorAccess(Loc, Constructor, Entity,
4488 Best->FoundDecl.getAccess(), IsExtraneousCopy);
4490 if (IsExtraneousCopy) {
4491 // If this is a totally extraneous copy for C++03 reference
4492 // binding purposes, just return the original initialization
4493 // expression. We don't generate an (elided) copy operation here
4494 // because doing so would require us to pass down a flag to avoid
4495 // infinite recursion, where each step adds another extraneous,
4498 // Instantiate the default arguments of any extra parameters in
4499 // the selected copy constructor, as if we were going to create a
4500 // proper call to the copy constructor.
4501 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4502 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4503 if (S.RequireCompleteType(Loc, Parm->getType(),
4504 diag::err_call_incomplete_argument))
4507 // Build the default argument expression; we don't actually care
4508 // if this succeeds or not, because this routine will complain
4509 // if there was a problem.
4510 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4513 return S.Owned(CurInitExpr);
4516 S.MarkFunctionReferenced(Loc, Constructor);
4518 // Determine the arguments required to actually perform the
4519 // constructor call (we might have derived-to-base conversions, or
4520 // the copy constructor may have default arguments).
4521 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
4522 Loc, ConstructorArgs))
4525 // Actually perform the constructor call.
4526 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
4528 HadMultipleCandidates,
4530 CXXConstructExpr::CK_Complete,
4533 // If we're supposed to bind temporaries, do so.
4534 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4535 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4539 /// \brief Check whether elidable copy construction for binding a reference to
4540 /// a temporary would have succeeded if we were building in C++98 mode, for
4542 static void CheckCXX98CompatAccessibleCopy(Sema &S,
4543 const InitializedEntity &Entity,
4544 Expr *CurInitExpr) {
4545 assert(S.getLangOpts().CPlusPlus0x);
4547 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4551 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4552 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4553 == DiagnosticsEngine::Ignored)
4556 // Find constructors which would have been considered.
4557 OverloadCandidateSet CandidateSet(Loc);
4558 LookupCopyAndMoveConstructors(
4559 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4561 // Perform overload resolution.
4562 OverloadCandidateSet::iterator Best;
4563 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4565 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4566 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4567 << CurInitExpr->getSourceRange();
4571 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
4572 Entity, Best->FoundDecl.getAccess(), Diag);
4573 // FIXME: Check default arguments as far as that's possible.
4576 case OR_No_Viable_Function:
4578 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
4583 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
4588 S.NoteDeletedFunction(Best->Function);
4593 void InitializationSequence::PrintInitLocationNote(Sema &S,
4594 const InitializedEntity &Entity) {
4595 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4596 if (Entity.getDecl()->getLocation().isInvalid())
4599 if (Entity.getDecl()->getDeclName())
4600 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4601 << Entity.getDecl()->getDeclName();
4603 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4607 static bool isReferenceBinding(const InitializationSequence::Step &s) {
4608 return s.Kind == InitializationSequence::SK_BindReference ||
4609 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4613 PerformConstructorInitialization(Sema &S,
4614 const InitializedEntity &Entity,
4615 const InitializationKind &Kind,
4617 const InitializationSequence::Step& Step,
4618 bool &ConstructorInitRequiresZeroInit) {
4619 unsigned NumArgs = Args.size();
4620 CXXConstructorDecl *Constructor
4621 = cast<CXXConstructorDecl>(Step.Function.Function);
4622 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4624 // Build a call to the selected constructor.
4625 SmallVector<Expr*, 8> ConstructorArgs;
4626 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4627 ? Kind.getEqualLoc()
4628 : Kind.getLocation();
4630 if (Kind.getKind() == InitializationKind::IK_Default) {
4631 // Force even a trivial, implicit default constructor to be
4632 // semantically checked. We do this explicitly because we don't build
4633 // the definition for completely trivial constructors.
4634 assert(Constructor->getParent() && "No parent class for constructor.");
4635 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
4636 Constructor->isTrivial() && !Constructor->isUsed(false))
4637 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4640 ExprResult CurInit = S.Owned((Expr *)0);
4642 // C++ [over.match.copy]p1:
4643 // - When initializing a temporary to be bound to the first parameter
4644 // of a constructor that takes a reference to possibly cv-qualified
4645 // T as its first argument, called with a single argument in the
4646 // context of direct-initialization, explicit conversion functions
4647 // are also considered.
4648 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
4650 Constructor->isCopyOrMoveConstructor();
4652 // Determine the arguments required to actually perform the constructor
4654 if (S.CompleteConstructorCall(Constructor, Args,
4655 Loc, ConstructorArgs,
4660 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
4661 (Kind.getKind() == InitializationKind::IK_DirectList ||
4662 (NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4663 (Kind.getKind() == InitializationKind::IK_Direct ||
4664 Kind.getKind() == InitializationKind::IK_Value)))) {
4665 // An explicitly-constructed temporary, e.g., X(1, 2).
4666 S.MarkFunctionReferenced(Loc, Constructor);
4667 S.DiagnoseUseOfDecl(Constructor, Loc);
4669 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4671 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
4672 SourceRange ParenRange;
4673 if (Kind.getKind() != InitializationKind::IK_DirectList)
4674 ParenRange = Kind.getParenRange();
4676 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4681 HadMultipleCandidates,
4682 ConstructorInitRequiresZeroInit));
4684 CXXConstructExpr::ConstructionKind ConstructKind =
4685 CXXConstructExpr::CK_Complete;
4687 if (Entity.getKind() == InitializedEntity::EK_Base) {
4688 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4689 CXXConstructExpr::CK_VirtualBase :
4690 CXXConstructExpr::CK_NonVirtualBase;
4691 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4692 ConstructKind = CXXConstructExpr::CK_Delegating;
4695 // Only get the parenthesis range if it is a direct construction.
4696 SourceRange parenRange =
4697 Kind.getKind() == InitializationKind::IK_Direct ?
4698 Kind.getParenRange() : SourceRange();
4700 // If the entity allows NRVO, mark the construction as elidable
4702 if (Entity.allowsNRVO())
4703 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4704 Constructor, /*Elidable=*/true,
4706 HadMultipleCandidates,
4707 ConstructorInitRequiresZeroInit,
4711 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4714 HadMultipleCandidates,
4715 ConstructorInitRequiresZeroInit,
4719 if (CurInit.isInvalid())
4722 // Only check access if all of that succeeded.
4723 S.CheckConstructorAccess(Loc, Constructor, Entity,
4724 Step.Function.FoundDecl.getAccess());
4725 S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc);
4727 if (shouldBindAsTemporary(Entity))
4728 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4733 /// Determine whether the specified InitializedEntity definitely has a lifetime
4734 /// longer than the current full-expression. Conservatively returns false if
4737 InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
4738 const InitializedEntity *Top = &Entity;
4739 while (Top->getParent())
4740 Top = Top->getParent();
4742 switch (Top->getKind()) {
4743 case InitializedEntity::EK_Variable:
4744 case InitializedEntity::EK_Result:
4745 case InitializedEntity::EK_Exception:
4746 case InitializedEntity::EK_Member:
4747 case InitializedEntity::EK_New:
4748 case InitializedEntity::EK_Base:
4749 case InitializedEntity::EK_Delegating:
4752 case InitializedEntity::EK_ArrayElement:
4753 case InitializedEntity::EK_VectorElement:
4754 case InitializedEntity::EK_BlockElement:
4755 case InitializedEntity::EK_ComplexElement:
4756 // Could not determine what the full initialization is. Assume it might not
4757 // outlive the full-expression.
4760 case InitializedEntity::EK_Parameter:
4761 case InitializedEntity::EK_Temporary:
4762 case InitializedEntity::EK_LambdaCapture:
4763 // The entity being initialized might not outlive the full-expression.
4767 llvm_unreachable("unknown entity kind");
4771 InitializationSequence::Perform(Sema &S,
4772 const InitializedEntity &Entity,
4773 const InitializationKind &Kind,
4775 QualType *ResultType) {
4777 unsigned NumArgs = Args.size();
4778 Diagnose(S, Entity, Kind, Args.data(), NumArgs);
4782 if (getKind() == DependentSequence) {
4783 // If the declaration is a non-dependent, incomplete array type
4784 // that has an initializer, then its type will be completed once
4785 // the initializer is instantiated.
4786 if (ResultType && !Entity.getType()->isDependentType() &&
4788 QualType DeclType = Entity.getType();
4789 if (const IncompleteArrayType *ArrayT
4790 = S.Context.getAsIncompleteArrayType(DeclType)) {
4791 // FIXME: We don't currently have the ability to accurately
4792 // compute the length of an initializer list without
4793 // performing full type-checking of the initializer list
4794 // (since we have to determine where braces are implicitly
4795 // introduced and such). So, we fall back to making the array
4796 // type a dependently-sized array type with no specified
4798 if (isa<InitListExpr>((Expr *)Args[0])) {
4799 SourceRange Brackets;
4801 // Scavange the location of the brackets from the entity, if we can.
4802 if (DeclaratorDecl *DD = Entity.getDecl()) {
4803 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4804 TypeLoc TL = TInfo->getTypeLoc();
4805 if (IncompleteArrayTypeLoc *ArrayLoc
4806 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4807 Brackets = ArrayLoc->getBracketsRange();
4812 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4814 ArrayT->getSizeModifier(),
4815 ArrayT->getIndexTypeCVRQualifiers(),
4821 if (Kind.getKind() == InitializationKind::IK_Direct &&
4822 !Kind.isExplicitCast()) {
4823 // Rebuild the ParenListExpr.
4824 SourceRange ParenRange = Kind.getParenRange();
4825 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
4828 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4829 Kind.isExplicitCast() ||
4830 Kind.getKind() == InitializationKind::IK_DirectList);
4831 return ExprResult(Args[0]);
4834 // No steps means no initialization.
4836 return S.Owned((Expr *)0);
4838 if (S.getLangOpts().CPlusPlus0x && Entity.getType()->isReferenceType() &&
4839 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
4840 Entity.getKind() != InitializedEntity::EK_Parameter) {
4841 // Produce a C++98 compatibility warning if we are initializing a reference
4842 // from an initializer list. For parameters, we produce a better warning
4844 Expr *Init = Args[0];
4845 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
4846 << Init->getSourceRange();
4849 // Diagnose cases where we initialize a pointer to an array temporary, and the
4850 // pointer obviously outlives the temporary.
4851 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
4852 Entity.getType()->isPointerType() &&
4853 InitializedEntityOutlivesFullExpression(Entity)) {
4854 Expr *Init = Args[0];
4855 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
4856 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
4857 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
4858 << Init->getSourceRange();
4861 QualType DestType = Entity.getType().getNonReferenceType();
4862 // FIXME: Ugly hack around the fact that Entity.getType() is not
4863 // the same as Entity.getDecl()->getType() in cases involving type merging,
4864 // and we want latter when it makes sense.
4866 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
4869 ExprResult CurInit = S.Owned((Expr *)0);
4871 // For initialization steps that start with a single initializer,
4872 // grab the only argument out the Args and place it into the "current"
4874 switch (Steps.front().Kind) {
4875 case SK_ResolveAddressOfOverloadedFunction:
4876 case SK_CastDerivedToBaseRValue:
4877 case SK_CastDerivedToBaseXValue:
4878 case SK_CastDerivedToBaseLValue:
4879 case SK_BindReference:
4880 case SK_BindReferenceToTemporary:
4881 case SK_ExtraneousCopyToTemporary:
4882 case SK_UserConversion:
4883 case SK_QualificationConversionLValue:
4884 case SK_QualificationConversionXValue:
4885 case SK_QualificationConversionRValue:
4886 case SK_ConversionSequence:
4887 case SK_ListInitialization:
4888 case SK_UnwrapInitList:
4889 case SK_RewrapInitList:
4890 case SK_CAssignment:
4892 case SK_ObjCObjectConversion:
4894 case SK_ParenthesizedArrayInit:
4895 case SK_PassByIndirectCopyRestore:
4896 case SK_PassByIndirectRestore:
4897 case SK_ProduceObjCObject:
4898 case SK_StdInitializerList: {
4899 assert(Args.size() == 1);
4901 if (!CurInit.get()) return ExprError();
4905 case SK_ConstructorInitialization:
4906 case SK_ListConstructorCall:
4907 case SK_ZeroInitialization:
4911 // Walk through the computed steps for the initialization sequence,
4912 // performing the specified conversions along the way.
4913 bool ConstructorInitRequiresZeroInit = false;
4914 for (step_iterator Step = step_begin(), StepEnd = step_end();
4915 Step != StepEnd; ++Step) {
4916 if (CurInit.isInvalid())
4919 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
4921 switch (Step->Kind) {
4922 case SK_ResolveAddressOfOverloadedFunction:
4923 // Overload resolution determined which function invoke; update the
4924 // initializer to reflect that choice.
4925 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
4926 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
4927 CurInit = S.FixOverloadedFunctionReference(CurInit,
4928 Step->Function.FoundDecl,
4929 Step->Function.Function);
4932 case SK_CastDerivedToBaseRValue:
4933 case SK_CastDerivedToBaseXValue:
4934 case SK_CastDerivedToBaseLValue: {
4935 // We have a derived-to-base cast that produces either an rvalue or an
4936 // lvalue. Perform that cast.
4938 CXXCastPath BasePath;
4940 // Casts to inaccessible base classes are allowed with C-style casts.
4941 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4942 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
4943 CurInit.get()->getLocStart(),
4944 CurInit.get()->getSourceRange(),
4945 &BasePath, IgnoreBaseAccess))
4948 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4949 QualType T = SourceType;
4950 if (const PointerType *Pointer = T->getAs<PointerType>())
4951 T = Pointer->getPointeeType();
4952 if (const RecordType *RecordTy = T->getAs<RecordType>())
4953 S.MarkVTableUsed(CurInit.get()->getLocStart(),
4954 cast<CXXRecordDecl>(RecordTy->getDecl()));
4958 Step->Kind == SK_CastDerivedToBaseLValue ?
4960 (Step->Kind == SK_CastDerivedToBaseXValue ?
4963 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4971 case SK_BindReference:
4972 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
4973 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4974 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
4975 << Entity.getType().isVolatileQualified()
4976 << BitField->getDeclName()
4977 << CurInit.get()->getSourceRange();
4978 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
4982 if (CurInit.get()->refersToVectorElement()) {
4983 // References cannot bind to vector elements.
4984 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4985 << Entity.getType().isVolatileQualified()
4986 << CurInit.get()->getSourceRange();
4987 PrintInitLocationNote(S, Entity);
4991 // Reference binding does not have any corresponding ASTs.
4993 // Check exception specifications
4994 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
4999 case SK_BindReferenceToTemporary:
5000 // Check exception specifications
5001 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
5004 // Materialize the temporary into memory.
5005 CurInit = new (S.Context) MaterializeTemporaryExpr(
5006 Entity.getType().getNonReferenceType(),
5008 Entity.getType()->isLValueReferenceType());
5010 // If we're binding to an Objective-C object that has lifetime, we
5012 if (S.getLangOpts().ObjCAutoRefCount &&
5013 CurInit.get()->getType()->isObjCLifetimeType())
5014 S.ExprNeedsCleanups = true;
5018 case SK_ExtraneousCopyToTemporary:
5019 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
5020 /*IsExtraneousCopy=*/true);
5023 case SK_UserConversion: {
5024 // We have a user-defined conversion that invokes either a constructor
5025 // or a conversion function.
5027 bool IsCopy = false;
5028 FunctionDecl *Fn = Step->Function.Function;
5029 DeclAccessPair FoundFn = Step->Function.FoundDecl;
5030 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
5031 bool CreatedObject = false;
5032 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
5033 // Build a call to the selected constructor.
5034 SmallVector<Expr*, 8> ConstructorArgs;
5035 SourceLocation Loc = CurInit.get()->getLocStart();
5036 CurInit.release(); // Ownership transferred into MultiExprArg, below.
5038 // Determine the arguments required to actually perform the constructor
5040 Expr *Arg = CurInit.get();
5041 if (S.CompleteConstructorCall(Constructor,
5042 MultiExprArg(&Arg, 1),
5043 Loc, ConstructorArgs))
5046 // Build an expression that constructs a temporary.
5047 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
5049 HadMultipleCandidates,
5051 CXXConstructExpr::CK_Complete,
5053 if (CurInit.isInvalid())
5056 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
5057 FoundFn.getAccess());
5058 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
5060 CastKind = CK_ConstructorConversion;
5061 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5062 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5063 S.IsDerivedFrom(SourceType, Class))
5066 CreatedObject = true;
5068 // Build a call to the conversion function.
5069 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
5070 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
5072 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
5074 // FIXME: Should we move this initialization into a separate
5075 // derived-to-base conversion? I believe the answer is "no", because
5076 // we don't want to turn off access control here for c-style casts.
5077 ExprResult CurInitExprRes =
5078 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5079 FoundFn, Conversion);
5080 if(CurInitExprRes.isInvalid())
5082 CurInit = CurInitExprRes;
5084 // Build the actual call to the conversion function.
5085 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5086 HadMultipleCandidates);
5087 if (CurInit.isInvalid() || !CurInit.get())
5090 CastKind = CK_UserDefinedConversion;
5092 CreatedObject = Conversion->getResultType()->isRecordType();
5095 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
5096 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5098 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
5099 QualType T = CurInit.get()->getType();
5100 if (const RecordType *Record = T->getAs<RecordType>()) {
5101 CXXDestructorDecl *Destructor
5102 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
5103 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
5104 S.PDiag(diag::err_access_dtor_temp) << T);
5105 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
5106 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
5110 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
5111 CurInit.get()->getType(),
5112 CastKind, CurInit.get(), 0,
5113 CurInit.get()->getValueKind()));
5114 if (MaybeBindToTemp)
5115 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
5117 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
5118 CurInit, /*IsExtraneousCopy=*/false);
5122 case SK_QualificationConversionLValue:
5123 case SK_QualificationConversionXValue:
5124 case SK_QualificationConversionRValue: {
5125 // Perform a qualification conversion; these can never go wrong.
5127 Step->Kind == SK_QualificationConversionLValue ?
5129 (Step->Kind == SK_QualificationConversionXValue ?
5132 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
5136 case SK_ConversionSequence: {
5137 Sema::CheckedConversionKind CCK
5138 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5139 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
5140 : Kind.isExplicitCast()? Sema::CCK_OtherCast
5141 : Sema::CCK_ImplicitConversion;
5142 ExprResult CurInitExprRes =
5143 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
5144 getAssignmentAction(Entity), CCK);
5145 if (CurInitExprRes.isInvalid())
5147 CurInit = CurInitExprRes;
5151 case SK_ListInitialization: {
5152 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
5153 // Hack: We must pass *ResultType if available in order to set the type
5154 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5155 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5156 // temporary, not a reference, so we should pass Ty.
5157 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5158 // Since this step is never used for a reference directly, we explicitly
5159 // unwrap references here and rewrap them afterwards.
5160 // We also need to create a InitializeTemporary entity for this.
5161 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
5162 bool IsTemporary = Entity.getType()->isReferenceType();
5163 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
5164 InitListChecker PerformInitList(S, IsTemporary ? TempEntity : Entity,
5165 InitList, Ty, /*VerifyOnly=*/false,
5166 Kind.getKind() != InitializationKind::IK_DirectList ||
5167 !S.getLangOpts().CPlusPlus0x);
5168 if (PerformInitList.HadError())
5172 if ((*ResultType)->isRValueReferenceType())
5173 Ty = S.Context.getRValueReferenceType(Ty);
5174 else if ((*ResultType)->isLValueReferenceType())
5175 Ty = S.Context.getLValueReferenceType(Ty,
5176 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5180 InitListExpr *StructuredInitList =
5181 PerformInitList.getFullyStructuredList();
5183 CurInit = S.Owned(StructuredInitList);
5187 case SK_ListConstructorCall: {
5188 // When an initializer list is passed for a parameter of type "reference
5189 // to object", we don't get an EK_Temporary entity, but instead an
5190 // EK_Parameter entity with reference type.
5191 // FIXME: This is a hack. What we really should do is create a user
5192 // conversion step for this case, but this makes it considerably more
5193 // complicated. For now, this will do.
5194 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5195 Entity.getType().getNonReferenceType());
5196 bool UseTemporary = Entity.getType()->isReferenceType();
5197 assert(Args.size() == 1 && "expected a single argument for list init");
5198 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5199 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
5200 << InitList->getSourceRange();
5201 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
5202 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
5205 ConstructorInitRequiresZeroInit);
5209 case SK_UnwrapInitList:
5210 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5213 case SK_RewrapInitList: {
5214 Expr *E = CurInit.take();
5215 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5216 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
5217 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
5218 ILE->setSyntacticForm(Syntactic);
5219 ILE->setType(E->getType());
5220 ILE->setValueKind(E->getValueKind());
5221 CurInit = S.Owned(ILE);
5225 case SK_ConstructorInitialization: {
5226 // When an initializer list is passed for a parameter of type "reference
5227 // to object", we don't get an EK_Temporary entity, but instead an
5228 // EK_Parameter entity with reference type.
5229 // FIXME: This is a hack. What we really should do is create a user
5230 // conversion step for this case, but this makes it considerably more
5231 // complicated. For now, this will do.
5232 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5233 Entity.getType().getNonReferenceType());
5234 bool UseTemporary = Entity.getType()->isReferenceType();
5235 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
5238 ConstructorInitRequiresZeroInit);
5242 case SK_ZeroInitialization: {
5243 step_iterator NextStep = Step;
5245 if (NextStep != StepEnd &&
5246 (NextStep->Kind == SK_ConstructorInitialization ||
5247 NextStep->Kind == SK_ListConstructorCall)) {
5248 // The need for zero-initialization is recorded directly into
5249 // the call to the object's constructor within the next step.
5250 ConstructorInitRequiresZeroInit = true;
5251 } else if (Kind.getKind() == InitializationKind::IK_Value &&
5252 S.getLangOpts().CPlusPlus &&
5253 !Kind.isImplicitValueInit()) {
5254 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5256 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
5257 Kind.getRange().getBegin());
5259 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5260 TSInfo->getType().getNonLValueExprType(S.Context),
5262 Kind.getRange().getEnd()));
5264 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
5269 case SK_CAssignment: {
5270 QualType SourceType = CurInit.get()->getType();
5271 ExprResult Result = CurInit;
5272 Sema::AssignConvertType ConvTy =
5273 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5274 if (Result.isInvalid())
5278 // If this is a call, allow conversion to a transparent union.
5279 ExprResult CurInitExprRes = CurInit;
5280 if (ConvTy != Sema::Compatible &&
5281 Entity.getKind() == InitializedEntity::EK_Parameter &&
5282 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
5283 == Sema::Compatible)
5284 ConvTy = Sema::Compatible;
5285 if (CurInitExprRes.isInvalid())
5287 CurInit = CurInitExprRes;
5290 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5291 Step->Type, SourceType,
5293 getAssignmentAction(Entity),
5295 PrintInitLocationNote(S, Entity);
5297 } else if (Complained)
5298 PrintInitLocationNote(S, Entity);
5302 case SK_StringInit: {
5303 QualType Ty = Step->Type;
5304 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
5305 S.Context.getAsArrayType(Ty), S);
5309 case SK_ObjCObjectConversion:
5310 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
5311 CK_ObjCObjectLValueCast,
5312 CurInit.get()->getValueKind());
5316 // Okay: we checked everything before creating this step. Note that
5317 // this is a GNU extension.
5318 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
5319 << Step->Type << CurInit.get()->getType()
5320 << CurInit.get()->getSourceRange();
5322 // If the destination type is an incomplete array type, update the
5323 // type accordingly.
5325 if (const IncompleteArrayType *IncompleteDest
5326 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5327 if (const ConstantArrayType *ConstantSource
5328 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
5329 *ResultType = S.Context.getConstantArrayType(
5330 IncompleteDest->getElementType(),
5331 ConstantSource->getSize(),
5332 ArrayType::Normal, 0);
5338 case SK_ParenthesizedArrayInit:
5339 // Okay: we checked everything before creating this step. Note that
5340 // this is a GNU extension.
5341 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
5342 << CurInit.get()->getSourceRange();
5345 case SK_PassByIndirectCopyRestore:
5346 case SK_PassByIndirectRestore:
5347 checkIndirectCopyRestoreSource(S, CurInit.get());
5348 CurInit = S.Owned(new (S.Context)
5349 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5350 Step->Kind == SK_PassByIndirectCopyRestore));
5353 case SK_ProduceObjCObject:
5354 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
5355 CK_ARCProduceObject,
5356 CurInit.take(), 0, VK_RValue));
5359 case SK_StdInitializerList: {
5360 QualType Dest = Step->Type;
5362 bool Success = S.isStdInitializerList(Dest, &E);
5364 assert(Success && "Destination type changed?");
5366 // If the element type has a destructor, check it.
5367 if (CXXRecordDecl *RD = E->getAsCXXRecordDecl()) {
5368 if (!RD->hasIrrelevantDestructor()) {
5369 if (CXXDestructorDecl *Destructor = S.LookupDestructor(RD)) {
5370 S.MarkFunctionReferenced(Kind.getLocation(), Destructor);
5371 S.CheckDestructorAccess(Kind.getLocation(), Destructor,
5372 S.PDiag(diag::err_access_dtor_temp) << E);
5373 S.DiagnoseUseOfDecl(Destructor, Kind.getLocation());
5378 InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
5379 S.Diag(ILE->getExprLoc(), diag::warn_cxx98_compat_initializer_list_init)
5380 << ILE->getSourceRange();
5381 unsigned NumInits = ILE->getNumInits();
5382 SmallVector<Expr*, 16> Converted(NumInits);
5383 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5384 S.Context.getConstantArrayType(E,
5385 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5387 ArrayType::Normal, 0));
5388 InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5390 for (unsigned i = 0; i < NumInits; ++i) {
5391 Element.setElementIndex(i);
5392 ExprResult Init = S.Owned(ILE->getInit(i));
5393 ExprResult Res = S.PerformCopyInitialization(Element,
5394 Init.get()->getExprLoc(),
5396 assert(!Res.isInvalid() && "Result changed since try phase.");
5397 Converted[i] = Res.take();
5399 InitListExpr *Semantic = new (S.Context)
5400 InitListExpr(S.Context, ILE->getLBraceLoc(),
5401 Converted, ILE->getRBraceLoc());
5402 Semantic->setSyntacticForm(ILE);
5403 Semantic->setType(Dest);
5404 Semantic->setInitializesStdInitializerList();
5405 CurInit = S.Owned(Semantic);
5411 // Diagnose non-fatal problems with the completed initialization.
5412 if (Entity.getKind() == InitializedEntity::EK_Member &&
5413 cast<FieldDecl>(Entity.getDecl())->isBitField())
5414 S.CheckBitFieldInitialization(Kind.getLocation(),
5415 cast<FieldDecl>(Entity.getDecl()),
5421 //===----------------------------------------------------------------------===//
5422 // Diagnose initialization failures
5423 //===----------------------------------------------------------------------===//
5424 bool InitializationSequence::Diagnose(Sema &S,
5425 const InitializedEntity &Entity,
5426 const InitializationKind &Kind,
5427 Expr **Args, unsigned NumArgs) {
5431 QualType DestType = Entity.getType();
5433 case FK_TooManyInitsForReference:
5434 // FIXME: Customize for the initialized entity?
5436 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
5437 << DestType.getNonReferenceType();
5438 else // FIXME: diagnostic below could be better!
5439 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
5440 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
5443 case FK_ArrayNeedsInitList:
5444 case FK_ArrayNeedsInitListOrStringLiteral:
5445 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5446 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5449 case FK_ArrayTypeMismatch:
5450 case FK_NonConstantArrayInit:
5451 S.Diag(Kind.getLocation(),
5452 (Failure == FK_ArrayTypeMismatch
5453 ? diag::err_array_init_different_type
5454 : diag::err_array_init_non_constant_array))
5455 << DestType.getNonReferenceType()
5456 << Args[0]->getType()
5457 << Args[0]->getSourceRange();
5460 case FK_VariableLengthArrayHasInitializer:
5461 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5462 << Args[0]->getSourceRange();
5465 case FK_AddressOfOverloadFailed: {
5466 DeclAccessPair Found;
5467 S.ResolveAddressOfOverloadedFunction(Args[0],
5468 DestType.getNonReferenceType(),
5474 case FK_ReferenceInitOverloadFailed:
5475 case FK_UserConversionOverloadFailed:
5476 switch (FailedOverloadResult) {
5478 if (Failure == FK_UserConversionOverloadFailed)
5479 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5480 << Args[0]->getType() << DestType
5481 << Args[0]->getSourceRange();
5483 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5484 << DestType << Args[0]->getType()
5485 << Args[0]->getSourceRange();
5487 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5488 llvm::makeArrayRef(Args, NumArgs));
5491 case OR_No_Viable_Function:
5492 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5493 << Args[0]->getType() << DestType.getNonReferenceType()
5494 << Args[0]->getSourceRange();
5495 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates,
5496 llvm::makeArrayRef(Args, NumArgs));
5500 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5501 << Args[0]->getType() << DestType.getNonReferenceType()
5502 << Args[0]->getSourceRange();
5503 OverloadCandidateSet::iterator Best;
5504 OverloadingResult Ovl
5505 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5507 if (Ovl == OR_Deleted) {
5508 S.NoteDeletedFunction(Best->Function);
5510 llvm_unreachable("Inconsistent overload resolution?");
5516 llvm_unreachable("Conversion did not fail!");
5520 case FK_NonConstLValueReferenceBindingToTemporary:
5521 if (isa<InitListExpr>(Args[0])) {
5522 S.Diag(Kind.getLocation(),
5523 diag::err_lvalue_reference_bind_to_initlist)
5524 << DestType.getNonReferenceType().isVolatileQualified()
5525 << DestType.getNonReferenceType()
5526 << Args[0]->getSourceRange();
5529 // Intentional fallthrough
5531 case FK_NonConstLValueReferenceBindingToUnrelated:
5532 S.Diag(Kind.getLocation(),
5533 Failure == FK_NonConstLValueReferenceBindingToTemporary
5534 ? diag::err_lvalue_reference_bind_to_temporary
5535 : diag::err_lvalue_reference_bind_to_unrelated)
5536 << DestType.getNonReferenceType().isVolatileQualified()
5537 << DestType.getNonReferenceType()
5538 << Args[0]->getType()
5539 << Args[0]->getSourceRange();
5542 case FK_RValueReferenceBindingToLValue:
5543 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
5544 << DestType.getNonReferenceType() << Args[0]->getType()
5545 << Args[0]->getSourceRange();
5548 case FK_ReferenceInitDropsQualifiers:
5549 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5550 << DestType.getNonReferenceType()
5551 << Args[0]->getType()
5552 << Args[0]->getSourceRange();
5555 case FK_ReferenceInitFailed:
5556 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5557 << DestType.getNonReferenceType()
5558 << Args[0]->isLValue()
5559 << Args[0]->getType()
5560 << Args[0]->getSourceRange();
5561 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5562 Args[0]->getType()->isObjCObjectPointerType())
5563 S.EmitRelatedResultTypeNote(Args[0]);
5566 case FK_ConversionFailed: {
5567 QualType FromType = Args[0]->getType();
5568 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
5569 << (int)Entity.getKind()
5571 << Args[0]->isLValue()
5573 << Args[0]->getSourceRange();
5574 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5575 S.Diag(Kind.getLocation(), PDiag);
5576 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5577 Args[0]->getType()->isObjCObjectPointerType())
5578 S.EmitRelatedResultTypeNote(Args[0]);
5582 case FK_ConversionFromPropertyFailed:
5583 // No-op. This error has already been reported.
5586 case FK_TooManyInitsForScalar: {
5589 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
5590 R = SourceRange(InitList->getInit(0)->getLocEnd(),
5591 InitList->getLocEnd());
5593 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
5595 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5596 if (Kind.isCStyleOrFunctionalCast())
5597 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5600 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5601 << /*scalar=*/2 << R;
5605 case FK_ReferenceBindingToInitList:
5606 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5607 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5610 case FK_InitListBadDestinationType:
5611 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5612 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5615 case FK_ListConstructorOverloadFailed:
5616 case FK_ConstructorOverloadFailed: {
5617 SourceRange ArgsRange;
5619 ArgsRange = SourceRange(Args[0]->getLocStart(),
5620 Args[NumArgs - 1]->getLocEnd());
5622 if (Failure == FK_ListConstructorOverloadFailed) {
5623 assert(NumArgs == 1 && "List construction from other than 1 argument.");
5624 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5625 Args = InitList->getInits();
5626 NumArgs = InitList->getNumInits();
5629 // FIXME: Using "DestType" for the entity we're printing is probably
5631 switch (FailedOverloadResult) {
5633 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5634 << DestType << ArgsRange;
5635 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5636 llvm::makeArrayRef(Args, NumArgs));
5639 case OR_No_Viable_Function:
5640 if (Kind.getKind() == InitializationKind::IK_Default &&
5641 (Entity.getKind() == InitializedEntity::EK_Base ||
5642 Entity.getKind() == InitializedEntity::EK_Member) &&
5643 isa<CXXConstructorDecl>(S.CurContext)) {
5644 // This is implicit default initialization of a member or
5645 // base within a constructor. If no viable function was
5646 // found, notify the user that she needs to explicitly
5647 // initialize this base/member.
5648 CXXConstructorDecl *Constructor
5649 = cast<CXXConstructorDecl>(S.CurContext);
5650 if (Entity.getKind() == InitializedEntity::EK_Base) {
5651 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5652 << Constructor->isImplicit()
5653 << S.Context.getTypeDeclType(Constructor->getParent())
5655 << Entity.getType();
5657 RecordDecl *BaseDecl
5658 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5660 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5661 << S.Context.getTagDeclType(BaseDecl);
5663 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5664 << Constructor->isImplicit()
5665 << S.Context.getTypeDeclType(Constructor->getParent())
5667 << Entity.getName();
5668 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5670 if (const RecordType *Record
5671 = Entity.getType()->getAs<RecordType>())
5672 S.Diag(Record->getDecl()->getLocation(),
5673 diag::note_previous_decl)
5674 << S.Context.getTagDeclType(Record->getDecl());
5679 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5680 << DestType << ArgsRange;
5681 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates,
5682 llvm::makeArrayRef(Args, NumArgs));
5686 OverloadCandidateSet::iterator Best;
5687 OverloadingResult Ovl
5688 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
5689 if (Ovl != OR_Deleted) {
5690 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5691 << true << DestType << ArgsRange;
5692 llvm_unreachable("Inconsistent overload resolution?");
5696 // If this is a defaulted or implicitly-declared function, then
5697 // it was implicitly deleted. Make it clear that the deletion was
5699 if (S.isImplicitlyDeleted(Best->Function))
5700 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
5701 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
5702 << DestType << ArgsRange;
5704 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5705 << true << DestType << ArgsRange;
5707 S.NoteDeletedFunction(Best->Function);
5712 llvm_unreachable("Conversion did not fail!");
5717 case FK_DefaultInitOfConst:
5718 if (Entity.getKind() == InitializedEntity::EK_Member &&
5719 isa<CXXConstructorDecl>(S.CurContext)) {
5720 // This is implicit default-initialization of a const member in
5721 // a constructor. Complain that it needs to be explicitly
5723 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5724 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5725 << Constructor->isImplicit()
5726 << S.Context.getTypeDeclType(Constructor->getParent())
5728 << Entity.getName();
5729 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5730 << Entity.getName();
5732 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5733 << DestType << (bool)DestType->getAs<RecordType>();
5738 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
5739 diag::err_init_incomplete_type);
5742 case FK_ListInitializationFailed: {
5743 // Run the init list checker again to emit diagnostics.
5744 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5745 QualType DestType = Entity.getType();
5746 InitListChecker DiagnoseInitList(S, Entity, InitList,
5747 DestType, /*VerifyOnly=*/false,
5748 Kind.getKind() != InitializationKind::IK_DirectList ||
5749 !S.getLangOpts().CPlusPlus0x);
5750 assert(DiagnoseInitList.HadError() &&
5751 "Inconsistent init list check result.");
5755 case FK_PlaceholderType: {
5756 // FIXME: Already diagnosed!
5760 case FK_InitListElementCopyFailure: {
5761 // Try to perform all copies again.
5762 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5763 unsigned NumInits = InitList->getNumInits();
5764 QualType DestType = Entity.getType();
5766 bool Success = S.isStdInitializerList(DestType, &E);
5768 assert(Success && "Where did the std::initializer_list go?");
5769 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5770 S.Context.getConstantArrayType(E,
5771 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5773 ArrayType::Normal, 0));
5774 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
5776 // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
5777 // where the init list type is wrong, e.g.
5778 // std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
5779 // FIXME: Emit a note if we hit the limit?
5781 for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
5782 Element.setElementIndex(i);
5783 ExprResult Init = S.Owned(InitList->getInit(i));
5784 if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
5791 case FK_ExplicitConstructor: {
5792 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
5793 << Args[0]->getSourceRange();
5794 OverloadCandidateSet::iterator Best;
5795 OverloadingResult Ovl
5796 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
5798 assert(Ovl == OR_Success && "Inconsistent overload resolution");
5799 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
5800 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
5805 PrintInitLocationNote(S, Entity);
5809 void InitializationSequence::dump(raw_ostream &OS) const {
5810 switch (SequenceKind) {
5811 case FailedSequence: {
5812 OS << "Failed sequence: ";
5814 case FK_TooManyInitsForReference:
5815 OS << "too many initializers for reference";
5818 case FK_ArrayNeedsInitList:
5819 OS << "array requires initializer list";
5822 case FK_ArrayNeedsInitListOrStringLiteral:
5823 OS << "array requires initializer list or string literal";
5826 case FK_ArrayTypeMismatch:
5827 OS << "array type mismatch";
5830 case FK_NonConstantArrayInit:
5831 OS << "non-constant array initializer";
5834 case FK_AddressOfOverloadFailed:
5835 OS << "address of overloaded function failed";
5838 case FK_ReferenceInitOverloadFailed:
5839 OS << "overload resolution for reference initialization failed";
5842 case FK_NonConstLValueReferenceBindingToTemporary:
5843 OS << "non-const lvalue reference bound to temporary";
5846 case FK_NonConstLValueReferenceBindingToUnrelated:
5847 OS << "non-const lvalue reference bound to unrelated type";
5850 case FK_RValueReferenceBindingToLValue:
5851 OS << "rvalue reference bound to an lvalue";
5854 case FK_ReferenceInitDropsQualifiers:
5855 OS << "reference initialization drops qualifiers";
5858 case FK_ReferenceInitFailed:
5859 OS << "reference initialization failed";
5862 case FK_ConversionFailed:
5863 OS << "conversion failed";
5866 case FK_ConversionFromPropertyFailed:
5867 OS << "conversion from property failed";
5870 case FK_TooManyInitsForScalar:
5871 OS << "too many initializers for scalar";
5874 case FK_ReferenceBindingToInitList:
5875 OS << "referencing binding to initializer list";
5878 case FK_InitListBadDestinationType:
5879 OS << "initializer list for non-aggregate, non-scalar type";
5882 case FK_UserConversionOverloadFailed:
5883 OS << "overloading failed for user-defined conversion";
5886 case FK_ConstructorOverloadFailed:
5887 OS << "constructor overloading failed";
5890 case FK_DefaultInitOfConst:
5891 OS << "default initialization of a const variable";
5895 OS << "initialization of incomplete type";
5898 case FK_ListInitializationFailed:
5899 OS << "list initialization checker failure";
5902 case FK_VariableLengthArrayHasInitializer:
5903 OS << "variable length array has an initializer";
5906 case FK_PlaceholderType:
5907 OS << "initializer expression isn't contextually valid";
5910 case FK_ListConstructorOverloadFailed:
5911 OS << "list constructor overloading failed";
5914 case FK_InitListElementCopyFailure:
5915 OS << "copy construction of initializer list element failed";
5918 case FK_ExplicitConstructor:
5919 OS << "list copy initialization chose explicit constructor";
5926 case DependentSequence:
5927 OS << "Dependent sequence\n";
5930 case NormalSequence:
5931 OS << "Normal sequence: ";
5935 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5936 if (S != step_begin()) {
5941 case SK_ResolveAddressOfOverloadedFunction:
5942 OS << "resolve address of overloaded function";
5945 case SK_CastDerivedToBaseRValue:
5946 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5949 case SK_CastDerivedToBaseXValue:
5950 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5953 case SK_CastDerivedToBaseLValue:
5954 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5957 case SK_BindReference:
5958 OS << "bind reference to lvalue";
5961 case SK_BindReferenceToTemporary:
5962 OS << "bind reference to a temporary";
5965 case SK_ExtraneousCopyToTemporary:
5966 OS << "extraneous C++03 copy to temporary";
5969 case SK_UserConversion:
5970 OS << "user-defined conversion via " << *S->Function.Function;
5973 case SK_QualificationConversionRValue:
5974 OS << "qualification conversion (rvalue)";
5977 case SK_QualificationConversionXValue:
5978 OS << "qualification conversion (xvalue)";
5981 case SK_QualificationConversionLValue:
5982 OS << "qualification conversion (lvalue)";
5985 case SK_ConversionSequence:
5986 OS << "implicit conversion sequence (";
5987 S->ICS->DebugPrint(); // FIXME: use OS
5991 case SK_ListInitialization:
5992 OS << "list aggregate initialization";
5995 case SK_ListConstructorCall:
5996 OS << "list initialization via constructor";
5999 case SK_UnwrapInitList:
6000 OS << "unwrap reference initializer list";
6003 case SK_RewrapInitList:
6004 OS << "rewrap reference initializer list";
6007 case SK_ConstructorInitialization:
6008 OS << "constructor initialization";
6011 case SK_ZeroInitialization:
6012 OS << "zero initialization";
6015 case SK_CAssignment:
6016 OS << "C assignment";
6020 OS << "string initialization";
6023 case SK_ObjCObjectConversion:
6024 OS << "Objective-C object conversion";
6028 OS << "array initialization";
6031 case SK_ParenthesizedArrayInit:
6032 OS << "parenthesized array initialization";
6035 case SK_PassByIndirectCopyRestore:
6036 OS << "pass by indirect copy and restore";
6039 case SK_PassByIndirectRestore:
6040 OS << "pass by indirect restore";
6043 case SK_ProduceObjCObject:
6044 OS << "Objective-C object retension";
6047 case SK_StdInitializerList:
6048 OS << "std::initializer_list from initializer list";
6054 void InitializationSequence::dump() const {
6058 static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
6059 QualType EntityType,
6060 const Expr *PreInit,
6061 const Expr *PostInit) {
6062 if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
6065 // A narrowing conversion can only appear as the final implicit conversion in
6066 // an initialization sequence.
6067 const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
6068 if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
6071 const ImplicitConversionSequence &ICS = *LastStep.ICS;
6072 const StandardConversionSequence *SCS = 0;
6073 switch (ICS.getKind()) {
6074 case ImplicitConversionSequence::StandardConversion:
6075 SCS = &ICS.Standard;
6077 case ImplicitConversionSequence::UserDefinedConversion:
6078 SCS = &ICS.UserDefined.After;
6080 case ImplicitConversionSequence::AmbiguousConversion:
6081 case ImplicitConversionSequence::EllipsisConversion:
6082 case ImplicitConversionSequence::BadConversion:
6086 // Determine the type prior to the narrowing conversion. If a conversion
6087 // operator was used, this may be different from both the type of the entity
6088 // and of the pre-initialization expression.
6089 QualType PreNarrowingType = PreInit->getType();
6090 if (Seq.step_begin() + 1 != Seq.step_end())
6091 PreNarrowingType = Seq.step_end()[-2].Type;
6093 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
6094 APValue ConstantValue;
6095 QualType ConstantType;
6096 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
6098 case NK_Not_Narrowing:
6099 // No narrowing occurred.
6102 case NK_Type_Narrowing:
6103 // This was a floating-to-integer conversion, which is always considered a
6104 // narrowing conversion even if the value is a constant and can be
6105 // represented exactly as an integer.
6106 S.Diag(PostInit->getLocStart(),
6107 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus0x?
6108 diag::warn_init_list_type_narrowing
6109 : S.isSFINAEContext()?
6110 diag::err_init_list_type_narrowing_sfinae
6111 : diag::err_init_list_type_narrowing)
6112 << PostInit->getSourceRange()
6113 << PreNarrowingType.getLocalUnqualifiedType()
6114 << EntityType.getLocalUnqualifiedType();
6117 case NK_Constant_Narrowing:
6118 // A constant value was narrowed.
6119 S.Diag(PostInit->getLocStart(),
6120 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus0x?
6121 diag::warn_init_list_constant_narrowing
6122 : S.isSFINAEContext()?
6123 diag::err_init_list_constant_narrowing_sfinae
6124 : diag::err_init_list_constant_narrowing)
6125 << PostInit->getSourceRange()
6126 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
6127 << EntityType.getLocalUnqualifiedType();
6130 case NK_Variable_Narrowing:
6131 // A variable's value may have been narrowed.
6132 S.Diag(PostInit->getLocStart(),
6133 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus0x?
6134 diag::warn_init_list_variable_narrowing
6135 : S.isSFINAEContext()?
6136 diag::err_init_list_variable_narrowing_sfinae
6137 : diag::err_init_list_variable_narrowing)
6138 << PostInit->getSourceRange()
6139 << PreNarrowingType.getLocalUnqualifiedType()
6140 << EntityType.getLocalUnqualifiedType();
6144 SmallString<128> StaticCast;
6145 llvm::raw_svector_ostream OS(StaticCast);
6146 OS << "static_cast<";
6147 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
6148 // It's important to use the typedef's name if there is one so that the
6149 // fixit doesn't break code using types like int64_t.
6151 // FIXME: This will break if the typedef requires qualification. But
6152 // getQualifiedNameAsString() includes non-machine-parsable components.
6153 OS << *TT->getDecl();
6154 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
6155 OS << BT->getName(S.getLangOpts());
6157 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
6158 // with a broken cast.
6162 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
6163 << PostInit->getSourceRange()
6164 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
6165 << FixItHint::CreateInsertion(
6166 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
6169 //===----------------------------------------------------------------------===//
6170 // Initialization helper functions
6171 //===----------------------------------------------------------------------===//
6173 Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
6175 if (Init.isInvalid())
6178 Expr *InitE = Init.get();
6179 assert(InitE && "No initialization expression");
6181 InitializationKind Kind
6182 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
6183 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
6184 return !Seq.Failed();
6188 Sema::PerformCopyInitialization(const InitializedEntity &Entity,
6189 SourceLocation EqualLoc,
6191 bool TopLevelOfInitList,
6192 bool AllowExplicit) {
6193 if (Init.isInvalid())
6196 Expr *InitE = Init.get();
6197 assert(InitE && "No initialization expression?");
6199 if (EqualLoc.isInvalid())
6200 EqualLoc = InitE->getLocStart();
6202 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
6205 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
6208 ExprResult Result = Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
6210 if (!Result.isInvalid() && TopLevelOfInitList)
6211 DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
6212 InitE, Result.get());