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::APSInt ConstVal(32);
97 // Return a new array type (C99 6.7.8p22).
98 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
100 ArrayType::Normal, 0);
104 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
106 // We have an array of character type with known size. However,
107 // the size may be smaller or larger than the string we are initializing.
108 // FIXME: Avoid truncation for 64-bit length strings.
109 if (S.getLangOpts().CPlusPlus) {
110 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
111 // For Pascal strings it's OK to strip off the terminating null character,
112 // so the example below is valid:
114 // unsigned char a[2] = "\pa";
119 // [dcl.init.string]p2
120 if (StrLength > CAT->getSize().getZExtValue())
121 S.Diag(Str->getLocStart(),
122 diag::err_initializer_string_for_char_array_too_long)
123 << Str->getSourceRange();
126 if (StrLength-1 > CAT->getSize().getZExtValue())
127 S.Diag(Str->getLocStart(),
128 diag::warn_initializer_string_for_char_array_too_long)
129 << Str->getSourceRange();
132 // Set the type to the actual size that we are initializing. If we have
134 // char x[1] = "foo";
135 // then this will set the string literal's type to char[1].
139 //===----------------------------------------------------------------------===//
140 // Semantic checking for initializer lists.
141 //===----------------------------------------------------------------------===//
143 /// @brief Semantic checking for initializer lists.
145 /// The InitListChecker class contains a set of routines that each
146 /// handle the initialization of a certain kind of entity, e.g.,
147 /// arrays, vectors, struct/union types, scalars, etc. The
148 /// InitListChecker itself performs a recursive walk of the subobject
149 /// structure of the type to be initialized, while stepping through
150 /// the initializer list one element at a time. The IList and Index
151 /// parameters to each of the Check* routines contain the active
152 /// (syntactic) initializer list and the index into that initializer
153 /// list that represents the current initializer. Each routine is
154 /// responsible for moving that Index forward as it consumes elements.
156 /// Each Check* routine also has a StructuredList/StructuredIndex
157 /// arguments, which contains the current "structured" (semantic)
158 /// initializer list and the index into that initializer list where we
159 /// are copying initializers as we map them over to the semantic
160 /// list. Once we have completed our recursive walk of the subobject
161 /// structure, we will have constructed a full semantic initializer
164 /// C99 designators cause changes in the initializer list traversal,
165 /// because they make the initialization "jump" into a specific
166 /// subobject and then continue the initialization from that
167 /// point. CheckDesignatedInitializer() recursively steps into the
168 /// designated subobject and manages backing out the recursion to
169 /// initialize the subobjects after the one designated.
171 class InitListChecker {
174 bool VerifyOnly; // no diagnostics, no structure building
175 bool AllowBraceElision;
176 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
177 InitListExpr *FullyStructuredList;
179 void CheckImplicitInitList(const InitializedEntity &Entity,
180 InitListExpr *ParentIList, QualType T,
181 unsigned &Index, InitListExpr *StructuredList,
182 unsigned &StructuredIndex);
183 void CheckExplicitInitList(const InitializedEntity &Entity,
184 InitListExpr *IList, QualType &T,
185 unsigned &Index, InitListExpr *StructuredList,
186 unsigned &StructuredIndex,
187 bool TopLevelObject = false);
188 void CheckListElementTypes(const InitializedEntity &Entity,
189 InitListExpr *IList, QualType &DeclType,
190 bool SubobjectIsDesignatorContext,
192 InitListExpr *StructuredList,
193 unsigned &StructuredIndex,
194 bool TopLevelObject = false);
195 void CheckSubElementType(const InitializedEntity &Entity,
196 InitListExpr *IList, QualType ElemType,
198 InitListExpr *StructuredList,
199 unsigned &StructuredIndex);
200 void CheckComplexType(const InitializedEntity &Entity,
201 InitListExpr *IList, QualType DeclType,
203 InitListExpr *StructuredList,
204 unsigned &StructuredIndex);
205 void CheckScalarType(const InitializedEntity &Entity,
206 InitListExpr *IList, QualType DeclType,
208 InitListExpr *StructuredList,
209 unsigned &StructuredIndex);
210 void CheckReferenceType(const InitializedEntity &Entity,
211 InitListExpr *IList, QualType DeclType,
213 InitListExpr *StructuredList,
214 unsigned &StructuredIndex);
215 void CheckVectorType(const InitializedEntity &Entity,
216 InitListExpr *IList, QualType DeclType, unsigned &Index,
217 InitListExpr *StructuredList,
218 unsigned &StructuredIndex);
219 void CheckStructUnionTypes(const InitializedEntity &Entity,
220 InitListExpr *IList, QualType DeclType,
221 RecordDecl::field_iterator Field,
222 bool SubobjectIsDesignatorContext, unsigned &Index,
223 InitListExpr *StructuredList,
224 unsigned &StructuredIndex,
225 bool TopLevelObject = false);
226 void CheckArrayType(const InitializedEntity &Entity,
227 InitListExpr *IList, QualType &DeclType,
228 llvm::APSInt elementIndex,
229 bool SubobjectIsDesignatorContext, unsigned &Index,
230 InitListExpr *StructuredList,
231 unsigned &StructuredIndex);
232 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
233 InitListExpr *IList, DesignatedInitExpr *DIE,
235 QualType &CurrentObjectType,
236 RecordDecl::field_iterator *NextField,
237 llvm::APSInt *NextElementIndex,
239 InitListExpr *StructuredList,
240 unsigned &StructuredIndex,
241 bool FinishSubobjectInit,
242 bool TopLevelObject);
243 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
244 QualType CurrentObjectType,
245 InitListExpr *StructuredList,
246 unsigned StructuredIndex,
247 SourceRange InitRange);
248 void UpdateStructuredListElement(InitListExpr *StructuredList,
249 unsigned &StructuredIndex,
251 int numArrayElements(QualType DeclType);
252 int numStructUnionElements(QualType DeclType);
254 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
255 const InitializedEntity &ParentEntity,
256 InitListExpr *ILE, bool &RequiresSecondPass);
257 void FillInValueInitializations(const InitializedEntity &Entity,
258 InitListExpr *ILE, bool &RequiresSecondPass);
259 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
260 Expr *InitExpr, FieldDecl *Field,
261 bool TopLevelObject);
262 void CheckValueInitializable(const InitializedEntity &Entity);
265 InitListChecker(Sema &S, const InitializedEntity &Entity,
266 InitListExpr *IL, QualType &T, bool VerifyOnly,
267 bool AllowBraceElision);
268 bool HadError() { return hadError; }
270 // @brief Retrieves the fully-structured initializer list used for
271 // semantic analysis and code generation.
272 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
274 } // end anonymous namespace
276 void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
278 "CheckValueInitializable is only inteded for verification mode.");
281 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
283 InitializationSequence InitSeq(SemaRef, Entity, Kind, 0, 0);
284 if (InitSeq.Failed())
288 void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
289 const InitializedEntity &ParentEntity,
291 bool &RequiresSecondPass) {
292 SourceLocation Loc = ILE->getLocStart();
293 unsigned NumInits = ILE->getNumInits();
294 InitializedEntity MemberEntity
295 = InitializedEntity::InitializeMember(Field, &ParentEntity);
296 if (Init >= NumInits || !ILE->getInit(Init)) {
297 // FIXME: We probably don't need to handle references
298 // specially here, since value-initialization of references is
299 // handled in InitializationSequence.
300 if (Field->getType()->isReferenceType()) {
301 // C++ [dcl.init.aggr]p9:
302 // If an incomplete or empty initializer-list leaves a
303 // member of reference type uninitialized, the program is
305 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
307 << ILE->getSyntacticForm()->getSourceRange();
308 SemaRef.Diag(Field->getLocation(),
309 diag::note_uninit_reference_member);
314 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
316 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
318 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
323 ExprResult MemberInit
324 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
325 if (MemberInit.isInvalid()) {
332 } else if (Init < NumInits) {
333 ILE->setInit(Init, MemberInit.takeAs<Expr>());
334 } else if (InitSeq.isConstructorInitialization()) {
335 // Value-initialization requires a constructor call, so
336 // extend the initializer list to include the constructor
337 // call and make a note that we'll need to take another pass
338 // through the initializer list.
339 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
340 RequiresSecondPass = true;
342 } else if (InitListExpr *InnerILE
343 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
344 FillInValueInitializations(MemberEntity, InnerILE,
348 /// Recursively replaces NULL values within the given initializer list
349 /// with expressions that perform value-initialization of the
350 /// appropriate type.
352 InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
354 bool &RequiresSecondPass) {
355 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
356 "Should not have void type");
357 SourceLocation Loc = ILE->getLocStart();
358 if (ILE->getSyntacticForm())
359 Loc = ILE->getSyntacticForm()->getLocStart();
361 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
362 if (RType->getDecl()->isUnion() &&
363 ILE->getInitializedFieldInUnion())
364 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
365 Entity, ILE, RequiresSecondPass);
368 for (RecordDecl::field_iterator
369 Field = RType->getDecl()->field_begin(),
370 FieldEnd = RType->getDecl()->field_end();
371 Field != FieldEnd; ++Field) {
372 if (Field->isUnnamedBitfield())
378 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
384 // Only look at the first initialization of a union.
385 if (RType->getDecl()->isUnion())
393 QualType ElementType;
395 InitializedEntity ElementEntity = Entity;
396 unsigned NumInits = ILE->getNumInits();
397 unsigned NumElements = NumInits;
398 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
399 ElementType = AType->getElementType();
400 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
401 NumElements = CAType->getSize().getZExtValue();
402 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
404 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
405 ElementType = VType->getElementType();
406 NumElements = VType->getNumElements();
407 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
410 ElementType = ILE->getType();
413 for (unsigned Init = 0; Init != NumElements; ++Init) {
417 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
418 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
419 ElementEntity.setElementIndex(Init);
421 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
422 if (!InitExpr && !ILE->hasArrayFiller()) {
423 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
425 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
427 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
432 ExprResult ElementInit
433 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
434 if (ElementInit.isInvalid()) {
441 } else if (Init < NumInits) {
442 // For arrays, just set the expression used for value-initialization
443 // of the "holes" in the array.
444 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
445 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
447 ILE->setInit(Init, ElementInit.takeAs<Expr>());
449 // For arrays, just set the expression used for value-initialization
450 // of the rest of elements and exit.
451 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
452 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
456 if (InitSeq.isConstructorInitialization()) {
457 // Value-initialization requires a constructor call, so
458 // extend the initializer list to include the constructor
459 // call and make a note that we'll need to take another pass
460 // through the initializer list.
461 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
462 RequiresSecondPass = true;
465 } else if (InitListExpr *InnerILE
466 = dyn_cast_or_null<InitListExpr>(InitExpr))
467 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
472 InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
473 InitListExpr *IL, QualType &T,
474 bool VerifyOnly, bool AllowBraceElision)
475 : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
478 unsigned newIndex = 0;
479 unsigned newStructuredIndex = 0;
481 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
482 CheckExplicitInitList(Entity, IL, T, newIndex,
483 FullyStructuredList, newStructuredIndex,
484 /*TopLevelObject=*/true);
486 if (!hadError && !VerifyOnly) {
487 bool RequiresSecondPass = false;
488 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
489 if (RequiresSecondPass && !hadError)
490 FillInValueInitializations(Entity, FullyStructuredList,
495 int InitListChecker::numArrayElements(QualType DeclType) {
496 // FIXME: use a proper constant
497 int maxElements = 0x7FFFFFFF;
498 if (const ConstantArrayType *CAT =
499 SemaRef.Context.getAsConstantArrayType(DeclType)) {
500 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
505 int InitListChecker::numStructUnionElements(QualType DeclType) {
506 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
507 int InitializableMembers = 0;
508 for (RecordDecl::field_iterator
509 Field = structDecl->field_begin(),
510 FieldEnd = structDecl->field_end();
511 Field != FieldEnd; ++Field) {
512 if (!Field->isUnnamedBitfield())
513 ++InitializableMembers;
515 if (structDecl->isUnion())
516 return std::min(InitializableMembers, 1);
517 return InitializableMembers - structDecl->hasFlexibleArrayMember();
520 void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
521 InitListExpr *ParentIList,
522 QualType T, unsigned &Index,
523 InitListExpr *StructuredList,
524 unsigned &StructuredIndex) {
527 if (T->isArrayType())
528 maxElements = numArrayElements(T);
529 else if (T->isRecordType())
530 maxElements = numStructUnionElements(T);
531 else if (T->isVectorType())
532 maxElements = T->getAs<VectorType>()->getNumElements();
534 llvm_unreachable("CheckImplicitInitList(): Illegal type");
536 if (maxElements == 0) {
538 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
539 diag::err_implicit_empty_initializer);
545 // Build a structured initializer list corresponding to this subobject.
546 InitListExpr *StructuredSubobjectInitList
547 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
549 SourceRange(ParentIList->getInit(Index)->getLocStart(),
550 ParentIList->getSourceRange().getEnd()));
551 unsigned StructuredSubobjectInitIndex = 0;
553 // Check the element types and build the structural subobject.
554 unsigned StartIndex = Index;
555 CheckListElementTypes(Entity, ParentIList, T,
556 /*SubobjectIsDesignatorContext=*/false, Index,
557 StructuredSubobjectInitList,
558 StructuredSubobjectInitIndex);
561 if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
564 StructuredSubobjectInitList->setType(T);
566 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
567 // Update the structured sub-object initializer so that it's ending
568 // range corresponds with the end of the last initializer it used.
569 if (EndIndex < ParentIList->getNumInits()) {
570 SourceLocation EndLoc
571 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
572 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
575 // Complain about missing braces.
576 if (T->isArrayType() || T->isRecordType()) {
577 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
578 AllowBraceElision ? diag::warn_missing_braces :
579 diag::err_missing_braces)
580 << StructuredSubobjectInitList->getSourceRange()
581 << FixItHint::CreateInsertion(
582 StructuredSubobjectInitList->getLocStart(), "{")
583 << FixItHint::CreateInsertion(
584 SemaRef.PP.getLocForEndOfToken(
585 StructuredSubobjectInitList->getLocEnd()),
587 if (!AllowBraceElision)
593 void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
594 InitListExpr *IList, QualType &T,
596 InitListExpr *StructuredList,
597 unsigned &StructuredIndex,
598 bool TopLevelObject) {
599 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
601 SyntacticToSemantic[IList] = StructuredList;
602 StructuredList->setSyntacticForm(IList);
604 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
605 Index, StructuredList, StructuredIndex, TopLevelObject);
608 if (!ExprTy->isArrayType())
609 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
610 IList->setType(ExprTy);
611 StructuredList->setType(ExprTy);
616 if (Index < IList->getNumInits()) {
617 // We have leftover initializers
619 if (SemaRef.getLangOpts().CPlusPlus ||
620 (SemaRef.getLangOpts().OpenCL &&
621 IList->getType()->isVectorType())) {
627 if (StructuredIndex == 1 &&
628 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
629 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
630 if (SemaRef.getLangOpts().CPlusPlus) {
631 DK = diag::err_excess_initializers_in_char_array_initializer;
635 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
636 << IList->getInit(Index)->getSourceRange();
637 } else if (!T->isIncompleteType()) {
638 // Don't complain for incomplete types, since we'll get an error
640 QualType CurrentObjectType = StructuredList->getType();
642 CurrentObjectType->isArrayType()? 0 :
643 CurrentObjectType->isVectorType()? 1 :
644 CurrentObjectType->isScalarType()? 2 :
645 CurrentObjectType->isUnionType()? 3 :
648 unsigned DK = diag::warn_excess_initializers;
649 if (SemaRef.getLangOpts().CPlusPlus) {
650 DK = diag::err_excess_initializers;
653 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
654 DK = diag::err_excess_initializers;
658 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
659 << initKind << IList->getInit(Index)->getSourceRange();
663 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
665 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
666 << IList->getSourceRange()
667 << FixItHint::CreateRemoval(IList->getLocStart())
668 << FixItHint::CreateRemoval(IList->getLocEnd());
671 void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
674 bool SubobjectIsDesignatorContext,
676 InitListExpr *StructuredList,
677 unsigned &StructuredIndex,
678 bool TopLevelObject) {
679 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
680 // Explicitly braced initializer for complex type can be real+imaginary
682 CheckComplexType(Entity, IList, DeclType, Index,
683 StructuredList, StructuredIndex);
684 } else if (DeclType->isScalarType()) {
685 CheckScalarType(Entity, IList, DeclType, Index,
686 StructuredList, StructuredIndex);
687 } else if (DeclType->isVectorType()) {
688 CheckVectorType(Entity, IList, DeclType, Index,
689 StructuredList, StructuredIndex);
690 } else if (DeclType->isAggregateType()) {
691 if (DeclType->isRecordType()) {
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);
705 llvm_unreachable("Aggregate that isn't a structure or array?!");
706 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
707 // This type is invalid, issue a diagnostic.
710 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
713 } else if (DeclType->isRecordType()) {
714 // C++ [dcl.init]p14:
715 // [...] If the class is an aggregate (8.5.1), and the initializer
716 // is a brace-enclosed list, see 8.5.1.
718 // Note: 8.5.1 is handled below; here, we diagnose the case where
719 // we have an initializer list and a destination type that is not
721 // FIXME: In C++0x, this is yet another form of initialization.
723 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
724 << DeclType << IList->getSourceRange();
726 } else if (DeclType->isReferenceType()) {
727 CheckReferenceType(Entity, IList, DeclType, Index,
728 StructuredList, StructuredIndex);
729 } else if (DeclType->isObjCObjectType()) {
731 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
736 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
742 void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
746 InitListExpr *StructuredList,
747 unsigned &StructuredIndex) {
748 Expr *expr = IList->getInit(Index);
749 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
750 unsigned newIndex = 0;
751 unsigned newStructuredIndex = 0;
752 InitListExpr *newStructuredList
753 = getStructuredSubobjectInit(IList, Index, ElemType,
754 StructuredList, StructuredIndex,
755 SubInitList->getSourceRange());
756 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
757 newStructuredList, newStructuredIndex);
761 } else if (ElemType->isScalarType()) {
762 return CheckScalarType(Entity, IList, ElemType, Index,
763 StructuredList, StructuredIndex);
764 } else if (ElemType->isReferenceType()) {
765 return CheckReferenceType(Entity, IList, ElemType, Index,
766 StructuredList, StructuredIndex);
769 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
770 // arrayType can be incomplete if we're initializing a flexible
771 // array member. There's nothing we can do with the completed
772 // type here, though.
774 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
776 CheckStringInit(Str, ElemType, arrayType, SemaRef);
777 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
783 // Fall through for subaggregate initialization.
785 } else if (SemaRef.getLangOpts().CPlusPlus) {
786 // C++ [dcl.init.aggr]p12:
787 // All implicit type conversions (clause 4) are considered when
788 // initializing the aggregate member with an initializer from
789 // an initializer-list. If the initializer can initialize a
790 // member, the member is initialized. [...]
792 // FIXME: Better EqualLoc?
793 InitializationKind Kind =
794 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
795 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
800 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
801 if (Result.isInvalid())
804 UpdateStructuredListElement(StructuredList, StructuredIndex,
805 Result.takeAs<Expr>());
811 // Fall through for subaggregate initialization
815 // The initializer for a structure or union object that has
816 // automatic storage duration shall be either an initializer
817 // list as described below, or a single expression that has
818 // compatible structure or union type. In the latter case, the
819 // initial value of the object, including unnamed members, is
820 // that of the expression.
821 ExprResult ExprRes = SemaRef.Owned(expr);
822 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
823 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
825 == Sema::Compatible) {
826 if (ExprRes.isInvalid())
829 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
830 if (ExprRes.isInvalid())
833 UpdateStructuredListElement(StructuredList, StructuredIndex,
834 ExprRes.takeAs<Expr>());
839 // Fall through for subaggregate initialization
842 // C++ [dcl.init.aggr]p12:
844 // [...] Otherwise, if the member is itself a non-empty
845 // subaggregate, brace elision is assumed and the initializer is
846 // considered for the initialization of the first member of
848 if (!SemaRef.getLangOpts().OpenCL &&
849 (ElemType->isAggregateType() || ElemType->isVectorType())) {
850 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
855 // We cannot initialize this element, so let
856 // PerformCopyInitialization produce the appropriate diagnostic.
857 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
859 /*TopLevelOfInitList=*/true);
867 void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
868 InitListExpr *IList, QualType DeclType,
870 InitListExpr *StructuredList,
871 unsigned &StructuredIndex) {
872 assert(Index == 0 && "Index in explicit init list must be zero");
874 // As an extension, clang supports complex initializers, which initialize
875 // a complex number component-wise. When an explicit initializer list for
876 // a complex number contains two two initializers, this extension kicks in:
877 // it exepcts the initializer list to contain two elements convertible to
878 // the element type of the complex type. The first element initializes
879 // the real part, and the second element intitializes the imaginary part.
881 if (IList->getNumInits() != 2)
882 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
885 // This is an extension in C. (The builtin _Complex type does not exist
886 // in the C++ standard.)
887 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
888 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
889 << IList->getSourceRange();
891 // Initialize the complex number.
892 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
893 InitializedEntity ElementEntity =
894 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
896 for (unsigned i = 0; i < 2; ++i) {
897 ElementEntity.setElementIndex(Index);
898 CheckSubElementType(ElementEntity, IList, elementType, Index,
899 StructuredList, StructuredIndex);
904 void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
905 InitListExpr *IList, QualType DeclType,
907 InitListExpr *StructuredList,
908 unsigned &StructuredIndex) {
909 if (Index >= IList->getNumInits()) {
911 SemaRef.Diag(IList->getLocStart(),
912 SemaRef.getLangOpts().CPlusPlus0x ?
913 diag::warn_cxx98_compat_empty_scalar_initializer :
914 diag::err_empty_scalar_initializer)
915 << IList->getSourceRange();
916 hadError = !SemaRef.getLangOpts().CPlusPlus0x;
922 Expr *expr = IList->getInit(Index);
923 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
925 SemaRef.Diag(SubIList->getLocStart(),
926 diag::warn_many_braces_around_scalar_init)
927 << SubIList->getSourceRange();
929 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
932 } else if (isa<DesignatedInitExpr>(expr)) {
934 SemaRef.Diag(expr->getLocStart(),
935 diag::err_designator_for_scalar_init)
936 << DeclType << expr->getSourceRange();
944 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
951 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
953 /*TopLevelOfInitList=*/true);
955 Expr *ResultExpr = 0;
957 if (Result.isInvalid())
958 hadError = true; // types weren't compatible.
960 ResultExpr = Result.takeAs<Expr>();
962 if (ResultExpr != expr) {
963 // The type was promoted, update initializer list.
964 IList->setInit(Index, ResultExpr);
970 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
974 void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
975 InitListExpr *IList, QualType DeclType,
977 InitListExpr *StructuredList,
978 unsigned &StructuredIndex) {
979 if (Index >= IList->getNumInits()) {
980 // FIXME: It would be wonderful if we could point at the actual member. In
981 // general, it would be useful to pass location information down the stack,
982 // so that we know the location (or decl) of the "current object" being
985 SemaRef.Diag(IList->getLocStart(),
986 diag::err_init_reference_member_uninitialized)
988 << IList->getSourceRange();
995 Expr *expr = IList->getInit(Index);
996 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus0x) {
998 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
999 << DeclType << IList->getSourceRange();
1007 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1014 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1015 SemaRef.Owned(expr),
1016 /*TopLevelOfInitList=*/true);
1018 if (Result.isInvalid())
1021 expr = Result.takeAs<Expr>();
1022 IList->setInit(Index, expr);
1027 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1031 void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1032 InitListExpr *IList, QualType DeclType,
1034 InitListExpr *StructuredList,
1035 unsigned &StructuredIndex) {
1036 const VectorType *VT = DeclType->getAs<VectorType>();
1037 unsigned maxElements = VT->getNumElements();
1038 unsigned numEltsInit = 0;
1039 QualType elementType = VT->getElementType();
1041 if (Index >= IList->getNumInits()) {
1042 // Make sure the element type can be value-initialized.
1044 CheckValueInitializable(
1045 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1049 if (!SemaRef.getLangOpts().OpenCL) {
1050 // If the initializing element is a vector, try to copy-initialize
1051 // instead of breaking it apart (which is doomed to failure anyway).
1052 Expr *Init = IList->getInit(Index);
1053 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1055 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1062 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
1063 SemaRef.Owned(Init),
1064 /*TopLevelOfInitList=*/true);
1066 Expr *ResultExpr = 0;
1067 if (Result.isInvalid())
1068 hadError = true; // types weren't compatible.
1070 ResultExpr = Result.takeAs<Expr>();
1072 if (ResultExpr != Init) {
1073 // The type was promoted, update initializer list.
1074 IList->setInit(Index, ResultExpr);
1080 UpdateStructuredListElement(StructuredList, StructuredIndex,
1086 InitializedEntity ElementEntity =
1087 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1089 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1090 // Don't attempt to go past the end of the init list
1091 if (Index >= IList->getNumInits()) {
1093 CheckValueInitializable(ElementEntity);
1097 ElementEntity.setElementIndex(Index);
1098 CheckSubElementType(ElementEntity, IList, elementType, Index,
1099 StructuredList, StructuredIndex);
1104 InitializedEntity ElementEntity =
1105 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1107 // OpenCL initializers allows vectors to be constructed from vectors.
1108 for (unsigned i = 0; i < maxElements; ++i) {
1109 // Don't attempt to go past the end of the init list
1110 if (Index >= IList->getNumInits())
1113 ElementEntity.setElementIndex(Index);
1115 QualType IType = IList->getInit(Index)->getType();
1116 if (!IType->isVectorType()) {
1117 CheckSubElementType(ElementEntity, IList, elementType, Index,
1118 StructuredList, StructuredIndex);
1122 const VectorType *IVT = IType->getAs<VectorType>();
1123 unsigned numIElts = IVT->getNumElements();
1125 if (IType->isExtVectorType())
1126 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1128 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1129 IVT->getVectorKind());
1130 CheckSubElementType(ElementEntity, IList, VecType, Index,
1131 StructuredList, StructuredIndex);
1132 numEltsInit += numIElts;
1136 // OpenCL requires all elements to be initialized.
1137 if (numEltsInit != maxElements) {
1139 SemaRef.Diag(IList->getLocStart(),
1140 diag::err_vector_incorrect_num_initializers)
1141 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1146 void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1147 InitListExpr *IList, QualType &DeclType,
1148 llvm::APSInt elementIndex,
1149 bool SubobjectIsDesignatorContext,
1151 InitListExpr *StructuredList,
1152 unsigned &StructuredIndex) {
1153 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1155 // Check for the special-case of initializing an array with a string.
1156 if (Index < IList->getNumInits()) {
1157 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
1159 // We place the string literal directly into the resulting
1160 // initializer list. This is the only place where the structure
1161 // of the structured initializer list doesn't match exactly,
1162 // because doing so would involve allocating one character
1163 // constant for each string.
1165 CheckStringInit(Str, DeclType, arrayType, SemaRef);
1166 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1167 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1173 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1174 // Check for VLAs; in standard C it would be possible to check this
1175 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1176 // them in all sorts of strange places).
1178 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1179 diag::err_variable_object_no_init)
1180 << VAT->getSizeExpr()->getSourceRange();
1187 // We might know the maximum number of elements in advance.
1188 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1189 elementIndex.isUnsigned());
1190 bool maxElementsKnown = false;
1191 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
1192 maxElements = CAT->getSize();
1193 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
1194 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1195 maxElementsKnown = true;
1198 QualType elementType = arrayType->getElementType();
1199 while (Index < IList->getNumInits()) {
1200 Expr *Init = IList->getInit(Index);
1201 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1202 // If we're not the subobject that matches up with the '{' for
1203 // the designator, we shouldn't be handling the
1204 // designator. Return immediately.
1205 if (!SubobjectIsDesignatorContext)
1208 // Handle this designated initializer. elementIndex will be
1209 // updated to be the next array element we'll initialize.
1210 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1211 DeclType, 0, &elementIndex, Index,
1212 StructuredList, StructuredIndex, true,
1218 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1219 maxElements = maxElements.extend(elementIndex.getBitWidth());
1220 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1221 elementIndex = elementIndex.extend(maxElements.getBitWidth());
1222 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1224 // If the array is of incomplete type, keep track of the number of
1225 // elements in the initializer.
1226 if (!maxElementsKnown && elementIndex > maxElements)
1227 maxElements = elementIndex;
1232 // If we know the maximum number of elements, and we've already
1233 // hit it, stop consuming elements in the initializer list.
1234 if (maxElementsKnown && elementIndex == maxElements)
1237 InitializedEntity ElementEntity =
1238 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1240 // Check this element.
1241 CheckSubElementType(ElementEntity, IList, elementType, Index,
1242 StructuredList, StructuredIndex);
1245 // If the array is of incomplete type, keep track of the number of
1246 // elements in the initializer.
1247 if (!maxElementsKnown && elementIndex > maxElements)
1248 maxElements = elementIndex;
1250 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
1251 // If this is an incomplete array type, the actual type needs to
1252 // be calculated here.
1253 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
1254 if (maxElements == Zero) {
1255 // Sizing an array implicitly to zero is not allowed by ISO C,
1256 // but is supported by GNU.
1257 SemaRef.Diag(IList->getLocStart(),
1258 diag::ext_typecheck_zero_array_size);
1261 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
1262 ArrayType::Normal, 0);
1264 if (!hadError && VerifyOnly) {
1265 // Check if there are any members of the array that get value-initialized.
1266 // If so, check if doing that is possible.
1267 // FIXME: This needs to detect holes left by designated initializers too.
1268 if (maxElementsKnown && elementIndex < maxElements)
1269 CheckValueInitializable(InitializedEntity::InitializeElement(
1270 SemaRef.Context, 0, Entity));
1274 bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1277 bool TopLevelObject) {
1278 // Handle GNU flexible array initializers.
1279 unsigned FlexArrayDiag;
1280 if (isa<InitListExpr>(InitExpr) &&
1281 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1282 // Empty flexible array init always allowed as an extension
1283 FlexArrayDiag = diag::ext_flexible_array_init;
1284 } else if (SemaRef.getLangOpts().CPlusPlus) {
1285 // Disallow flexible array init in C++; it is not required for gcc
1286 // compatibility, and it needs work to IRGen correctly in general.
1287 FlexArrayDiag = diag::err_flexible_array_init;
1288 } else if (!TopLevelObject) {
1289 // Disallow flexible array init on non-top-level object
1290 FlexArrayDiag = diag::err_flexible_array_init;
1291 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1292 // Disallow flexible array init on anything which is not a variable.
1293 FlexArrayDiag = diag::err_flexible_array_init;
1294 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1295 // Disallow flexible array init on local variables.
1296 FlexArrayDiag = diag::err_flexible_array_init;
1298 // Allow other cases.
1299 FlexArrayDiag = diag::ext_flexible_array_init;
1303 SemaRef.Diag(InitExpr->getLocStart(),
1305 << InitExpr->getLocStart();
1306 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1310 return FlexArrayDiag != diag::ext_flexible_array_init;
1313 void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
1314 InitListExpr *IList,
1316 RecordDecl::field_iterator Field,
1317 bool SubobjectIsDesignatorContext,
1319 InitListExpr *StructuredList,
1320 unsigned &StructuredIndex,
1321 bool TopLevelObject) {
1322 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
1324 // If the record is invalid, some of it's members are invalid. To avoid
1325 // confusion, we forgo checking the intializer for the entire record.
1326 if (structDecl->isInvalidDecl()) {
1331 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1332 // Value-initialize the first named member of the union.
1333 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1334 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1335 Field != FieldEnd; ++Field) {
1336 if (Field->getDeclName()) {
1338 CheckValueInitializable(
1339 InitializedEntity::InitializeMember(*Field, &Entity));
1341 StructuredList->setInitializedFieldInUnion(*Field);
1348 // If structDecl is a forward declaration, this loop won't do
1349 // anything except look at designated initializers; That's okay,
1350 // because an error should get printed out elsewhere. It might be
1351 // worthwhile to skip over the rest of the initializer, though.
1352 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1353 RecordDecl::field_iterator FieldEnd = RD->field_end();
1354 bool InitializedSomething = false;
1355 bool CheckForMissingFields = true;
1356 while (Index < IList->getNumInits()) {
1357 Expr *Init = IList->getInit(Index);
1359 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1360 // If we're not the subobject that matches up with the '{' for
1361 // the designator, we shouldn't be handling the
1362 // designator. Return immediately.
1363 if (!SubobjectIsDesignatorContext)
1366 // Handle this designated initializer. Field will be updated to
1367 // the next field that we'll be initializing.
1368 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1369 DeclType, &Field, 0, Index,
1370 StructuredList, StructuredIndex,
1371 true, TopLevelObject))
1374 InitializedSomething = true;
1376 // Disable check for missing fields when designators are used.
1377 // This matches gcc behaviour.
1378 CheckForMissingFields = false;
1382 if (Field == FieldEnd) {
1383 // We've run out of fields. We're done.
1387 // We've already initialized a member of a union. We're done.
1388 if (InitializedSomething && DeclType->isUnionType())
1391 // If we've hit the flexible array member at the end, we're done.
1392 if (Field->getType()->isIncompleteArrayType())
1395 if (Field->isUnnamedBitfield()) {
1396 // Don't initialize unnamed bitfields, e.g. "int : 20;"
1401 // Make sure we can use this declaration.
1404 InvalidUse = !SemaRef.CanUseDecl(*Field);
1406 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1407 IList->getInit(Index)->getLocStart());
1415 InitializedEntity MemberEntity =
1416 InitializedEntity::InitializeMember(*Field, &Entity);
1417 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1418 StructuredList, StructuredIndex);
1419 InitializedSomething = true;
1421 if (DeclType->isUnionType() && !VerifyOnly) {
1422 // Initialize the first field within the union.
1423 StructuredList->setInitializedFieldInUnion(*Field);
1429 // Emit warnings for missing struct field initializers.
1430 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1431 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1432 !DeclType->isUnionType()) {
1433 // It is possible we have one or more unnamed bitfields remaining.
1434 // Find first (if any) named field and emit warning.
1435 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1437 if (!it->isUnnamedBitfield()) {
1438 SemaRef.Diag(IList->getSourceRange().getEnd(),
1439 diag::warn_missing_field_initializers) << it->getName();
1445 // Check that any remaining fields can be value-initialized.
1446 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1447 !Field->getType()->isIncompleteArrayType()) {
1448 // FIXME: Should check for holes left by designated initializers too.
1449 for (; Field != FieldEnd && !hadError; ++Field) {
1450 if (!Field->isUnnamedBitfield())
1451 CheckValueInitializable(
1452 InitializedEntity::InitializeMember(*Field, &Entity));
1456 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
1457 Index >= IList->getNumInits())
1460 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1467 InitializedEntity MemberEntity =
1468 InitializedEntity::InitializeMember(*Field, &Entity);
1470 if (isa<InitListExpr>(IList->getInit(Index)))
1471 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1472 StructuredList, StructuredIndex);
1474 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
1475 StructuredList, StructuredIndex);
1478 /// \brief Expand a field designator that refers to a member of an
1479 /// anonymous struct or union into a series of field designators that
1480 /// refers to the field within the appropriate subobject.
1482 static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1483 DesignatedInitExpr *DIE,
1485 IndirectFieldDecl *IndirectField) {
1486 typedef DesignatedInitExpr::Designator Designator;
1488 // Build the replacement designators.
1489 SmallVector<Designator, 4> Replacements;
1490 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1491 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1493 Replacements.push_back(Designator((IdentifierInfo *)0,
1494 DIE->getDesignator(DesigIdx)->getDotLoc(),
1495 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1497 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1499 assert(isa<FieldDecl>(*PI));
1500 Replacements.back().setField(cast<FieldDecl>(*PI));
1503 // Expand the current designator into the set of replacement
1504 // designators, so we have a full subobject path down to where the
1505 // member of the anonymous struct/union is actually stored.
1506 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
1507 &Replacements[0] + Replacements.size());
1510 /// \brief Given an implicit anonymous field, search the IndirectField that
1511 /// corresponds to FieldName.
1512 static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1513 IdentifierInfo *FieldName) {
1514 assert(AnonField->isAnonymousStructOrUnion());
1515 Decl *NextDecl = AnonField->getNextDeclInContext();
1516 while (IndirectFieldDecl *IF =
1517 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
1518 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1520 NextDecl = NextDecl->getNextDeclInContext();
1525 static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1526 DesignatedInitExpr *DIE) {
1527 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1528 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1529 for (unsigned I = 0; I < NumIndexExprs; ++I)
1530 IndexExprs[I] = DIE->getSubExpr(I + 1);
1531 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1532 DIE->size(), IndexExprs.data(),
1533 NumIndexExprs, DIE->getEqualOrColonLoc(),
1534 DIE->usesGNUSyntax(), DIE->getInit());
1539 // Callback to only accept typo corrections that are for field members of
1540 // the given struct or union.
1541 class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1543 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1546 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1547 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1548 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1557 /// @brief Check the well-formedness of a C99 designated initializer.
1559 /// Determines whether the designated initializer @p DIE, which
1560 /// resides at the given @p Index within the initializer list @p
1561 /// IList, is well-formed for a current object of type @p DeclType
1562 /// (C99 6.7.8). The actual subobject that this designator refers to
1563 /// within the current subobject is returned in either
1564 /// @p NextField or @p NextElementIndex (whichever is appropriate).
1566 /// @param IList The initializer list in which this designated
1567 /// initializer occurs.
1569 /// @param DIE The designated initializer expression.
1571 /// @param DesigIdx The index of the current designator.
1573 /// @param DeclType The type of the "current object" (C99 6.7.8p17),
1574 /// into which the designation in @p DIE should refer.
1576 /// @param NextField If non-NULL and the first designator in @p DIE is
1577 /// a field, this will be set to the field declaration corresponding
1578 /// to the field named by the designator.
1580 /// @param NextElementIndex If non-NULL and the first designator in @p
1581 /// DIE is an array designator or GNU array-range designator, this
1582 /// will be set to the last index initialized by this designator.
1584 /// @param Index Index into @p IList where the designated initializer
1587 /// @param StructuredList The initializer list expression that
1588 /// describes all of the subobject initializers in the order they'll
1589 /// actually be initialized.
1591 /// @returns true if there was an error, false otherwise.
1593 InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
1594 InitListExpr *IList,
1595 DesignatedInitExpr *DIE,
1597 QualType &CurrentObjectType,
1598 RecordDecl::field_iterator *NextField,
1599 llvm::APSInt *NextElementIndex,
1601 InitListExpr *StructuredList,
1602 unsigned &StructuredIndex,
1603 bool FinishSubobjectInit,
1604 bool TopLevelObject) {
1605 if (DesigIdx == DIE->size()) {
1606 // Check the actual initialization for the designated object type.
1607 bool prevHadError = hadError;
1609 // Temporarily remove the designator expression from the
1610 // initializer list that the child calls see, so that we don't try
1611 // to re-process the designator.
1612 unsigned OldIndex = Index;
1613 IList->setInit(OldIndex, DIE->getInit());
1615 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
1616 StructuredList, StructuredIndex);
1618 // Restore the designated initializer expression in the syntactic
1619 // form of the initializer list.
1620 if (IList->getInit(OldIndex) != DIE->getInit())
1621 DIE->setInit(IList->getInit(OldIndex));
1622 IList->setInit(OldIndex, DIE);
1624 return hadError && !prevHadError;
1627 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
1628 bool IsFirstDesignator = (DesigIdx == 0);
1630 assert((IsFirstDesignator || StructuredList) &&
1631 "Need a non-designated initializer list to start from");
1633 // Determine the structural initializer list that corresponds to the
1634 // current subobject.
1635 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
1636 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1637 StructuredList, StructuredIndex,
1638 SourceRange(D->getStartLocation(),
1639 DIE->getSourceRange().getEnd()));
1640 assert(StructuredList && "Expected a structured initializer list");
1643 if (D->isFieldDesignator()) {
1646 // If a designator has the form
1650 // then the current object (defined below) shall have
1651 // structure or union type and the identifier shall be the
1652 // name of a member of that type.
1653 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
1655 SourceLocation Loc = D->getDotLoc();
1656 if (Loc.isInvalid())
1657 Loc = D->getFieldLoc();
1659 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1660 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
1665 // Note: we perform a linear search of the fields here, despite
1666 // the fact that we have a faster lookup method, because we always
1667 // need to compute the field's index.
1668 FieldDecl *KnownField = D->getField();
1669 IdentifierInfo *FieldName = D->getFieldName();
1670 unsigned FieldIndex = 0;
1671 RecordDecl::field_iterator
1672 Field = RT->getDecl()->field_begin(),
1673 FieldEnd = RT->getDecl()->field_end();
1674 for (; Field != FieldEnd; ++Field) {
1675 if (Field->isUnnamedBitfield())
1678 // If we find a field representing an anonymous field, look in the
1679 // IndirectFieldDecl that follow for the designated initializer.
1680 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1681 if (IndirectFieldDecl *IF =
1682 FindIndirectFieldDesignator(*Field, FieldName)) {
1683 // In verify mode, don't modify the original.
1685 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
1686 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1687 D = DIE->getDesignator(DesigIdx);
1691 if (KnownField && KnownField == *Field)
1693 if (FieldName && FieldName == Field->getIdentifier())
1699 if (Field == FieldEnd) {
1702 return true; // No typo correction when just trying this out.
1705 // There was no normal field in the struct with the designated
1706 // name. Perform another lookup for this name, which may find
1707 // something that we can't designate (e.g., a member function),
1708 // may find nothing, or may find a member of an anonymous
1710 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
1711 FieldDecl *ReplacementField = 0;
1712 if (Lookup.first == Lookup.second) {
1713 // Name lookup didn't find anything. Determine whether this
1714 // was a typo for another field name.
1715 FieldInitializerValidatorCCC Validator(RT->getDecl());
1716 TypoCorrection Corrected = SemaRef.CorrectTypo(
1717 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1718 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator,
1721 std::string CorrectedStr(
1722 Corrected.getAsString(SemaRef.getLangOpts()));
1723 std::string CorrectedQuotedStr(
1724 Corrected.getQuoted(SemaRef.getLangOpts()));
1725 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
1726 SemaRef.Diag(D->getFieldLoc(),
1727 diag::err_field_designator_unknown_suggest)
1728 << FieldName << CurrentObjectType << CorrectedQuotedStr
1729 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
1730 SemaRef.Diag(ReplacementField->getLocation(),
1731 diag::note_previous_decl) << CorrectedQuotedStr;
1734 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1735 << FieldName << CurrentObjectType;
1741 if (!ReplacementField) {
1742 // Name lookup found something, but it wasn't a field.
1743 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
1745 SemaRef.Diag((*Lookup.first)->getLocation(),
1746 diag::note_field_designator_found);
1752 // The replacement field comes from typo correction; find it
1753 // in the list of fields.
1755 Field = RT->getDecl()->field_begin();
1756 for (; Field != FieldEnd; ++Field) {
1757 if (Field->isUnnamedBitfield())
1760 if (ReplacementField == *Field ||
1761 Field->getIdentifier() == ReplacementField->getIdentifier())
1769 // All of the fields of a union are located at the same place in
1770 // the initializer list.
1771 if (RT->getDecl()->isUnion()) {
1774 StructuredList->setInitializedFieldInUnion(*Field);
1777 // Make sure we can use this declaration.
1780 InvalidUse = !SemaRef.CanUseDecl(*Field);
1782 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1789 // Update the designator with the field declaration.
1790 D->setField(*Field);
1792 // Make sure that our non-designated initializer list has space
1793 // for a subobject corresponding to this field.
1794 if (FieldIndex >= StructuredList->getNumInits())
1795 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1798 // This designator names a flexible array member.
1799 if (Field->getType()->isIncompleteArrayType()) {
1800 bool Invalid = false;
1801 if ((DesigIdx + 1) != DIE->size()) {
1802 // We can't designate an object within the flexible array
1803 // member (because GCC doesn't allow it).
1805 DesignatedInitExpr::Designator *NextD
1806 = DIE->getDesignator(DesigIdx + 1);
1807 SemaRef.Diag(NextD->getStartLocation(),
1808 diag::err_designator_into_flexible_array_member)
1809 << SourceRange(NextD->getStartLocation(),
1810 DIE->getSourceRange().getEnd());
1811 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1817 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1818 !isa<StringLiteral>(DIE->getInit())) {
1819 // The initializer is not an initializer list.
1821 SemaRef.Diag(DIE->getInit()->getLocStart(),
1822 diag::err_flexible_array_init_needs_braces)
1823 << DIE->getInit()->getSourceRange();
1824 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1830 // Check GNU flexible array initializer.
1831 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1840 // Initialize the array.
1841 bool prevHadError = hadError;
1842 unsigned newStructuredIndex = FieldIndex;
1843 unsigned OldIndex = Index;
1844 IList->setInit(Index, DIE->getInit());
1846 InitializedEntity MemberEntity =
1847 InitializedEntity::InitializeMember(*Field, &Entity);
1848 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1849 StructuredList, newStructuredIndex);
1851 IList->setInit(OldIndex, DIE);
1852 if (hadError && !prevHadError) {
1857 StructuredIndex = FieldIndex;
1861 // Recurse to check later designated subobjects.
1862 QualType FieldType = (*Field)->getType();
1863 unsigned newStructuredIndex = FieldIndex;
1865 InitializedEntity MemberEntity =
1866 InitializedEntity::InitializeMember(*Field, &Entity);
1867 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1868 FieldType, 0, 0, Index,
1869 StructuredList, newStructuredIndex,
1874 // Find the position of the next field to be initialized in this
1879 // If this the first designator, our caller will continue checking
1880 // the rest of this struct/class/union subobject.
1881 if (IsFirstDesignator) {
1884 StructuredIndex = FieldIndex;
1888 if (!FinishSubobjectInit)
1891 // We've already initialized something in the union; we're done.
1892 if (RT->getDecl()->isUnion())
1895 // Check the remaining fields within this class/struct/union subobject.
1896 bool prevHadError = hadError;
1898 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
1899 StructuredList, FieldIndex);
1900 return hadError && !prevHadError;
1905 // If a designator has the form
1907 // [ constant-expression ]
1909 // then the current object (defined below) shall have array
1910 // type and the expression shall be an integer constant
1911 // expression. If the array is of unknown size, any
1912 // nonnegative value is valid.
1914 // Additionally, cope with the GNU extension that permits
1915 // designators of the form
1917 // [ constant-expression ... constant-expression ]
1918 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
1921 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1922 << CurrentObjectType;
1927 Expr *IndexExpr = 0;
1928 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1929 if (D->isArrayDesignator()) {
1930 IndexExpr = DIE->getArrayIndex(*D);
1931 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
1932 DesignatedEndIndex = DesignatedStartIndex;
1934 assert(D->isArrayRangeDesignator() && "Need array-range designator");
1936 DesignatedStartIndex =
1937 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
1938 DesignatedEndIndex =
1939 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
1940 IndexExpr = DIE->getArrayRangeEnd(*D);
1942 // Codegen can't handle evaluating array range designators that have side
1943 // effects, because we replicate the AST value for each initialized element.
1944 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1945 // elements with something that has a side effect, so codegen can emit an
1946 // "error unsupported" error instead of miscompiling the app.
1947 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
1948 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
1949 FullyStructuredList->sawArrayRangeDesignator();
1952 if (isa<ConstantArrayType>(AT)) {
1953 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
1954 DesignatedStartIndex
1955 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1956 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1958 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1959 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1960 if (DesignatedEndIndex >= MaxElements) {
1962 SemaRef.Diag(IndexExpr->getLocStart(),
1963 diag::err_array_designator_too_large)
1964 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1965 << IndexExpr->getSourceRange();
1970 // Make sure the bit-widths and signedness match.
1971 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1973 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
1974 else if (DesignatedStartIndex.getBitWidth() <
1975 DesignatedEndIndex.getBitWidth())
1976 DesignatedStartIndex
1977 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1978 DesignatedStartIndex.setIsUnsigned(true);
1979 DesignatedEndIndex.setIsUnsigned(true);
1982 // Make sure that our non-designated initializer list has space
1983 // for a subobject corresponding to this array element.
1985 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
1986 StructuredList->resizeInits(SemaRef.Context,
1987 DesignatedEndIndex.getZExtValue() + 1);
1989 // Repeatedly perform subobject initializations in the range
1990 // [DesignatedStartIndex, DesignatedEndIndex].
1992 // Move to the next designator
1993 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1994 unsigned OldIndex = Index;
1996 InitializedEntity ElementEntity =
1997 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1999 while (DesignatedStartIndex <= DesignatedEndIndex) {
2000 // Recurse to check later designated subobjects.
2001 QualType ElementType = AT->getElementType();
2004 ElementEntity.setElementIndex(ElementIndex);
2005 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2006 ElementType, 0, 0, Index,
2007 StructuredList, ElementIndex,
2008 (DesignatedStartIndex == DesignatedEndIndex),
2012 // Move to the next index in the array that we'll be initializing.
2013 ++DesignatedStartIndex;
2014 ElementIndex = DesignatedStartIndex.getZExtValue();
2017 // If this the first designator, our caller will continue checking
2018 // the rest of this array subobject.
2019 if (IsFirstDesignator) {
2020 if (NextElementIndex)
2021 *NextElementIndex = DesignatedStartIndex;
2022 StructuredIndex = ElementIndex;
2026 if (!FinishSubobjectInit)
2029 // Check the remaining elements within this array subobject.
2030 bool prevHadError = hadError;
2031 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
2032 /*SubobjectIsDesignatorContext=*/false, Index,
2033 StructuredList, ElementIndex);
2034 return hadError && !prevHadError;
2037 // Get the structured initializer list for a subobject of type
2038 // @p CurrentObjectType.
2040 InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2041 QualType CurrentObjectType,
2042 InitListExpr *StructuredList,
2043 unsigned StructuredIndex,
2044 SourceRange InitRange) {
2046 return 0; // No structured list in verification-only mode.
2047 Expr *ExistingInit = 0;
2048 if (!StructuredList)
2049 ExistingInit = SyntacticToSemantic.lookup(IList);
2050 else if (StructuredIndex < StructuredList->getNumInits())
2051 ExistingInit = StructuredList->getInit(StructuredIndex);
2053 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2057 // We are creating an initializer list that initializes the
2058 // subobjects of the current object, but there was already an
2059 // initialization that completely initialized the current
2060 // subobject, e.g., by a compound literal:
2062 // struct X { int a, b; };
2063 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2065 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2066 // designated initializer re-initializes the whole
2067 // subobject [0], overwriting previous initializers.
2068 SemaRef.Diag(InitRange.getBegin(),
2069 diag::warn_subobject_initializer_overrides)
2071 SemaRef.Diag(ExistingInit->getLocStart(),
2072 diag::note_previous_initializer)
2073 << /*FIXME:has side effects=*/0
2074 << ExistingInit->getSourceRange();
2077 InitListExpr *Result
2078 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2079 InitRange.getBegin(), 0, 0,
2080 InitRange.getEnd());
2082 QualType ResultType = CurrentObjectType;
2083 if (!ResultType->isArrayType())
2084 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2085 Result->setType(ResultType);
2087 // Pre-allocate storage for the structured initializer list.
2088 unsigned NumElements = 0;
2089 unsigned NumInits = 0;
2090 bool GotNumInits = false;
2091 if (!StructuredList) {
2092 NumInits = IList->getNumInits();
2094 } else if (Index < IList->getNumInits()) {
2095 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
2096 NumInits = SubList->getNumInits();
2101 if (const ArrayType *AType
2102 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2103 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2104 NumElements = CAType->getSize().getZExtValue();
2105 // Simple heuristic so that we don't allocate a very large
2106 // initializer with many empty entries at the end.
2107 if (GotNumInits && NumElements > NumInits)
2110 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
2111 NumElements = VType->getNumElements();
2112 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
2113 RecordDecl *RDecl = RType->getDecl();
2114 if (RDecl->isUnion())
2117 NumElements = std::distance(RDecl->field_begin(),
2118 RDecl->field_end());
2121 Result->reserveInits(SemaRef.Context, NumElements);
2123 // Link this new initializer list into the structured initializer
2126 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
2128 Result->setSyntacticForm(IList);
2129 SyntacticToSemantic[IList] = Result;
2135 /// Update the initializer at index @p StructuredIndex within the
2136 /// structured initializer list to the value @p expr.
2137 void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2138 unsigned &StructuredIndex,
2140 // No structured initializer list to update
2141 if (!StructuredList)
2144 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2145 StructuredIndex, expr)) {
2146 // This initializer overwrites a previous initializer. Warn.
2147 SemaRef.Diag(expr->getLocStart(),
2148 diag::warn_initializer_overrides)
2149 << expr->getSourceRange();
2150 SemaRef.Diag(PrevInit->getLocStart(),
2151 diag::note_previous_initializer)
2152 << /*FIXME:has side effects=*/0
2153 << PrevInit->getSourceRange();
2159 /// Check that the given Index expression is a valid array designator
2160 /// value. This is essentially just a wrapper around
2161 /// VerifyIntegerConstantExpression that also checks for negative values
2162 /// and produces a reasonable diagnostic if there is a
2163 /// failure. Returns the index expression, possibly with an implicit cast
2164 /// added, on success. If everything went okay, Value will receive the
2165 /// value of the constant expression.
2167 CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
2168 SourceLocation Loc = Index->getLocStart();
2170 // Make sure this is an integer constant expression.
2171 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2172 if (Result.isInvalid())
2175 if (Value.isSigned() && Value.isNegative())
2176 return S.Diag(Loc, diag::err_array_designator_negative)
2177 << Value.toString(10) << Index->getSourceRange();
2179 Value.setIsUnsigned(true);
2183 ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
2187 typedef DesignatedInitExpr::Designator ASTDesignator;
2189 bool Invalid = false;
2190 SmallVector<ASTDesignator, 32> Designators;
2191 SmallVector<Expr *, 32> InitExpressions;
2193 // Build designators and check array designator expressions.
2194 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2195 const Designator &D = Desig.getDesignator(Idx);
2196 switch (D.getKind()) {
2197 case Designator::FieldDesignator:
2198 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
2202 case Designator::ArrayDesignator: {
2203 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2204 llvm::APSInt IndexValue;
2205 if (!Index->isTypeDependent() && !Index->isValueDependent())
2206 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2210 Designators.push_back(ASTDesignator(InitExpressions.size(),
2212 D.getRBracketLoc()));
2213 InitExpressions.push_back(Index);
2218 case Designator::ArrayRangeDesignator: {
2219 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2220 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2221 llvm::APSInt StartValue;
2222 llvm::APSInt EndValue;
2223 bool StartDependent = StartIndex->isTypeDependent() ||
2224 StartIndex->isValueDependent();
2225 bool EndDependent = EndIndex->isTypeDependent() ||
2226 EndIndex->isValueDependent();
2227 if (!StartDependent)
2229 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2231 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2233 if (!StartIndex || !EndIndex)
2236 // Make sure we're comparing values with the same bit width.
2237 if (StartDependent || EndDependent) {
2238 // Nothing to compute.
2239 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
2240 EndValue = EndValue.extend(StartValue.getBitWidth());
2241 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
2242 StartValue = StartValue.extend(EndValue.getBitWidth());
2244 if (!StartDependent && !EndDependent && EndValue < StartValue) {
2245 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
2246 << StartValue.toString(10) << EndValue.toString(10)
2247 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2250 Designators.push_back(ASTDesignator(InitExpressions.size(),
2253 D.getRBracketLoc()));
2254 InitExpressions.push_back(StartIndex);
2255 InitExpressions.push_back(EndIndex);
2263 if (Invalid || Init.isInvalid())
2266 // Clear out the expressions within the designation.
2267 Desig.ClearExprs(*this);
2269 DesignatedInitExpr *DIE
2270 = DesignatedInitExpr::Create(Context,
2271 Designators.data(), Designators.size(),
2272 InitExpressions.data(), InitExpressions.size(),
2273 Loc, GNUSyntax, Init.takeAs<Expr>());
2275 if (!getLangOpts().C99)
2276 Diag(DIE->getLocStart(), diag::ext_designated_init)
2277 << DIE->getSourceRange();
2282 //===----------------------------------------------------------------------===//
2283 // Initialization entity
2284 //===----------------------------------------------------------------------===//
2286 InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
2287 const InitializedEntity &Parent)
2288 : Parent(&Parent), Index(Index)
2290 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2291 Kind = EK_ArrayElement;
2292 Type = AT->getElementType();
2293 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
2294 Kind = EK_VectorElement;
2295 Type = VT->getElementType();
2297 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2298 assert(CT && "Unexpected type");
2299 Kind = EK_ComplexElement;
2300 Type = CT->getElementType();
2304 InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
2305 CXXBaseSpecifier *Base,
2306 bool IsInheritedVirtualBase)
2308 InitializedEntity Result;
2309 Result.Kind = EK_Base;
2310 Result.Base = reinterpret_cast<uintptr_t>(Base);
2311 if (IsInheritedVirtualBase)
2312 Result.Base |= 0x01;
2314 Result.Type = Base->getType();
2318 DeclarationName InitializedEntity::getName() const {
2319 switch (getKind()) {
2320 case EK_Parameter: {
2321 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2322 return (D ? D->getDeclName() : DeclarationName());
2327 return VariableOrMember->getDeclName();
2329 case EK_LambdaCapture:
2330 return Capture.Var->getDeclName();
2338 case EK_ArrayElement:
2339 case EK_VectorElement:
2340 case EK_ComplexElement:
2341 case EK_BlockElement:
2342 return DeclarationName();
2345 llvm_unreachable("Invalid EntityKind!");
2348 DeclaratorDecl *InitializedEntity::getDecl() const {
2349 switch (getKind()) {
2352 return VariableOrMember;
2355 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2363 case EK_ArrayElement:
2364 case EK_VectorElement:
2365 case EK_ComplexElement:
2366 case EK_BlockElement:
2367 case EK_LambdaCapture:
2371 llvm_unreachable("Invalid EntityKind!");
2374 bool InitializedEntity::allowsNRVO() const {
2375 switch (getKind()) {
2378 return LocAndNRVO.NRVO;
2387 case EK_ArrayElement:
2388 case EK_VectorElement:
2389 case EK_ComplexElement:
2390 case EK_BlockElement:
2391 case EK_LambdaCapture:
2398 //===----------------------------------------------------------------------===//
2399 // Initialization sequence
2400 //===----------------------------------------------------------------------===//
2402 void InitializationSequence::Step::Destroy() {
2404 case SK_ResolveAddressOfOverloadedFunction:
2405 case SK_CastDerivedToBaseRValue:
2406 case SK_CastDerivedToBaseXValue:
2407 case SK_CastDerivedToBaseLValue:
2408 case SK_BindReference:
2409 case SK_BindReferenceToTemporary:
2410 case SK_ExtraneousCopyToTemporary:
2411 case SK_UserConversion:
2412 case SK_QualificationConversionRValue:
2413 case SK_QualificationConversionXValue:
2414 case SK_QualificationConversionLValue:
2415 case SK_ListInitialization:
2416 case SK_ListConstructorCall:
2417 case SK_UnwrapInitList:
2418 case SK_RewrapInitList:
2419 case SK_ConstructorInitialization:
2420 case SK_ZeroInitialization:
2421 case SK_CAssignment:
2423 case SK_ObjCObjectConversion:
2425 case SK_ParenthesizedArrayInit:
2426 case SK_PassByIndirectCopyRestore:
2427 case SK_PassByIndirectRestore:
2428 case SK_ProduceObjCObject:
2429 case SK_StdInitializerList:
2432 case SK_ConversionSequence:
2437 bool InitializationSequence::isDirectReferenceBinding() const {
2438 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
2441 bool InitializationSequence::isAmbiguous() const {
2445 switch (getFailureKind()) {
2446 case FK_TooManyInitsForReference:
2447 case FK_ArrayNeedsInitList:
2448 case FK_ArrayNeedsInitListOrStringLiteral:
2449 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2450 case FK_NonConstLValueReferenceBindingToTemporary:
2451 case FK_NonConstLValueReferenceBindingToUnrelated:
2452 case FK_RValueReferenceBindingToLValue:
2453 case FK_ReferenceInitDropsQualifiers:
2454 case FK_ReferenceInitFailed:
2455 case FK_ConversionFailed:
2456 case FK_ConversionFromPropertyFailed:
2457 case FK_TooManyInitsForScalar:
2458 case FK_ReferenceBindingToInitList:
2459 case FK_InitListBadDestinationType:
2460 case FK_DefaultInitOfConst:
2462 case FK_ArrayTypeMismatch:
2463 case FK_NonConstantArrayInit:
2464 case FK_ListInitializationFailed:
2465 case FK_VariableLengthArrayHasInitializer:
2466 case FK_PlaceholderType:
2467 case FK_InitListElementCopyFailure:
2468 case FK_ExplicitConstructor:
2471 case FK_ReferenceInitOverloadFailed:
2472 case FK_UserConversionOverloadFailed:
2473 case FK_ConstructorOverloadFailed:
2474 case FK_ListConstructorOverloadFailed:
2475 return FailedOverloadResult == OR_Ambiguous;
2478 llvm_unreachable("Invalid EntityKind!");
2481 bool InitializationSequence::isConstructorInitialization() const {
2482 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2486 InitializationSequence
2487 ::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2488 DeclAccessPair Found,
2489 bool HadMultipleCandidates) {
2491 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2492 S.Type = Function->getType();
2493 S.Function.HadMultipleCandidates = HadMultipleCandidates;
2494 S.Function.Function = Function;
2495 S.Function.FoundDecl = Found;
2499 void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2503 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2504 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2505 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
2511 void InitializationSequence::AddReferenceBindingStep(QualType T,
2512 bool BindingTemporary) {
2514 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2519 void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2521 S.Kind = SK_ExtraneousCopyToTemporary;
2527 InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2528 DeclAccessPair FoundDecl,
2530 bool HadMultipleCandidates) {
2532 S.Kind = SK_UserConversion;
2534 S.Function.HadMultipleCandidates = HadMultipleCandidates;
2535 S.Function.Function = Function;
2536 S.Function.FoundDecl = FoundDecl;
2540 void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2543 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
2546 S.Kind = SK_QualificationConversionRValue;
2549 S.Kind = SK_QualificationConversionXValue;
2552 S.Kind = SK_QualificationConversionLValue;
2559 void InitializationSequence::AddConversionSequenceStep(
2560 const ImplicitConversionSequence &ICS,
2563 S.Kind = SK_ConversionSequence;
2565 S.ICS = new ImplicitConversionSequence(ICS);
2569 void InitializationSequence::AddListInitializationStep(QualType T) {
2571 S.Kind = SK_ListInitialization;
2577 InitializationSequence
2578 ::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2579 AccessSpecifier Access,
2581 bool HadMultipleCandidates,
2582 bool FromInitList, bool AsInitList) {
2584 S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2585 : SK_ConstructorInitialization;
2587 S.Function.HadMultipleCandidates = HadMultipleCandidates;
2588 S.Function.Function = Constructor;
2589 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
2593 void InitializationSequence::AddZeroInitializationStep(QualType T) {
2595 S.Kind = SK_ZeroInitialization;
2600 void InitializationSequence::AddCAssignmentStep(QualType T) {
2602 S.Kind = SK_CAssignment;
2607 void InitializationSequence::AddStringInitStep(QualType T) {
2609 S.Kind = SK_StringInit;
2614 void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2616 S.Kind = SK_ObjCObjectConversion;
2621 void InitializationSequence::AddArrayInitStep(QualType T) {
2623 S.Kind = SK_ArrayInit;
2628 void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2630 S.Kind = SK_ParenthesizedArrayInit;
2635 void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2638 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2639 : SK_PassByIndirectRestore);
2644 void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2646 S.Kind = SK_ProduceObjCObject;
2651 void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2653 S.Kind = SK_StdInitializerList;
2658 void InitializationSequence::RewrapReferenceInitList(QualType T,
2659 InitListExpr *Syntactic) {
2660 assert(Syntactic->getNumInits() == 1 &&
2661 "Can only rewrap trivial init lists.");
2663 S.Kind = SK_UnwrapInitList;
2664 S.Type = Syntactic->getInit(0)->getType();
2665 Steps.insert(Steps.begin(), S);
2667 S.Kind = SK_RewrapInitList;
2669 S.WrappingSyntacticList = Syntactic;
2673 void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2674 OverloadingResult Result) {
2675 setSequenceKind(FailedSequence);
2676 this->Failure = Failure;
2677 this->FailedOverloadResult = Result;
2680 //===----------------------------------------------------------------------===//
2681 // Attempt initialization
2682 //===----------------------------------------------------------------------===//
2684 static void MaybeProduceObjCObject(Sema &S,
2685 InitializationSequence &Sequence,
2686 const InitializedEntity &Entity) {
2687 if (!S.getLangOpts().ObjCAutoRefCount) return;
2689 /// When initializing a parameter, produce the value if it's marked
2690 /// __attribute__((ns_consumed)).
2691 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2692 if (!Entity.isParameterConsumed())
2695 assert(Entity.getType()->isObjCRetainableType() &&
2696 "consuming an object of unretainable type?");
2697 Sequence.AddProduceObjCObjectStep(Entity.getType());
2699 /// When initializing a return value, if the return type is a
2700 /// retainable type, then returns need to immediately retain the
2701 /// object. If an autorelease is required, it will be done at the
2703 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2704 if (!Entity.getType()->isObjCRetainableType())
2707 Sequence.AddProduceObjCObjectStep(Entity.getType());
2711 /// \brief When initializing from init list via constructor, deal with the
2712 /// empty init list and std::initializer_list special cases.
2714 /// \return True if this was a special case, false otherwise.
2715 static bool TryListConstructionSpecialCases(Sema &S,
2717 CXXRecordDecl *DestRecordDecl,
2719 InitializationSequence &Sequence) {
2720 // C++11 [dcl.init.list]p3:
2721 // List-initialization of an object or reference of type T is defined as
2723 // - If T is an aggregate, aggregate initialization is performed.
2724 if (DestType->isAggregateType())
2727 // - Otherwise, if the initializer list has no elements and T is a class
2728 // type with a default constructor, the object is value-initialized.
2729 if (List->getNumInits() == 0) {
2730 if (CXXConstructorDecl *DefaultConstructor =
2731 S.LookupDefaultConstructor(DestRecordDecl)) {
2732 if (DefaultConstructor->isDeleted() ||
2733 S.isFunctionConsideredUnavailable(DefaultConstructor)) {
2734 // Fake an overload resolution failure.
2735 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2736 DeclAccessPair FoundDecl = DeclAccessPair::make(DefaultConstructor,
2737 DefaultConstructor->getAccess());
2738 if (FunctionTemplateDecl *ConstructorTmpl =
2739 dyn_cast<FunctionTemplateDecl>(DefaultConstructor))
2740 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2742 ArrayRef<Expr*>(), CandidateSet,
2743 /*SuppressUserConversions*/ false);
2745 S.AddOverloadCandidate(DefaultConstructor, FoundDecl,
2746 ArrayRef<Expr*>(), CandidateSet,
2747 /*SuppressUserConversions*/ false);
2748 Sequence.SetOverloadFailure(
2749 InitializationSequence::FK_ListConstructorOverloadFailed,
2752 Sequence.AddConstructorInitializationStep(DefaultConstructor,
2753 DefaultConstructor->getAccess(),
2755 /*MultipleCandidates=*/false,
2756 /*FromInitList=*/true,
2757 /*AsInitList=*/false);
2762 // - Otherwise, if T is a specialization of std::initializer_list, [...]
2764 if (S.isStdInitializerList(DestType, &E)) {
2765 // Check that each individual element can be copy-constructed. But since we
2766 // have no place to store further information, we'll recalculate everything
2768 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2769 S.Context.getConstantArrayType(E,
2770 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2771 List->getNumInits()),
2772 ArrayType::Normal, 0));
2773 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2775 for (unsigned i = 0, n = List->getNumInits(); i < n; ++i) {
2776 Element.setElementIndex(i);
2777 if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) {
2779 InitializationSequence::FK_InitListElementCopyFailure);
2783 Sequence.AddStdInitializerListConstructionStep(DestType);
2787 // Not a special case.
2791 static OverloadingResult
2792 ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
2793 Expr **Args, unsigned NumArgs,
2794 OverloadCandidateSet &CandidateSet,
2795 DeclContext::lookup_iterator Con,
2796 DeclContext::lookup_iterator ConEnd,
2797 OverloadCandidateSet::iterator &Best,
2798 bool CopyInitializing, bool AllowExplicit,
2799 bool OnlyListConstructors, bool InitListSyntax) {
2800 CandidateSet.clear();
2802 for (; Con != ConEnd; ++Con) {
2803 NamedDecl *D = *Con;
2804 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2805 bool SuppressUserConversions = false;
2807 // Find the constructor (which may be a template).
2808 CXXConstructorDecl *Constructor = 0;
2809 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2810 if (ConstructorTmpl)
2811 Constructor = cast<CXXConstructorDecl>(
2812 ConstructorTmpl->getTemplatedDecl());
2814 Constructor = cast<CXXConstructorDecl>(D);
2816 // If we're performing copy initialization using a copy constructor, we
2817 // suppress user-defined conversions on the arguments. We do the same for
2818 // move constructors.
2819 if ((CopyInitializing || (InitListSyntax && NumArgs == 1)) &&
2820 Constructor->isCopyOrMoveConstructor())
2821 SuppressUserConversions = true;
2824 if (!Constructor->isInvalidDecl() &&
2825 (AllowExplicit || !Constructor->isExplicit()) &&
2826 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
2827 if (ConstructorTmpl)
2828 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2830 llvm::makeArrayRef(Args, NumArgs),
2831 CandidateSet, SuppressUserConversions);
2833 // C++ [over.match.copy]p1:
2834 // - When initializing a temporary to be bound to the first parameter
2835 // of a constructor that takes a reference to possibly cv-qualified
2836 // T as its first argument, called with a single argument in the
2837 // context of direct-initialization, explicit conversion functions
2838 // are also considered.
2839 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
2841 Constructor->isCopyOrMoveConstructor();
2842 S.AddOverloadCandidate(Constructor, FoundDecl,
2843 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
2844 SuppressUserConversions,
2845 /*PartialOverloading=*/false,
2846 /*AllowExplicit=*/AllowExplicitConv);
2851 // Perform overload resolution and return the result.
2852 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
2855 /// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2856 /// enumerates the constructors of the initialized entity and performs overload
2857 /// resolution to select the best.
2858 /// If InitListSyntax is true, this is list-initialization of a non-aggregate
2860 static void TryConstructorInitialization(Sema &S,
2861 const InitializedEntity &Entity,
2862 const InitializationKind &Kind,
2863 Expr **Args, unsigned NumArgs,
2865 InitializationSequence &Sequence,
2866 bool InitListSyntax = false) {
2867 assert((!InitListSyntax || (NumArgs == 1 && isa<InitListExpr>(Args[0]))) &&
2868 "InitListSyntax must come with a single initializer list argument.");
2870 // Check constructor arguments for self reference.
2871 if (DeclaratorDecl *DD = Entity.getDecl())
2872 // Parameters arguments are occassionially constructed with itself,
2873 // for instance, in recursive functions. Skip them.
2874 if (!isa<ParmVarDecl>(DD))
2875 for (unsigned i = 0; i < NumArgs; ++i)
2876 S.CheckSelfReference(DD, Args[i]);
2878 // The type we're constructing needs to be complete.
2879 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
2880 Sequence.setIncompleteTypeFailure(DestType);
2884 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2885 assert(DestRecordType && "Constructor initialization requires record type");
2886 CXXRecordDecl *DestRecordDecl
2887 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2889 if (InitListSyntax &&
2890 TryListConstructionSpecialCases(S, cast<InitListExpr>(Args[0]),
2891 DestRecordDecl, DestType, Sequence))
2894 // Build the candidate set directly in the initialization sequence
2895 // structure, so that it will persist if we fail.
2896 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2898 // Determine whether we are allowed to call explicit constructors or
2899 // explicit conversion operators.
2900 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
2901 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
2903 // - Otherwise, if T is a class type, constructors are considered. The
2904 // applicable constructors are enumerated, and the best one is chosen
2905 // through overload resolution.
2906 DeclContext::lookup_iterator ConStart, ConEnd;
2907 llvm::tie(ConStart, ConEnd) = S.LookupConstructors(DestRecordDecl);
2909 OverloadingResult Result = OR_No_Viable_Function;
2910 OverloadCandidateSet::iterator Best;
2911 bool AsInitializerList = false;
2913 // C++11 [over.match.list]p1:
2914 // When objects of non-aggregate type T are list-initialized, overload
2915 // resolution selects the constructor in two phases:
2916 // - Initially, the candidate functions are the initializer-list
2917 // constructors of the class T and the argument list consists of the
2918 // initializer list as a single argument.
2919 if (InitListSyntax) {
2920 AsInitializerList = true;
2921 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
2922 CandidateSet, ConStart, ConEnd, Best,
2923 CopyInitialization, AllowExplicit,
2924 /*OnlyListConstructor=*/true,
2927 // Time to unwrap the init list.
2928 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
2929 Args = ILE->getInits();
2930 NumArgs = ILE->getNumInits();
2933 // C++11 [over.match.list]p1:
2934 // - If no viable initializer-list constructor is found, overload resolution
2935 // is performed again, where the candidate functions are all the
2936 // constructors of the class T nad the argument list consists of the
2937 // elements of the initializer list.
2938 if (Result == OR_No_Viable_Function) {
2939 AsInitializerList = false;
2940 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
2941 CandidateSet, ConStart, ConEnd, Best,
2942 CopyInitialization, AllowExplicit,
2943 /*OnlyListConstructors=*/false,
2947 Sequence.SetOverloadFailure(InitListSyntax ?
2948 InitializationSequence::FK_ListConstructorOverloadFailed :
2949 InitializationSequence::FK_ConstructorOverloadFailed,
2954 // C++0x [dcl.init]p6:
2955 // If a program calls for the default initialization of an object
2956 // of a const-qualified type T, T shall be a class type with a
2957 // user-provided default constructor.
2958 if (Kind.getKind() == InitializationKind::IK_Default &&
2959 Entity.getType().isConstQualified() &&
2960 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2961 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2965 // C++11 [over.match.list]p1:
2966 // In copy-list-initialization, if an explicit constructor is chosen, the
2967 // initializer is ill-formed.
2968 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
2969 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
2970 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
2974 // Add the constructor initialization step. Any cv-qualification conversion is
2975 // subsumed by the initialization.
2976 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2977 Sequence.AddConstructorInitializationStep(CtorDecl,
2978 Best->FoundDecl.getAccess(),
2979 DestType, HadMultipleCandidates,
2980 InitListSyntax, AsInitializerList);
2984 ResolveOverloadedFunctionForReferenceBinding(Sema &S,
2986 QualType &SourceType,
2987 QualType &UnqualifiedSourceType,
2988 QualType UnqualifiedTargetType,
2989 InitializationSequence &Sequence) {
2990 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
2991 S.Context.OverloadTy) {
2992 DeclAccessPair Found;
2993 bool HadMultipleCandidates = false;
2994 if (FunctionDecl *Fn
2995 = S.ResolveAddressOfOverloadedFunction(Initializer,
2996 UnqualifiedTargetType,
2998 &HadMultipleCandidates)) {
2999 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3000 HadMultipleCandidates);
3001 SourceType = Fn->getType();
3002 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3003 } else if (!UnqualifiedTargetType->isRecordType()) {
3004 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3011 static void TryReferenceInitializationCore(Sema &S,
3012 const InitializedEntity &Entity,
3013 const InitializationKind &Kind,
3015 QualType cv1T1, QualType T1,
3017 QualType cv2T2, QualType T2,
3019 InitializationSequence &Sequence);
3021 static void TryListInitialization(Sema &S,
3022 const InitializedEntity &Entity,
3023 const InitializationKind &Kind,
3024 InitListExpr *InitList,
3025 InitializationSequence &Sequence);
3027 /// \brief Attempt list initialization of a reference.
3028 static void TryReferenceListInitialization(Sema &S,
3029 const InitializedEntity &Entity,
3030 const InitializationKind &Kind,
3031 InitListExpr *InitList,
3032 InitializationSequence &Sequence)
3034 // First, catch C++03 where this isn't possible.
3035 if (!S.getLangOpts().CPlusPlus0x) {
3036 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3040 QualType DestType = Entity.getType();
3041 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3043 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3045 // Reference initialization via an initializer list works thus:
3046 // If the initializer list consists of a single element that is
3047 // reference-related to the referenced type, bind directly to that element
3048 // (possibly creating temporaries).
3049 // Otherwise, initialize a temporary with the initializer list and
3051 if (InitList->getNumInits() == 1) {
3052 Expr *Initializer = InitList->getInit(0);
3053 QualType cv2T2 = Initializer->getType();
3055 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3057 // If this fails, creating a temporary wouldn't work either.
3058 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3062 SourceLocation DeclLoc = Initializer->getLocStart();
3063 bool dummy1, dummy2, dummy3;
3064 Sema::ReferenceCompareResult RefRelationship
3065 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3067 if (RefRelationship >= Sema::Ref_Related) {
3068 // Try to bind the reference here.
3069 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3070 T1Quals, cv2T2, T2, T2Quals, Sequence);
3072 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3077 // Not reference-related. Create a temporary and bind to that.
3078 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3080 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3082 if (DestType->isRValueReferenceType() ||
3083 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3084 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3087 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3091 /// \brief Attempt list initialization (C++0x [dcl.init.list])
3092 static void TryListInitialization(Sema &S,
3093 const InitializedEntity &Entity,
3094 const InitializationKind &Kind,
3095 InitListExpr *InitList,
3096 InitializationSequence &Sequence) {
3097 QualType DestType = Entity.getType();
3099 // C++ doesn't allow scalar initialization with more than one argument.
3100 // But C99 complex numbers are scalars and it makes sense there.
3101 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
3102 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3103 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3106 if (DestType->isReferenceType()) {
3107 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
3110 if (DestType->isRecordType()) {
3111 if (S.RequireCompleteType(InitList->getLocStart(), DestType, S.PDiag())) {
3112 Sequence.setIncompleteTypeFailure(DestType);
3116 if (!DestType->isAggregateType()) {
3117 if (S.getLangOpts().CPlusPlus0x) {
3118 Expr *Arg = InitList;
3119 // A direct-initializer is not list-syntax, i.e. there's no special
3120 // treatment of "A a({1, 2});".
3121 TryConstructorInitialization(S, Entity, Kind, &Arg, 1, DestType,
3123 Kind.getKind() != InitializationKind::IK_Direct);
3126 InitializationSequence::FK_InitListBadDestinationType);
3131 InitListChecker CheckInitList(S, Entity, InitList,
3132 DestType, /*VerifyOnly=*/true,
3133 Kind.getKind() != InitializationKind::IK_DirectList ||
3134 !S.getLangOpts().CPlusPlus0x);
3135 if (CheckInitList.HadError()) {
3136 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3140 // Add the list initialization step with the built init list.
3141 Sequence.AddListInitializationStep(DestType);
3144 /// \brief Try a reference initialization that involves calling a conversion
3146 static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3147 const InitializedEntity &Entity,
3148 const InitializationKind &Kind,
3151 InitializationSequence &Sequence) {
3152 QualType DestType = Entity.getType();
3153 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3154 QualType T1 = cv1T1.getUnqualifiedType();
3155 QualType cv2T2 = Initializer->getType();
3156 QualType T2 = cv2T2.getUnqualifiedType();
3159 bool ObjCConversion;
3160 bool ObjCLifetimeConversion;
3161 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
3162 T1, T2, DerivedToBase,
3164 ObjCLifetimeConversion) &&
3165 "Must have incompatible references when binding via conversion");
3166 (void)DerivedToBase;
3167 (void)ObjCConversion;
3168 (void)ObjCLifetimeConversion;
3170 // Build the candidate set directly in the initialization sequence
3171 // structure, so that it will persist if we fail.
3172 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3173 CandidateSet.clear();
3175 // Determine whether we are allowed to call explicit constructors or
3176 // explicit conversion operators.
3177 bool AllowExplicit = Kind.AllowExplicit();
3178 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctions();
3180 const RecordType *T1RecordType = 0;
3181 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3182 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
3183 // The type we're converting to is a class type. Enumerate its constructors
3184 // to see if there is a suitable conversion.
3185 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
3187 DeclContext::lookup_iterator Con, ConEnd;
3188 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
3189 Con != ConEnd; ++Con) {
3190 NamedDecl *D = *Con;
3191 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3193 // Find the constructor (which may be a template).
3194 CXXConstructorDecl *Constructor = 0;
3195 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3196 if (ConstructorTmpl)
3197 Constructor = cast<CXXConstructorDecl>(
3198 ConstructorTmpl->getTemplatedDecl());
3200 Constructor = cast<CXXConstructorDecl>(D);
3202 if (!Constructor->isInvalidDecl() &&
3203 Constructor->isConvertingConstructor(AllowExplicit)) {
3204 if (ConstructorTmpl)
3205 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3207 Initializer, CandidateSet,
3208 /*SuppressUserConversions=*/true);
3210 S.AddOverloadCandidate(Constructor, FoundDecl,
3211 Initializer, CandidateSet,
3212 /*SuppressUserConversions=*/true);
3216 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3217 return OR_No_Viable_Function;
3219 const RecordType *T2RecordType = 0;
3220 if ((T2RecordType = T2->getAs<RecordType>()) &&
3221 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
3222 // The type we're converting from is a class type, enumerate its conversion
3224 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3226 const UnresolvedSetImpl *Conversions
3227 = T2RecordDecl->getVisibleConversionFunctions();
3228 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
3229 E = Conversions->end(); I != E; ++I) {
3231 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3232 if (isa<UsingShadowDecl>(D))
3233 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3235 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3236 CXXConversionDecl *Conv;
3238 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3240 Conv = cast<CXXConversionDecl>(D);
3242 // If the conversion function doesn't return a reference type,
3243 // it can't be considered for this conversion unless we're allowed to
3244 // consider rvalues.
3245 // FIXME: Do we need to make sure that we only consider conversion
3246 // candidates with reference-compatible results? That might be needed to
3248 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
3249 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3251 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3252 ActingDC, Initializer,
3253 DestType, CandidateSet);
3255 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
3256 Initializer, DestType, CandidateSet);
3260 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3261 return OR_No_Viable_Function;
3263 SourceLocation DeclLoc = Initializer->getLocStart();
3265 // Perform overload resolution. If it fails, return the failed result.
3266 OverloadCandidateSet::iterator Best;
3267 if (OverloadingResult Result
3268 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
3271 FunctionDecl *Function = Best->Function;
3273 // This is the overload that will actually be used for the initialization, so
3275 S.MarkFunctionReferenced(DeclLoc, Function);
3277 // Compute the returned type of the conversion.
3278 if (isa<CXXConversionDecl>(Function))
3279 T2 = Function->getResultType();
3283 // Add the user-defined conversion step.
3284 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3285 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3286 T2.getNonLValueExprType(S.Context),
3287 HadMultipleCandidates);
3289 // Determine whether we need to perform derived-to-base or
3290 // cv-qualification adjustments.
3291 ExprValueKind VK = VK_RValue;
3292 if (T2->isLValueReferenceType())
3294 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
3295 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
3297 bool NewDerivedToBase = false;
3298 bool NewObjCConversion = false;
3299 bool NewObjCLifetimeConversion = false;
3300 Sema::ReferenceCompareResult NewRefRelationship
3301 = S.CompareReferenceRelationship(DeclLoc, T1,
3302 T2.getNonLValueExprType(S.Context),
3303 NewDerivedToBase, NewObjCConversion,
3304 NewObjCLifetimeConversion);
3305 if (NewRefRelationship == Sema::Ref_Incompatible) {
3306 // If the type we've converted to is not reference-related to the
3307 // type we're looking for, then there is another conversion step
3308 // we need to perform to produce a temporary of the right type
3309 // that we'll be binding to.
3310 ImplicitConversionSequence ICS;
3312 ICS.Standard = Best->FinalConversion;
3313 T2 = ICS.Standard.getToType(2);
3314 Sequence.AddConversionSequenceStep(ICS, T2);
3315 } else if (NewDerivedToBase)
3316 Sequence.AddDerivedToBaseCastStep(
3317 S.Context.getQualifiedType(T1,
3318 T2.getNonReferenceType().getQualifiers()),
3320 else if (NewObjCConversion)
3321 Sequence.AddObjCObjectConversionStep(
3322 S.Context.getQualifiedType(T1,
3323 T2.getNonReferenceType().getQualifiers()));
3325 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
3326 Sequence.AddQualificationConversionStep(cv1T1, VK);
3328 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3332 static void CheckCXX98CompatAccessibleCopy(Sema &S,
3333 const InitializedEntity &Entity,
3336 /// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3337 static void TryReferenceInitialization(Sema &S,
3338 const InitializedEntity &Entity,
3339 const InitializationKind &Kind,
3341 InitializationSequence &Sequence) {
3342 QualType DestType = Entity.getType();
3343 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3345 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3346 QualType cv2T2 = Initializer->getType();
3348 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3350 // If the initializer is the address of an overloaded function, try
3351 // to resolve the overloaded function. If all goes well, T2 is the
3352 // type of the resulting function.
3353 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3357 // Delegate everything else to a subfunction.
3358 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3359 T1Quals, cv2T2, T2, T2Quals, Sequence);
3362 /// \brief Reference initialization without resolving overloaded functions.
3363 static void TryReferenceInitializationCore(Sema &S,
3364 const InitializedEntity &Entity,
3365 const InitializationKind &Kind,
3367 QualType cv1T1, QualType T1,
3369 QualType cv2T2, QualType T2,
3371 InitializationSequence &Sequence) {
3372 QualType DestType = Entity.getType();
3373 SourceLocation DeclLoc = Initializer->getLocStart();
3374 // Compute some basic properties of the types and the initializer.
3375 bool isLValueRef = DestType->isLValueReferenceType();
3376 bool isRValueRef = !isLValueRef;
3377 bool DerivedToBase = false;
3378 bool ObjCConversion = false;
3379 bool ObjCLifetimeConversion = false;
3380 Expr::Classification InitCategory = Initializer->Classify(S.Context);
3381 Sema::ReferenceCompareResult RefRelationship
3382 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
3383 ObjCConversion, ObjCLifetimeConversion);
3385 // C++0x [dcl.init.ref]p5:
3386 // A reference to type "cv1 T1" is initialized by an expression of type
3387 // "cv2 T2" as follows:
3389 // - If the reference is an lvalue reference and the initializer
3391 // Note the analogous bullet points for rvlaue refs to functions. Because
3392 // there are no function rvalues in C++, rvalue refs to functions are treated
3393 // like lvalue refs.
3394 OverloadingResult ConvOvlResult = OR_Success;
3395 bool T1Function = T1->isFunctionType();
3396 if (isLValueRef || T1Function) {
3397 if (InitCategory.isLValue() &&
3398 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
3399 (Kind.isCStyleOrFunctionalCast() &&
3400 RefRelationship == Sema::Ref_Related))) {
3401 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
3402 // reference-compatible with "cv2 T2," or
3404 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
3405 // bit-field when we're determining whether the reference initialization
3406 // can occur. However, we do pay attention to whether it is a bit-field
3407 // to decide whether we're actually binding to a temporary created from
3410 Sequence.AddDerivedToBaseCastStep(
3411 S.Context.getQualifiedType(T1, T2Quals),
3413 else if (ObjCConversion)
3414 Sequence.AddObjCObjectConversionStep(
3415 S.Context.getQualifiedType(T1, T2Quals));
3417 if (T1Quals != T2Quals)
3418 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
3419 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
3420 (Initializer->getBitField() || Initializer->refersToVectorElement());
3421 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
3425 // - has a class type (i.e., T2 is a class type), where T1 is not
3426 // reference-related to T2, and can be implicitly converted to an
3427 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3428 // with "cv3 T3" (this conversion is selected by enumerating the
3429 // applicable conversion functions (13.3.1.6) and choosing the best
3430 // one through overload resolution (13.3)),
3431 // If we have an rvalue ref to function type here, the rhs must be
3433 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3434 (isLValueRef || InitCategory.isRValue())) {
3435 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
3437 /*AllowRValues=*/isRValueRef,
3439 if (ConvOvlResult == OR_Success)
3441 if (ConvOvlResult != OR_No_Viable_Function) {
3442 Sequence.SetOverloadFailure(
3443 InitializationSequence::FK_ReferenceInitOverloadFailed,
3449 // - Otherwise, the reference shall be an lvalue reference to a
3450 // non-volatile const type (i.e., cv1 shall be const), or the reference
3451 // shall be an rvalue reference.
3452 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
3453 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3454 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3455 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3456 Sequence.SetOverloadFailure(
3457 InitializationSequence::FK_ReferenceInitOverloadFailed,
3460 Sequence.SetFailed(InitCategory.isLValue()
3461 ? (RefRelationship == Sema::Ref_Related
3462 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3463 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3464 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3469 // - If the initializer expression
3470 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3471 // "cv1 T1" is reference-compatible with "cv2 T2"
3472 // Note: functions are handled below.
3474 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
3475 (Kind.isCStyleOrFunctionalCast() &&
3476 RefRelationship == Sema::Ref_Related)) &&
3477 (InitCategory.isXValue() ||
3478 (InitCategory.isPRValue() && T2->isRecordType()) ||
3479 (InitCategory.isPRValue() && T2->isArrayType()))) {
3480 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3481 if (InitCategory.isPRValue() && T2->isRecordType()) {
3482 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3483 // compiler the freedom to perform a copy here or bind to the
3484 // object, while C++0x requires that we bind directly to the
3485 // object. Hence, we always bind to the object without making an
3486 // extra copy. However, in C++03 requires that we check for the
3487 // presence of a suitable copy constructor:
3489 // The constructor that would be used to make the copy shall
3490 // be callable whether or not the copy is actually done.
3491 if (!S.getLangOpts().CPlusPlus0x && !S.getLangOpts().MicrosoftExt)
3492 Sequence.AddExtraneousCopyToTemporary(cv2T2);
3493 else if (S.getLangOpts().CPlusPlus0x)
3494 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
3498 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3500 else if (ObjCConversion)
3501 Sequence.AddObjCObjectConversionStep(
3502 S.Context.getQualifiedType(T1, T2Quals));
3504 if (T1Quals != T2Quals)
3505 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
3506 Sequence.AddReferenceBindingStep(cv1T1,
3507 /*bindingTemporary=*/InitCategory.isPRValue());
3511 // - has a class type (i.e., T2 is a class type), where T1 is not
3512 // reference-related to T2, and can be implicitly converted to an
3513 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3514 // where "cv1 T1" is reference-compatible with "cv3 T3",
3515 if (T2->isRecordType()) {
3516 if (RefRelationship == Sema::Ref_Incompatible) {
3517 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3519 /*AllowRValues=*/true,
3522 Sequence.SetOverloadFailure(
3523 InitializationSequence::FK_ReferenceInitOverloadFailed,
3529 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3533 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
3534 // from the initializer expression using the rules for a non-reference
3535 // copy initialization (8.5). The reference is then bound to the
3538 // Determine whether we are allowed to call explicit constructors or
3539 // explicit conversion operators.
3540 bool AllowExplicit = Kind.AllowExplicit();
3542 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3544 ImplicitConversionSequence ICS
3545 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
3546 /*SuppressUserConversions*/ false,
3548 /*FIXME:InOverloadResolution=*/false,
3549 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3550 /*AllowObjCWritebackConversion=*/false);
3553 // FIXME: Use the conversion function set stored in ICS to turn
3554 // this into an overloading ambiguity diagnostic. However, we need
3555 // to keep that set as an OverloadCandidateSet rather than as some
3556 // other kind of set.
3557 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3558 Sequence.SetOverloadFailure(
3559 InitializationSequence::FK_ReferenceInitOverloadFailed,
3561 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3562 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3564 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
3567 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
3570 // [...] If T1 is reference-related to T2, cv1 must be the
3571 // same cv-qualification as, or greater cv-qualification
3572 // than, cv2; otherwise, the program is ill-formed.
3573 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3574 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
3575 if (RefRelationship == Sema::Ref_Related &&
3576 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
3577 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3581 // [...] If T1 is reference-related to T2 and the reference is an rvalue
3582 // reference, the initializer expression shall not be an lvalue.
3583 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
3584 InitCategory.isLValue()) {
3586 InitializationSequence::FK_RValueReferenceBindingToLValue);
3590 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3594 /// \brief Attempt character array initialization from a string literal
3595 /// (C++ [dcl.init.string], C99 6.7.8).
3596 static void TryStringLiteralInitialization(Sema &S,
3597 const InitializedEntity &Entity,
3598 const InitializationKind &Kind,
3600 InitializationSequence &Sequence) {
3601 Sequence.AddStringInitStep(Entity.getType());
3604 /// \brief Attempt value initialization (C++ [dcl.init]p7).
3605 static void TryValueInitialization(Sema &S,
3606 const InitializedEntity &Entity,
3607 const InitializationKind &Kind,
3608 InitializationSequence &Sequence) {
3609 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
3611 // To value-initialize an object of type T means:
3612 QualType T = Entity.getType();
3614 // -- if T is an array type, then each element is value-initialized;
3615 T = S.Context.getBaseElementType(T);
3617 if (const RecordType *RT = T->getAs<RecordType>()) {
3618 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3620 // -- if T is a class type (clause 9) with a user-declared
3621 // constructor (12.1), then the default constructor for T is
3622 // called (and the initialization is ill-formed if T has no
3623 // accessible default constructor);
3624 if (!S.getLangOpts().CPlusPlus0x) {
3625 if (ClassDecl->hasUserDeclaredConstructor())
3626 // FIXME: we really want to refer to a single subobject of the array,
3627 // but Entity doesn't have a way to capture that (yet).
3628 return TryConstructorInitialization(S, Entity, Kind, 0, 0,
3632 // -- if T is a class type (clause 9) with either no default constructor
3633 // (12.1 [class.ctor]) or a default constructor that is user-provided
3634 // or deleted, then the object is default-initialized;
3635 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3636 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
3637 return TryConstructorInitialization(S, Entity, Kind, 0, 0,
3641 // -- if T is a (possibly cv-qualified) non-union class type without a
3642 // user-provided or deleted default constructor, then the object is
3643 // zero-initialized and, if T has a non-trivial default constructor,
3644 // default-initialized;
3645 if ((ClassDecl->getTagKind() == TTK_Class ||
3646 ClassDecl->getTagKind() == TTK_Struct)) {
3647 Sequence.AddZeroInitializationStep(Entity.getType());
3648 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
3653 Sequence.AddZeroInitializationStep(Entity.getType());
3656 /// \brief Attempt default initialization (C++ [dcl.init]p6).
3657 static void TryDefaultInitialization(Sema &S,
3658 const InitializedEntity &Entity,
3659 const InitializationKind &Kind,
3660 InitializationSequence &Sequence) {
3661 assert(Kind.getKind() == InitializationKind::IK_Default);
3663 // C++ [dcl.init]p6:
3664 // To default-initialize an object of type T means:
3665 // - if T is an array type, each element is default-initialized;
3666 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3668 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3669 // constructor for T is called (and the initialization is ill-formed if
3670 // T has no accessible default constructor);
3671 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
3672 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3676 // - otherwise, no initialization is performed.
3678 // If a program calls for the default initialization of an object of
3679 // a const-qualified type T, T shall be a class type with a user-provided
3680 // default constructor.
3681 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
3682 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3686 // If the destination type has a lifetime property, zero-initialize it.
3687 if (DestType.getQualifiers().hasObjCLifetime()) {
3688 Sequence.AddZeroInitializationStep(Entity.getType());
3693 /// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3694 /// which enumerates all conversion functions and performs overload resolution
3695 /// to select the best.
3696 static void TryUserDefinedConversion(Sema &S,
3697 const InitializedEntity &Entity,
3698 const InitializationKind &Kind,
3700 InitializationSequence &Sequence) {
3701 QualType DestType = Entity.getType();
3702 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3703 QualType SourceType = Initializer->getType();
3704 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3705 "Must have a class type to perform a user-defined conversion");
3707 // Build the candidate set directly in the initialization sequence
3708 // structure, so that it will persist if we fail.
3709 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3710 CandidateSet.clear();
3712 // Determine whether we are allowed to call explicit constructors or
3713 // explicit conversion operators.
3714 bool AllowExplicit = Kind.AllowExplicit();
3716 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3717 // The type we're converting to is a class type. Enumerate its constructors
3718 // to see if there is a suitable conversion.
3719 CXXRecordDecl *DestRecordDecl
3720 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3722 // Try to complete the type we're converting to.
3723 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
3724 DeclContext::lookup_iterator Con, ConEnd;
3725 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
3726 Con != ConEnd; ++Con) {
3727 NamedDecl *D = *Con;
3728 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3730 // Find the constructor (which may be a template).
3731 CXXConstructorDecl *Constructor = 0;
3732 FunctionTemplateDecl *ConstructorTmpl
3733 = dyn_cast<FunctionTemplateDecl>(D);
3734 if (ConstructorTmpl)
3735 Constructor = cast<CXXConstructorDecl>(
3736 ConstructorTmpl->getTemplatedDecl());
3738 Constructor = cast<CXXConstructorDecl>(D);
3740 if (!Constructor->isInvalidDecl() &&
3741 Constructor->isConvertingConstructor(AllowExplicit)) {
3742 if (ConstructorTmpl)
3743 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3745 Initializer, CandidateSet,
3746 /*SuppressUserConversions=*/true);
3748 S.AddOverloadCandidate(Constructor, FoundDecl,
3749 Initializer, CandidateSet,
3750 /*SuppressUserConversions=*/true);
3756 SourceLocation DeclLoc = Initializer->getLocStart();
3758 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3759 // The type we're converting from is a class type, enumerate its conversion
3762 // We can only enumerate the conversion functions for a complete type; if
3763 // the type isn't complete, simply skip this step.
3764 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3765 CXXRecordDecl *SourceRecordDecl
3766 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
3768 const UnresolvedSetImpl *Conversions
3769 = SourceRecordDecl->getVisibleConversionFunctions();
3770 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
3771 E = Conversions->end();
3774 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3775 if (isa<UsingShadowDecl>(D))
3776 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3778 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3779 CXXConversionDecl *Conv;
3781 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3783 Conv = cast<CXXConversionDecl>(D);
3785 if (AllowExplicit || !Conv->isExplicit()) {
3787 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3788 ActingDC, Initializer, DestType,
3791 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
3792 Initializer, DestType, CandidateSet);
3798 // Perform overload resolution. If it fails, return the failed result.
3799 OverloadCandidateSet::iterator Best;
3800 if (OverloadingResult Result
3801 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
3802 Sequence.SetOverloadFailure(
3803 InitializationSequence::FK_UserConversionOverloadFailed,
3808 FunctionDecl *Function = Best->Function;
3809 S.MarkFunctionReferenced(DeclLoc, Function);
3810 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3812 if (isa<CXXConstructorDecl>(Function)) {
3813 // Add the user-defined conversion step. Any cv-qualification conversion is
3814 // subsumed by the initialization. Per DR5, the created temporary is of the
3815 // cv-unqualified type of the destination.
3816 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3817 DestType.getUnqualifiedType(),
3818 HadMultipleCandidates);
3822 // Add the user-defined conversion step that calls the conversion function.
3823 QualType ConvType = Function->getCallResultType();
3824 if (ConvType->getAs<RecordType>()) {
3825 // If we're converting to a class type, there may be an copy of
3826 // the resulting temporary object (possible to create an object of
3827 // a base class type). That copy is not a separate conversion, so
3828 // we just make a note of the actual destination type (possibly a
3829 // base class of the type returned by the conversion function) and
3830 // let the user-defined conversion step handle the conversion.
3831 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3832 HadMultipleCandidates);
3836 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3837 HadMultipleCandidates);
3839 // If the conversion following the call to the conversion function
3840 // is interesting, add it as a separate step.
3841 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3842 Best->FinalConversion.Third) {
3843 ImplicitConversionSequence ICS;
3845 ICS.Standard = Best->FinalConversion;
3846 Sequence.AddConversionSequenceStep(ICS, DestType);
3850 /// The non-zero enum values here are indexes into diagnostic alternatives.
3851 enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3853 /// Determines whether this expression is an acceptable ICR source.
3854 static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3857 e = e->IgnoreParens();
3859 // Skip address-of nodes.
3860 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3861 if (op->getOpcode() == UO_AddrOf)
3862 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
3864 // Skip certain casts.
3865 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3866 switch (ce->getCastKind()) {
3869 case CK_LValueBitCast:
3871 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
3873 case CK_ArrayToPointerDecay:
3874 return IIK_nonscalar;
3876 case CK_NullToPointer:
3883 // If we have a declaration reference, it had better be a local variable.
3884 } else if (isa<DeclRefExpr>(e)) {
3885 if (!isAddressOf) return IIK_nonlocal;
3887 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3888 if (!var) return IIK_nonlocal;
3890 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
3892 // If we have a conditional operator, check both sides.
3893 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
3894 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
3897 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
3899 // These are never scalar.
3900 } else if (isa<ArraySubscriptExpr>(e)) {
3901 return IIK_nonscalar;
3903 // Otherwise, it needs to be a null pointer constant.
3905 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3906 ? IIK_okay : IIK_nonlocal);
3909 return IIK_nonlocal;
3912 /// Check whether the given expression is a valid operand for an
3913 /// indirect copy/restore.
3914 static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3915 assert(src->isRValue());
3917 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
3918 if (iik == IIK_okay) return;
3920 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3921 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3922 << src->getSourceRange();
3925 /// \brief Determine whether we have compatible array types for the
3926 /// purposes of GNU by-copy array initialization.
3927 static bool hasCompatibleArrayTypes(ASTContext &Context,
3928 const ArrayType *Dest,
3929 const ArrayType *Source) {
3930 // If the source and destination array types are equivalent, we're
3932 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3935 // Make sure that the element types are the same.
3936 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3939 // The only mismatch we allow is when the destination is an
3940 // incomplete array type and the source is a constant array type.
3941 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3944 static bool tryObjCWritebackConversion(Sema &S,
3945 InitializationSequence &Sequence,
3946 const InitializedEntity &Entity,
3947 Expr *Initializer) {
3948 bool ArrayDecay = false;
3949 QualType ArgType = Initializer->getType();
3950 QualType ArgPointee;
3951 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3953 ArgPointee = ArgArrayType->getElementType();
3954 ArgType = S.Context.getPointerType(ArgPointee);
3957 // Handle write-back conversion.
3958 QualType ConvertedArgType;
3959 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3963 // We should copy unless we're passing to an argument explicitly
3965 bool ShouldCopy = true;
3966 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3967 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3969 // Do we need an lvalue conversion?
3970 if (ArrayDecay || Initializer->isGLValue()) {
3971 ImplicitConversionSequence ICS;
3973 ICS.Standard.setAsIdentityConversion();
3975 QualType ResultType;
3977 ICS.Standard.First = ICK_Array_To_Pointer;
3978 ResultType = S.Context.getPointerType(ArgPointee);
3980 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3981 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3984 Sequence.AddConversionSequenceStep(ICS, ResultType);
3987 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3991 InitializationSequence::InitializationSequence(Sema &S,
3992 const InitializedEntity &Entity,
3993 const InitializationKind &Kind,
3996 : FailedCandidateSet(Kind.getLocation()) {
3997 ASTContext &Context = S.Context;
3999 // C++0x [dcl.init]p16:
4000 // The semantics of initializers are as follows. The destination type is
4001 // the type of the object or reference being initialized and the source
4002 // type is the type of the initializer expression. The source type is not
4003 // defined when the initializer is a braced-init-list or when it is a
4004 // parenthesized list of expressions.
4005 QualType DestType = Entity.getType();
4007 if (DestType->isDependentType() ||
4008 Expr::hasAnyTypeDependentArguments(llvm::makeArrayRef(Args, NumArgs))) {
4009 SequenceKind = DependentSequence;
4013 // Almost everything is a normal sequence.
4014 setSequenceKind(NormalSequence);
4016 for (unsigned I = 0; I != NumArgs; ++I)
4017 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4018 // FIXME: should we be doing this here?
4019 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4020 if (result.isInvalid()) {
4021 SetFailed(FK_PlaceholderType);
4024 Args[I] = result.take();
4028 QualType SourceType;
4029 Expr *Initializer = 0;
4031 Initializer = Args[0];
4032 if (!isa<InitListExpr>(Initializer))
4033 SourceType = Initializer->getType();
4036 // - If the initializer is a (non-parenthesized) braced-init-list, the
4037 // object is list-initialized (8.5.4).
4038 if (Kind.getKind() != InitializationKind::IK_Direct) {
4039 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4040 TryListInitialization(S, Entity, Kind, InitList, *this);
4045 // - If the destination type is a reference type, see 8.5.3.
4046 if (DestType->isReferenceType()) {
4047 // C++0x [dcl.init.ref]p1:
4048 // A variable declared to be a T& or T&&, that is, "reference to type T"
4049 // (8.3.2), shall be initialized by an object, or function, of type T or
4050 // by an object that can be converted into a T.
4051 // (Therefore, multiple arguments are not permitted.)
4053 SetFailed(FK_TooManyInitsForReference);
4055 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
4059 // - If the initializer is (), the object is value-initialized.
4060 if (Kind.getKind() == InitializationKind::IK_Value ||
4061 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
4062 TryValueInitialization(S, Entity, Kind, *this);
4066 // Handle default initialization.
4067 if (Kind.getKind() == InitializationKind::IK_Default) {
4068 TryDefaultInitialization(S, Entity, Kind, *this);
4072 // - If the destination type is an array of characters, an array of
4073 // char16_t, an array of char32_t, or an array of wchar_t, and the
4074 // initializer is a string literal, see 8.5.2.
4075 // - Otherwise, if the destination type is an array, the program is
4077 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
4078 if (Initializer && isa<VariableArrayType>(DestAT)) {
4079 SetFailed(FK_VariableLengthArrayHasInitializer);
4083 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
4084 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4088 // Note: as an GNU C extension, we allow initialization of an
4089 // array from a compound literal that creates an array of the same
4090 // type, so long as the initializer has no side effects.
4091 if (!S.getLangOpts().CPlusPlus && Initializer &&
4092 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4093 Initializer->getType()->isArrayType()) {
4094 const ArrayType *SourceAT
4095 = Context.getAsArrayType(Initializer->getType());
4096 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
4097 SetFailed(FK_ArrayTypeMismatch);
4098 else if (Initializer->HasSideEffects(S.Context))
4099 SetFailed(FK_NonConstantArrayInit);
4101 AddArrayInitStep(DestType);
4104 // Note: as a GNU C++ extension, we allow initialization of a
4105 // class member from a parenthesized initializer list.
4106 else if (S.getLangOpts().CPlusPlus &&
4107 Entity.getKind() == InitializedEntity::EK_Member &&
4108 Initializer && isa<InitListExpr>(Initializer)) {
4109 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4111 AddParenthesizedArrayInitStep(DestType);
4112 } else if (DestAT->getElementType()->isAnyCharacterType())
4113 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
4115 SetFailed(FK_ArrayNeedsInitList);
4120 // Determine whether we should consider writeback conversions for
4122 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
4123 Entity.getKind() == InitializedEntity::EK_Parameter;
4125 // We're at the end of the line for C: it's either a write-back conversion
4126 // or it's a C assignment. There's no need to check anything else.
4127 if (!S.getLangOpts().CPlusPlus) {
4128 // If allowed, check whether this is an Objective-C writeback conversion.
4129 if (allowObjCWritebackConversion &&
4130 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
4134 // Handle initialization in C
4135 AddCAssignmentStep(DestType);
4136 MaybeProduceObjCObject(S, *this, Entity);
4140 assert(S.getLangOpts().CPlusPlus);
4142 // - If the destination type is a (possibly cv-qualified) class type:
4143 if (DestType->isRecordType()) {
4144 // - If the initialization is direct-initialization, or if it is
4145 // copy-initialization where the cv-unqualified version of the
4146 // source type is the same class as, or a derived class of, the
4147 // class of the destination, constructors are considered. [...]
4148 if (Kind.getKind() == InitializationKind::IK_Direct ||
4149 (Kind.getKind() == InitializationKind::IK_Copy &&
4150 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4151 S.IsDerivedFrom(SourceType, DestType))))
4152 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
4153 Entity.getType(), *this);
4154 // - Otherwise (i.e., for the remaining copy-initialization cases),
4155 // user-defined conversion sequences that can convert from the source
4156 // type to the destination type or (when a conversion function is
4157 // used) to a derived class thereof are enumerated as described in
4158 // 13.3.1.4, and the best one is chosen through overload resolution
4161 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4166 SetFailed(FK_TooManyInitsForScalar);
4169 assert(NumArgs == 1 && "Zero-argument case handled above");
4171 // - Otherwise, if the source type is a (possibly cv-qualified) class
4172 // type, conversion functions are considered.
4173 if (!SourceType.isNull() && SourceType->isRecordType()) {
4174 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4175 MaybeProduceObjCObject(S, *this, Entity);
4179 // - Otherwise, the initial value of the object being initialized is the
4180 // (possibly converted) value of the initializer expression. Standard
4181 // conversions (Clause 4) will be used, if necessary, to convert the
4182 // initializer expression to the cv-unqualified version of the
4183 // destination type; no user-defined conversions are considered.
4185 ImplicitConversionSequence ICS
4186 = S.TryImplicitConversion(Initializer, Entity.getType(),
4187 /*SuppressUserConversions*/true,
4188 /*AllowExplicitConversions*/ false,
4189 /*InOverloadResolution*/ false,
4190 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4191 allowObjCWritebackConversion);
4193 if (ICS.isStandard() &&
4194 ICS.Standard.Second == ICK_Writeback_Conversion) {
4195 // Objective-C ARC writeback conversion.
4197 // We should copy unless we're passing to an argument explicitly
4199 bool ShouldCopy = true;
4200 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4201 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4203 // If there was an lvalue adjustment, add it as a separate conversion.
4204 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4205 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4206 ImplicitConversionSequence LvalueICS;
4207 LvalueICS.setStandard();
4208 LvalueICS.Standard.setAsIdentityConversion();
4209 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4210 LvalueICS.Standard.First = ICS.Standard.First;
4211 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
4214 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4215 } else if (ICS.isBad()) {
4217 if (Initializer->getType() == Context.OverloadTy &&
4218 !S.ResolveAddressOfOverloadedFunction(Initializer
4219 , DestType, false, dap))
4220 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4222 SetFailed(InitializationSequence::FK_ConversionFailed);
4224 AddConversionSequenceStep(ICS, Entity.getType());
4226 MaybeProduceObjCObject(S, *this, Entity);
4230 InitializationSequence::~InitializationSequence() {
4231 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
4232 StepEnd = Steps.end();
4233 Step != StepEnd; ++Step)
4237 //===----------------------------------------------------------------------===//
4238 // Perform initialization
4239 //===----------------------------------------------------------------------===//
4240 static Sema::AssignmentAction
4241 getAssignmentAction(const InitializedEntity &Entity) {
4242 switch(Entity.getKind()) {
4243 case InitializedEntity::EK_Variable:
4244 case InitializedEntity::EK_New:
4245 case InitializedEntity::EK_Exception:
4246 case InitializedEntity::EK_Base:
4247 case InitializedEntity::EK_Delegating:
4248 return Sema::AA_Initializing;
4250 case InitializedEntity::EK_Parameter:
4251 if (Entity.getDecl() &&
4252 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4253 return Sema::AA_Sending;
4255 return Sema::AA_Passing;
4257 case InitializedEntity::EK_Result:
4258 return Sema::AA_Returning;
4260 case InitializedEntity::EK_Temporary:
4261 // FIXME: Can we tell apart casting vs. converting?
4262 return Sema::AA_Casting;
4264 case InitializedEntity::EK_Member:
4265 case InitializedEntity::EK_ArrayElement:
4266 case InitializedEntity::EK_VectorElement:
4267 case InitializedEntity::EK_ComplexElement:
4268 case InitializedEntity::EK_BlockElement:
4269 case InitializedEntity::EK_LambdaCapture:
4270 return Sema::AA_Initializing;
4273 llvm_unreachable("Invalid EntityKind!");
4276 /// \brief Whether we should binding a created object as a temporary when
4277 /// initializing the given entity.
4278 static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
4279 switch (Entity.getKind()) {
4280 case InitializedEntity::EK_ArrayElement:
4281 case InitializedEntity::EK_Member:
4282 case InitializedEntity::EK_Result:
4283 case InitializedEntity::EK_New:
4284 case InitializedEntity::EK_Variable:
4285 case InitializedEntity::EK_Base:
4286 case InitializedEntity::EK_Delegating:
4287 case InitializedEntity::EK_VectorElement:
4288 case InitializedEntity::EK_ComplexElement:
4289 case InitializedEntity::EK_Exception:
4290 case InitializedEntity::EK_BlockElement:
4291 case InitializedEntity::EK_LambdaCapture:
4294 case InitializedEntity::EK_Parameter:
4295 case InitializedEntity::EK_Temporary:
4299 llvm_unreachable("missed an InitializedEntity kind?");
4302 /// \brief Whether the given entity, when initialized with an object
4303 /// created for that initialization, requires destruction.
4304 static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4305 switch (Entity.getKind()) {
4306 case InitializedEntity::EK_Member:
4307 case InitializedEntity::EK_Result:
4308 case InitializedEntity::EK_New:
4309 case InitializedEntity::EK_Base:
4310 case InitializedEntity::EK_Delegating:
4311 case InitializedEntity::EK_VectorElement:
4312 case InitializedEntity::EK_ComplexElement:
4313 case InitializedEntity::EK_BlockElement:
4314 case InitializedEntity::EK_LambdaCapture:
4317 case InitializedEntity::EK_Variable:
4318 case InitializedEntity::EK_Parameter:
4319 case InitializedEntity::EK_Temporary:
4320 case InitializedEntity::EK_ArrayElement:
4321 case InitializedEntity::EK_Exception:
4325 llvm_unreachable("missed an InitializedEntity kind?");
4328 /// \brief Look for copy and move constructors and constructor templates, for
4329 /// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4330 static void LookupCopyAndMoveConstructors(Sema &S,
4331 OverloadCandidateSet &CandidateSet,
4332 CXXRecordDecl *Class,
4333 Expr *CurInitExpr) {
4334 DeclContext::lookup_iterator Con, ConEnd;
4335 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
4336 Con != ConEnd; ++Con) {
4337 CXXConstructorDecl *Constructor = 0;
4339 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
4340 // Handle copy/moveconstructors, only.
4341 if (!Constructor || Constructor->isInvalidDecl() ||
4342 !Constructor->isCopyOrMoveConstructor() ||
4343 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4346 DeclAccessPair FoundDecl
4347 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4348 S.AddOverloadCandidate(Constructor, FoundDecl,
4349 CurInitExpr, CandidateSet);
4353 // Handle constructor templates.
4354 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4355 if (ConstructorTmpl->isInvalidDecl())
4358 Constructor = cast<CXXConstructorDecl>(
4359 ConstructorTmpl->getTemplatedDecl());
4360 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4363 // FIXME: Do we need to limit this to copy-constructor-like
4365 DeclAccessPair FoundDecl
4366 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4367 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4368 CurInitExpr, CandidateSet, true);
4372 /// \brief Get the location at which initialization diagnostics should appear.
4373 static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4374 Expr *Initializer) {
4375 switch (Entity.getKind()) {
4376 case InitializedEntity::EK_Result:
4377 return Entity.getReturnLoc();
4379 case InitializedEntity::EK_Exception:
4380 return Entity.getThrowLoc();
4382 case InitializedEntity::EK_Variable:
4383 return Entity.getDecl()->getLocation();
4385 case InitializedEntity::EK_LambdaCapture:
4386 return Entity.getCaptureLoc();
4388 case InitializedEntity::EK_ArrayElement:
4389 case InitializedEntity::EK_Member:
4390 case InitializedEntity::EK_Parameter:
4391 case InitializedEntity::EK_Temporary:
4392 case InitializedEntity::EK_New:
4393 case InitializedEntity::EK_Base:
4394 case InitializedEntity::EK_Delegating:
4395 case InitializedEntity::EK_VectorElement:
4396 case InitializedEntity::EK_ComplexElement:
4397 case InitializedEntity::EK_BlockElement:
4398 return Initializer->getLocStart();
4400 llvm_unreachable("missed an InitializedEntity kind?");
4403 /// \brief Make a (potentially elidable) temporary copy of the object
4404 /// provided by the given initializer by calling the appropriate copy
4407 /// \param S The Sema object used for type-checking.
4409 /// \param T The type of the temporary object, which must either be
4410 /// the type of the initializer expression or a superclass thereof.
4412 /// \param Enter The entity being initialized.
4414 /// \param CurInit The initializer expression.
4416 /// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4417 /// is permitted in C++03 (but not C++0x) when binding a reference to
4420 /// \returns An expression that copies the initializer expression into
4421 /// a temporary object, or an error expression if a copy could not be
4423 static ExprResult CopyObject(Sema &S,
4425 const InitializedEntity &Entity,
4427 bool IsExtraneousCopy) {
4428 // Determine which class type we're copying to.
4429 Expr *CurInitExpr = (Expr *)CurInit.get();
4430 CXXRecordDecl *Class = 0;
4431 if (const RecordType *Record = T->getAs<RecordType>())
4432 Class = cast<CXXRecordDecl>(Record->getDecl());
4434 return move(CurInit);
4436 // C++0x [class.copy]p32:
4437 // When certain criteria are met, an implementation is allowed to
4438 // omit the copy/move construction of a class object, even if the
4439 // copy/move constructor and/or destructor for the object have
4440 // side effects. [...]
4441 // - when a temporary class object that has not been bound to a
4442 // reference (12.2) would be copied/moved to a class object
4443 // with the same cv-unqualified type, the copy/move operation
4444 // can be omitted by constructing the temporary object
4445 // directly into the target of the omitted copy/move
4447 // Note that the other three bullets are handled elsewhere. Copy
4448 // elision for return statements and throw expressions are handled as part
4449 // of constructor initialization, while copy elision for exception handlers
4450 // is handled by the run-time.
4451 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
4452 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
4454 // Make sure that the type we are copying is complete.
4455 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4456 return move(CurInit);
4458 // Perform overload resolution using the class's copy/move constructors.
4459 // Only consider constructors and constructor templates. Per
4460 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4461 // is direct-initialization.
4462 OverloadCandidateSet CandidateSet(Loc);
4463 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
4465 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4467 OverloadCandidateSet::iterator Best;
4468 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
4472 case OR_No_Viable_Function:
4473 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4474 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4475 : diag::err_temp_copy_no_viable)
4476 << (int)Entity.getKind() << CurInitExpr->getType()
4477 << CurInitExpr->getSourceRange();
4478 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
4479 if (!IsExtraneousCopy || S.isSFINAEContext())
4481 return move(CurInit);
4484 S.Diag(Loc, diag::err_temp_copy_ambiguous)
4485 << (int)Entity.getKind() << CurInitExpr->getType()
4486 << CurInitExpr->getSourceRange();
4487 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
4491 S.Diag(Loc, diag::err_temp_copy_deleted)
4492 << (int)Entity.getKind() << CurInitExpr->getType()
4493 << CurInitExpr->getSourceRange();
4494 S.NoteDeletedFunction(Best->Function);
4498 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
4499 ASTOwningVector<Expr*> ConstructorArgs(S);
4500 CurInit.release(); // Ownership transferred into MultiExprArg, below.
4502 S.CheckConstructorAccess(Loc, Constructor, Entity,
4503 Best->FoundDecl.getAccess(), IsExtraneousCopy);
4505 if (IsExtraneousCopy) {
4506 // If this is a totally extraneous copy for C++03 reference
4507 // binding purposes, just return the original initialization
4508 // expression. We don't generate an (elided) copy operation here
4509 // because doing so would require us to pass down a flag to avoid
4510 // infinite recursion, where each step adds another extraneous,
4513 // Instantiate the default arguments of any extra parameters in
4514 // the selected copy constructor, as if we were going to create a
4515 // proper call to the copy constructor.
4516 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4517 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4518 if (S.RequireCompleteType(Loc, Parm->getType(),
4519 S.PDiag(diag::err_call_incomplete_argument)))
4522 // Build the default argument expression; we don't actually care
4523 // if this succeeds or not, because this routine will complain
4524 // if there was a problem.
4525 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4528 return S.Owned(CurInitExpr);
4531 S.MarkFunctionReferenced(Loc, Constructor);
4533 // Determine the arguments required to actually perform the
4534 // constructor call (we might have derived-to-base conversions, or
4535 // the copy constructor may have default arguments).
4536 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
4537 Loc, ConstructorArgs))
4540 // Actually perform the constructor call.
4541 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
4542 move_arg(ConstructorArgs),
4543 HadMultipleCandidates,
4545 CXXConstructExpr::CK_Complete,
4548 // If we're supposed to bind temporaries, do so.
4549 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4550 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4551 return move(CurInit);
4554 /// \brief Check whether elidable copy construction for binding a reference to
4555 /// a temporary would have succeeded if we were building in C++98 mode, for
4557 static void CheckCXX98CompatAccessibleCopy(Sema &S,
4558 const InitializedEntity &Entity,
4559 Expr *CurInitExpr) {
4560 assert(S.getLangOpts().CPlusPlus0x);
4562 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4566 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4567 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4568 == DiagnosticsEngine::Ignored)
4571 // Find constructors which would have been considered.
4572 OverloadCandidateSet CandidateSet(Loc);
4573 LookupCopyAndMoveConstructors(
4574 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4576 // Perform overload resolution.
4577 OverloadCandidateSet::iterator Best;
4578 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4580 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4581 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4582 << CurInitExpr->getSourceRange();
4586 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
4587 Entity, Best->FoundDecl.getAccess(), Diag);
4588 // FIXME: Check default arguments as far as that's possible.
4591 case OR_No_Viable_Function:
4593 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
4598 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
4603 S.NoteDeletedFunction(Best->Function);
4608 void InitializationSequence::PrintInitLocationNote(Sema &S,
4609 const InitializedEntity &Entity) {
4610 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4611 if (Entity.getDecl()->getLocation().isInvalid())
4614 if (Entity.getDecl()->getDeclName())
4615 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4616 << Entity.getDecl()->getDeclName();
4618 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4622 static bool isReferenceBinding(const InitializationSequence::Step &s) {
4623 return s.Kind == InitializationSequence::SK_BindReference ||
4624 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4628 PerformConstructorInitialization(Sema &S,
4629 const InitializedEntity &Entity,
4630 const InitializationKind &Kind,
4632 const InitializationSequence::Step& Step,
4633 bool &ConstructorInitRequiresZeroInit) {
4634 unsigned NumArgs = Args.size();
4635 CXXConstructorDecl *Constructor
4636 = cast<CXXConstructorDecl>(Step.Function.Function);
4637 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4639 // Build a call to the selected constructor.
4640 ASTOwningVector<Expr*> ConstructorArgs(S);
4641 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4642 ? Kind.getEqualLoc()
4643 : Kind.getLocation();
4645 if (Kind.getKind() == InitializationKind::IK_Default) {
4646 // Force even a trivial, implicit default constructor to be
4647 // semantically checked. We do this explicitly because we don't build
4648 // the definition for completely trivial constructors.
4649 assert(Constructor->getParent() && "No parent class for constructor.");
4650 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
4651 Constructor->isTrivial() && !Constructor->isUsed(false))
4652 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4655 ExprResult CurInit = S.Owned((Expr *)0);
4657 // C++ [over.match.copy]p1:
4658 // - When initializing a temporary to be bound to the first parameter
4659 // of a constructor that takes a reference to possibly cv-qualified
4660 // T as its first argument, called with a single argument in the
4661 // context of direct-initialization, explicit conversion functions
4662 // are also considered.
4663 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
4665 Constructor->isCopyOrMoveConstructor();
4667 // Determine the arguments required to actually perform the constructor
4669 if (S.CompleteConstructorCall(Constructor, move(Args),
4670 Loc, ConstructorArgs,
4675 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
4676 (Kind.getKind() == InitializationKind::IK_DirectList ||
4677 (NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4678 (Kind.getKind() == InitializationKind::IK_Direct ||
4679 Kind.getKind() == InitializationKind::IK_Value)))) {
4680 // An explicitly-constructed temporary, e.g., X(1, 2).
4681 unsigned NumExprs = ConstructorArgs.size();
4682 Expr **Exprs = (Expr **)ConstructorArgs.take();
4683 S.MarkFunctionReferenced(Loc, Constructor);
4684 S.DiagnoseUseOfDecl(Constructor, Loc);
4686 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4688 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
4689 SourceRange ParenRange;
4690 if (Kind.getKind() != InitializationKind::IK_DirectList)
4691 ParenRange = Kind.getParenRange();
4693 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4699 HadMultipleCandidates,
4700 ConstructorInitRequiresZeroInit));
4702 CXXConstructExpr::ConstructionKind ConstructKind =
4703 CXXConstructExpr::CK_Complete;
4705 if (Entity.getKind() == InitializedEntity::EK_Base) {
4706 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4707 CXXConstructExpr::CK_VirtualBase :
4708 CXXConstructExpr::CK_NonVirtualBase;
4709 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4710 ConstructKind = CXXConstructExpr::CK_Delegating;
4713 // Only get the parenthesis range if it is a direct construction.
4714 SourceRange parenRange =
4715 Kind.getKind() == InitializationKind::IK_Direct ?
4716 Kind.getParenRange() : SourceRange();
4718 // If the entity allows NRVO, mark the construction as elidable
4720 if (Entity.allowsNRVO())
4721 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4722 Constructor, /*Elidable=*/true,
4723 move_arg(ConstructorArgs),
4724 HadMultipleCandidates,
4725 ConstructorInitRequiresZeroInit,
4729 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4731 move_arg(ConstructorArgs),
4732 HadMultipleCandidates,
4733 ConstructorInitRequiresZeroInit,
4737 if (CurInit.isInvalid())
4740 // Only check access if all of that succeeded.
4741 S.CheckConstructorAccess(Loc, Constructor, Entity,
4742 Step.Function.FoundDecl.getAccess());
4743 S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc);
4745 if (shouldBindAsTemporary(Entity))
4746 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4748 return move(CurInit);
4752 InitializationSequence::Perform(Sema &S,
4753 const InitializedEntity &Entity,
4754 const InitializationKind &Kind,
4756 QualType *ResultType) {
4758 unsigned NumArgs = Args.size();
4759 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
4763 if (getKind() == DependentSequence) {
4764 // If the declaration is a non-dependent, incomplete array type
4765 // that has an initializer, then its type will be completed once
4766 // the initializer is instantiated.
4767 if (ResultType && !Entity.getType()->isDependentType() &&
4769 QualType DeclType = Entity.getType();
4770 if (const IncompleteArrayType *ArrayT
4771 = S.Context.getAsIncompleteArrayType(DeclType)) {
4772 // FIXME: We don't currently have the ability to accurately
4773 // compute the length of an initializer list without
4774 // performing full type-checking of the initializer list
4775 // (since we have to determine where braces are implicitly
4776 // introduced and such). So, we fall back to making the array
4777 // type a dependently-sized array type with no specified
4779 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4780 SourceRange Brackets;
4782 // Scavange the location of the brackets from the entity, if we can.
4783 if (DeclaratorDecl *DD = Entity.getDecl()) {
4784 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4785 TypeLoc TL = TInfo->getTypeLoc();
4786 if (IncompleteArrayTypeLoc *ArrayLoc
4787 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4788 Brackets = ArrayLoc->getBracketsRange();
4793 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4795 ArrayT->getSizeModifier(),
4796 ArrayT->getIndexTypeCVRQualifiers(),
4802 if (Kind.getKind() == InitializationKind::IK_Direct &&
4803 !Kind.isExplicitCast()) {
4804 // Rebuild the ParenListExpr.
4805 SourceRange ParenRange = Kind.getParenRange();
4806 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
4809 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4810 Kind.isExplicitCast() ||
4811 Kind.getKind() == InitializationKind::IK_DirectList);
4812 return ExprResult(Args.release()[0]);
4815 // No steps means no initialization.
4817 return S.Owned((Expr *)0);
4819 QualType DestType = Entity.getType().getNonReferenceType();
4820 // FIXME: Ugly hack around the fact that Entity.getType() is not
4821 // the same as Entity.getDecl()->getType() in cases involving type merging,
4822 // and we want latter when it makes sense.
4824 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
4827 ExprResult CurInit = S.Owned((Expr *)0);
4829 // For initialization steps that start with a single initializer,
4830 // grab the only argument out the Args and place it into the "current"
4832 switch (Steps.front().Kind) {
4833 case SK_ResolveAddressOfOverloadedFunction:
4834 case SK_CastDerivedToBaseRValue:
4835 case SK_CastDerivedToBaseXValue:
4836 case SK_CastDerivedToBaseLValue:
4837 case SK_BindReference:
4838 case SK_BindReferenceToTemporary:
4839 case SK_ExtraneousCopyToTemporary:
4840 case SK_UserConversion:
4841 case SK_QualificationConversionLValue:
4842 case SK_QualificationConversionXValue:
4843 case SK_QualificationConversionRValue:
4844 case SK_ConversionSequence:
4845 case SK_ListConstructorCall:
4846 case SK_ListInitialization:
4847 case SK_UnwrapInitList:
4848 case SK_RewrapInitList:
4849 case SK_CAssignment:
4851 case SK_ObjCObjectConversion:
4853 case SK_ParenthesizedArrayInit:
4854 case SK_PassByIndirectCopyRestore:
4855 case SK_PassByIndirectRestore:
4856 case SK_ProduceObjCObject:
4857 case SK_StdInitializerList: {
4858 assert(Args.size() == 1);
4859 CurInit = Args.get()[0];
4860 if (!CurInit.get()) return ExprError();
4864 case SK_ConstructorInitialization:
4865 case SK_ZeroInitialization:
4869 // Walk through the computed steps for the initialization sequence,
4870 // performing the specified conversions along the way.
4871 bool ConstructorInitRequiresZeroInit = false;
4872 for (step_iterator Step = step_begin(), StepEnd = step_end();
4873 Step != StepEnd; ++Step) {
4874 if (CurInit.isInvalid())
4877 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
4879 switch (Step->Kind) {
4880 case SK_ResolveAddressOfOverloadedFunction:
4881 // Overload resolution determined which function invoke; update the
4882 // initializer to reflect that choice.
4883 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
4884 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
4885 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
4886 Step->Function.FoundDecl,
4887 Step->Function.Function);
4890 case SK_CastDerivedToBaseRValue:
4891 case SK_CastDerivedToBaseXValue:
4892 case SK_CastDerivedToBaseLValue: {
4893 // We have a derived-to-base cast that produces either an rvalue or an
4894 // lvalue. Perform that cast.
4896 CXXCastPath BasePath;
4898 // Casts to inaccessible base classes are allowed with C-style casts.
4899 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4900 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
4901 CurInit.get()->getLocStart(),
4902 CurInit.get()->getSourceRange(),
4903 &BasePath, IgnoreBaseAccess))
4906 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4907 QualType T = SourceType;
4908 if (const PointerType *Pointer = T->getAs<PointerType>())
4909 T = Pointer->getPointeeType();
4910 if (const RecordType *RecordTy = T->getAs<RecordType>())
4911 S.MarkVTableUsed(CurInit.get()->getLocStart(),
4912 cast<CXXRecordDecl>(RecordTy->getDecl()));
4916 Step->Kind == SK_CastDerivedToBaseLValue ?
4918 (Step->Kind == SK_CastDerivedToBaseXValue ?
4921 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4929 case SK_BindReference:
4930 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
4931 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4932 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
4933 << Entity.getType().isVolatileQualified()
4934 << BitField->getDeclName()
4935 << CurInit.get()->getSourceRange();
4936 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
4940 if (CurInit.get()->refersToVectorElement()) {
4941 // References cannot bind to vector elements.
4942 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4943 << Entity.getType().isVolatileQualified()
4944 << CurInit.get()->getSourceRange();
4945 PrintInitLocationNote(S, Entity);
4949 // Reference binding does not have any corresponding ASTs.
4951 // Check exception specifications
4952 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
4957 case SK_BindReferenceToTemporary:
4958 // Check exception specifications
4959 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
4962 // Materialize the temporary into memory.
4963 CurInit = new (S.Context) MaterializeTemporaryExpr(
4964 Entity.getType().getNonReferenceType(),
4966 Entity.getType()->isLValueReferenceType());
4968 // If we're binding to an Objective-C object that has lifetime, we
4970 if (S.getLangOpts().ObjCAutoRefCount &&
4971 CurInit.get()->getType()->isObjCLifetimeType())
4972 S.ExprNeedsCleanups = true;
4976 case SK_ExtraneousCopyToTemporary:
4977 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
4978 /*IsExtraneousCopy=*/true);
4981 case SK_UserConversion: {
4982 // We have a user-defined conversion that invokes either a constructor
4983 // or a conversion function.
4985 bool IsCopy = false;
4986 FunctionDecl *Fn = Step->Function.Function;
4987 DeclAccessPair FoundFn = Step->Function.FoundDecl;
4988 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
4989 bool CreatedObject = false;
4990 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
4991 // Build a call to the selected constructor.
4992 ASTOwningVector<Expr*> ConstructorArgs(S);
4993 SourceLocation Loc = CurInit.get()->getLocStart();
4994 CurInit.release(); // Ownership transferred into MultiExprArg, below.
4996 // Determine the arguments required to actually perform the constructor
4998 Expr *Arg = CurInit.get();
4999 if (S.CompleteConstructorCall(Constructor,
5000 MultiExprArg(&Arg, 1),
5001 Loc, ConstructorArgs))
5004 // Build an expression that constructs a temporary.
5005 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
5006 move_arg(ConstructorArgs),
5007 HadMultipleCandidates,
5009 CXXConstructExpr::CK_Complete,
5011 if (CurInit.isInvalid())
5014 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
5015 FoundFn.getAccess());
5016 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
5018 CastKind = CK_ConstructorConversion;
5019 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5020 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5021 S.IsDerivedFrom(SourceType, Class))
5024 CreatedObject = true;
5026 // Build a call to the conversion function.
5027 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
5028 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
5030 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
5032 // FIXME: Should we move this initialization into a separate
5033 // derived-to-base conversion? I believe the answer is "no", because
5034 // we don't want to turn off access control here for c-style casts.
5035 ExprResult CurInitExprRes =
5036 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5037 FoundFn, Conversion);
5038 if(CurInitExprRes.isInvalid())
5040 CurInit = move(CurInitExprRes);
5042 // Build the actual call to the conversion function.
5043 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5044 HadMultipleCandidates);
5045 if (CurInit.isInvalid() || !CurInit.get())
5048 CastKind = CK_UserDefinedConversion;
5050 CreatedObject = Conversion->getResultType()->isRecordType();
5053 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
5054 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5056 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
5057 QualType T = CurInit.get()->getType();
5058 if (const RecordType *Record = T->getAs<RecordType>()) {
5059 CXXDestructorDecl *Destructor
5060 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
5061 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
5062 S.PDiag(diag::err_access_dtor_temp) << T);
5063 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
5064 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
5068 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
5069 CurInit.get()->getType(),
5070 CastKind, CurInit.get(), 0,
5071 CurInit.get()->getValueKind()));
5072 if (MaybeBindToTemp)
5073 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
5075 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
5076 move(CurInit), /*IsExtraneousCopy=*/false);
5080 case SK_QualificationConversionLValue:
5081 case SK_QualificationConversionXValue:
5082 case SK_QualificationConversionRValue: {
5083 // Perform a qualification conversion; these can never go wrong.
5085 Step->Kind == SK_QualificationConversionLValue ?
5087 (Step->Kind == SK_QualificationConversionXValue ?
5090 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
5094 case SK_ConversionSequence: {
5095 Sema::CheckedConversionKind CCK
5096 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5097 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
5098 : Kind.isExplicitCast()? Sema::CCK_OtherCast
5099 : Sema::CCK_ImplicitConversion;
5100 ExprResult CurInitExprRes =
5101 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
5102 getAssignmentAction(Entity), CCK);
5103 if (CurInitExprRes.isInvalid())
5105 CurInit = move(CurInitExprRes);
5109 case SK_ListInitialization: {
5110 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
5111 // Hack: We must pass *ResultType if available in order to set the type
5112 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5113 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5114 // temporary, not a reference, so we should pass Ty.
5115 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5116 // Since this step is never used for a reference directly, we explicitly
5117 // unwrap references here and rewrap them afterwards.
5118 // We also need to create a InitializeTemporary entity for this.
5119 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
5120 bool IsTemporary = Entity.getType()->isReferenceType();
5121 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
5122 InitListChecker PerformInitList(S, IsTemporary ? TempEntity : Entity,
5123 InitList, Ty, /*VerifyOnly=*/false,
5124 Kind.getKind() != InitializationKind::IK_DirectList ||
5125 !S.getLangOpts().CPlusPlus0x);
5126 if (PerformInitList.HadError())
5130 if ((*ResultType)->isRValueReferenceType())
5131 Ty = S.Context.getRValueReferenceType(Ty);
5132 else if ((*ResultType)->isLValueReferenceType())
5133 Ty = S.Context.getLValueReferenceType(Ty,
5134 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5138 InitListExpr *StructuredInitList =
5139 PerformInitList.getFullyStructuredList();
5141 CurInit = S.Owned(StructuredInitList);
5145 case SK_ListConstructorCall: {
5146 // When an initializer list is passed for a parameter of type "reference
5147 // to object", we don't get an EK_Temporary entity, but instead an
5148 // EK_Parameter entity with reference type.
5149 // FIXME: This is a hack. What we really should do is create a user
5150 // conversion step for this case, but this makes it considerably more
5151 // complicated. For now, this will do.
5152 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5153 Entity.getType().getNonReferenceType());
5154 bool UseTemporary = Entity.getType()->isReferenceType();
5155 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
5156 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
5157 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
5159 Kind, move(Arg), *Step,
5160 ConstructorInitRequiresZeroInit);
5164 case SK_UnwrapInitList:
5165 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5168 case SK_RewrapInitList: {
5169 Expr *E = CurInit.take();
5170 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5171 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
5172 Syntactic->getLBraceLoc(), &E, 1, Syntactic->getRBraceLoc());
5173 ILE->setSyntacticForm(Syntactic);
5174 ILE->setType(E->getType());
5175 ILE->setValueKind(E->getValueKind());
5176 CurInit = S.Owned(ILE);
5180 case SK_ConstructorInitialization: {
5181 // When an initializer list is passed for a parameter of type "reference
5182 // to object", we don't get an EK_Temporary entity, but instead an
5183 // EK_Parameter entity with reference type.
5184 // FIXME: This is a hack. What we really should do is create a user
5185 // conversion step for this case, but this makes it considerably more
5186 // complicated. For now, this will do.
5187 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5188 Entity.getType().getNonReferenceType());
5189 bool UseTemporary = Entity.getType()->isReferenceType();
5190 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
5192 Kind, move(Args), *Step,
5193 ConstructorInitRequiresZeroInit);
5197 case SK_ZeroInitialization: {
5198 step_iterator NextStep = Step;
5200 if (NextStep != StepEnd &&
5201 NextStep->Kind == SK_ConstructorInitialization) {
5202 // The need for zero-initialization is recorded directly into
5203 // the call to the object's constructor within the next step.
5204 ConstructorInitRequiresZeroInit = true;
5205 } else if (Kind.getKind() == InitializationKind::IK_Value &&
5206 S.getLangOpts().CPlusPlus &&
5207 !Kind.isImplicitValueInit()) {
5208 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5210 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
5211 Kind.getRange().getBegin());
5213 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5214 TSInfo->getType().getNonLValueExprType(S.Context),
5216 Kind.getRange().getEnd()));
5218 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
5223 case SK_CAssignment: {
5224 QualType SourceType = CurInit.get()->getType();
5225 ExprResult Result = move(CurInit);
5226 Sema::AssignConvertType ConvTy =
5227 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5228 if (Result.isInvalid())
5230 CurInit = move(Result);
5232 // If this is a call, allow conversion to a transparent union.
5233 ExprResult CurInitExprRes = move(CurInit);
5234 if (ConvTy != Sema::Compatible &&
5235 Entity.getKind() == InitializedEntity::EK_Parameter &&
5236 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
5237 == Sema::Compatible)
5238 ConvTy = Sema::Compatible;
5239 if (CurInitExprRes.isInvalid())
5241 CurInit = move(CurInitExprRes);
5244 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5245 Step->Type, SourceType,
5247 getAssignmentAction(Entity),
5249 PrintInitLocationNote(S, Entity);
5251 } else if (Complained)
5252 PrintInitLocationNote(S, Entity);
5256 case SK_StringInit: {
5257 QualType Ty = Step->Type;
5258 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
5259 S.Context.getAsArrayType(Ty), S);
5263 case SK_ObjCObjectConversion:
5264 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
5265 CK_ObjCObjectLValueCast,
5266 CurInit.get()->getValueKind());
5270 // Okay: we checked everything before creating this step. Note that
5271 // this is a GNU extension.
5272 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
5273 << Step->Type << CurInit.get()->getType()
5274 << CurInit.get()->getSourceRange();
5276 // If the destination type is an incomplete array type, update the
5277 // type accordingly.
5279 if (const IncompleteArrayType *IncompleteDest
5280 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5281 if (const ConstantArrayType *ConstantSource
5282 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
5283 *ResultType = S.Context.getConstantArrayType(
5284 IncompleteDest->getElementType(),
5285 ConstantSource->getSize(),
5286 ArrayType::Normal, 0);
5292 case SK_ParenthesizedArrayInit:
5293 // Okay: we checked everything before creating this step. Note that
5294 // this is a GNU extension.
5295 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
5296 << CurInit.get()->getSourceRange();
5299 case SK_PassByIndirectCopyRestore:
5300 case SK_PassByIndirectRestore:
5301 checkIndirectCopyRestoreSource(S, CurInit.get());
5302 CurInit = S.Owned(new (S.Context)
5303 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5304 Step->Kind == SK_PassByIndirectCopyRestore));
5307 case SK_ProduceObjCObject:
5308 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
5309 CK_ARCProduceObject,
5310 CurInit.take(), 0, VK_RValue));
5313 case SK_StdInitializerList: {
5314 QualType Dest = Step->Type;
5316 bool Success = S.isStdInitializerList(Dest, &E);
5318 assert(Success && "Destination type changed?");
5320 // If the element type has a destructor, check it.
5321 if (CXXRecordDecl *RD = E->getAsCXXRecordDecl()) {
5322 if (!RD->hasIrrelevantDestructor()) {
5323 if (CXXDestructorDecl *Destructor = S.LookupDestructor(RD)) {
5324 S.MarkFunctionReferenced(Kind.getLocation(), Destructor);
5325 S.CheckDestructorAccess(Kind.getLocation(), Destructor,
5326 S.PDiag(diag::err_access_dtor_temp) << E);
5327 S.DiagnoseUseOfDecl(Destructor, Kind.getLocation());
5332 InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
5333 unsigned NumInits = ILE->getNumInits();
5334 SmallVector<Expr*, 16> Converted(NumInits);
5335 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5336 S.Context.getConstantArrayType(E,
5337 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5339 ArrayType::Normal, 0));
5340 InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5342 for (unsigned i = 0; i < NumInits; ++i) {
5343 Element.setElementIndex(i);
5344 ExprResult Init = S.Owned(ILE->getInit(i));
5345 ExprResult Res = S.PerformCopyInitialization(Element,
5346 Init.get()->getExprLoc(),
5348 assert(!Res.isInvalid() && "Result changed since try phase.");
5349 Converted[i] = Res.take();
5351 InitListExpr *Semantic = new (S.Context)
5352 InitListExpr(S.Context, ILE->getLBraceLoc(),
5353 Converted.data(), NumInits, ILE->getRBraceLoc());
5354 Semantic->setSyntacticForm(ILE);
5355 Semantic->setType(Dest);
5356 Semantic->setInitializesStdInitializerList();
5357 CurInit = S.Owned(Semantic);
5363 // Diagnose non-fatal problems with the completed initialization.
5364 if (Entity.getKind() == InitializedEntity::EK_Member &&
5365 cast<FieldDecl>(Entity.getDecl())->isBitField())
5366 S.CheckBitFieldInitialization(Kind.getLocation(),
5367 cast<FieldDecl>(Entity.getDecl()),
5370 return move(CurInit);
5373 //===----------------------------------------------------------------------===//
5374 // Diagnose initialization failures
5375 //===----------------------------------------------------------------------===//
5376 bool InitializationSequence::Diagnose(Sema &S,
5377 const InitializedEntity &Entity,
5378 const InitializationKind &Kind,
5379 Expr **Args, unsigned NumArgs) {
5383 QualType DestType = Entity.getType();
5385 case FK_TooManyInitsForReference:
5386 // FIXME: Customize for the initialized entity?
5388 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
5389 << DestType.getNonReferenceType();
5390 else // FIXME: diagnostic below could be better!
5391 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
5392 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
5395 case FK_ArrayNeedsInitList:
5396 case FK_ArrayNeedsInitListOrStringLiteral:
5397 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5398 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5401 case FK_ArrayTypeMismatch:
5402 case FK_NonConstantArrayInit:
5403 S.Diag(Kind.getLocation(),
5404 (Failure == FK_ArrayTypeMismatch
5405 ? diag::err_array_init_different_type
5406 : diag::err_array_init_non_constant_array))
5407 << DestType.getNonReferenceType()
5408 << Args[0]->getType()
5409 << Args[0]->getSourceRange();
5412 case FK_VariableLengthArrayHasInitializer:
5413 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5414 << Args[0]->getSourceRange();
5417 case FK_AddressOfOverloadFailed: {
5418 DeclAccessPair Found;
5419 S.ResolveAddressOfOverloadedFunction(Args[0],
5420 DestType.getNonReferenceType(),
5426 case FK_ReferenceInitOverloadFailed:
5427 case FK_UserConversionOverloadFailed:
5428 switch (FailedOverloadResult) {
5430 if (Failure == FK_UserConversionOverloadFailed)
5431 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5432 << Args[0]->getType() << DestType
5433 << Args[0]->getSourceRange();
5435 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5436 << DestType << Args[0]->getType()
5437 << Args[0]->getSourceRange();
5439 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5440 llvm::makeArrayRef(Args, NumArgs));
5443 case OR_No_Viable_Function:
5444 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5445 << Args[0]->getType() << DestType.getNonReferenceType()
5446 << Args[0]->getSourceRange();
5447 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates,
5448 llvm::makeArrayRef(Args, NumArgs));
5452 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5453 << Args[0]->getType() << DestType.getNonReferenceType()
5454 << Args[0]->getSourceRange();
5455 OverloadCandidateSet::iterator Best;
5456 OverloadingResult Ovl
5457 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5459 if (Ovl == OR_Deleted) {
5460 S.NoteDeletedFunction(Best->Function);
5462 llvm_unreachable("Inconsistent overload resolution?");
5468 llvm_unreachable("Conversion did not fail!");
5472 case FK_NonConstLValueReferenceBindingToTemporary:
5473 if (isa<InitListExpr>(Args[0])) {
5474 S.Diag(Kind.getLocation(),
5475 diag::err_lvalue_reference_bind_to_initlist)
5476 << DestType.getNonReferenceType().isVolatileQualified()
5477 << DestType.getNonReferenceType()
5478 << Args[0]->getSourceRange();
5481 // Intentional fallthrough
5483 case FK_NonConstLValueReferenceBindingToUnrelated:
5484 S.Diag(Kind.getLocation(),
5485 Failure == FK_NonConstLValueReferenceBindingToTemporary
5486 ? diag::err_lvalue_reference_bind_to_temporary
5487 : diag::err_lvalue_reference_bind_to_unrelated)
5488 << DestType.getNonReferenceType().isVolatileQualified()
5489 << DestType.getNonReferenceType()
5490 << Args[0]->getType()
5491 << Args[0]->getSourceRange();
5494 case FK_RValueReferenceBindingToLValue:
5495 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
5496 << DestType.getNonReferenceType() << Args[0]->getType()
5497 << Args[0]->getSourceRange();
5500 case FK_ReferenceInitDropsQualifiers:
5501 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5502 << DestType.getNonReferenceType()
5503 << Args[0]->getType()
5504 << Args[0]->getSourceRange();
5507 case FK_ReferenceInitFailed:
5508 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5509 << DestType.getNonReferenceType()
5510 << Args[0]->isLValue()
5511 << Args[0]->getType()
5512 << Args[0]->getSourceRange();
5513 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5514 Args[0]->getType()->isObjCObjectPointerType())
5515 S.EmitRelatedResultTypeNote(Args[0]);
5518 case FK_ConversionFailed: {
5519 QualType FromType = Args[0]->getType();
5520 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
5521 << (int)Entity.getKind()
5523 << Args[0]->isLValue()
5525 << Args[0]->getSourceRange();
5526 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5527 S.Diag(Kind.getLocation(), PDiag);
5528 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5529 Args[0]->getType()->isObjCObjectPointerType())
5530 S.EmitRelatedResultTypeNote(Args[0]);
5534 case FK_ConversionFromPropertyFailed:
5535 // No-op. This error has already been reported.
5538 case FK_TooManyInitsForScalar: {
5541 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
5542 R = SourceRange(InitList->getInit(0)->getLocEnd(),
5543 InitList->getLocEnd());
5545 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
5547 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5548 if (Kind.isCStyleOrFunctionalCast())
5549 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5552 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5553 << /*scalar=*/2 << R;
5557 case FK_ReferenceBindingToInitList:
5558 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5559 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5562 case FK_InitListBadDestinationType:
5563 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5564 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5567 case FK_ListConstructorOverloadFailed:
5568 case FK_ConstructorOverloadFailed: {
5569 SourceRange ArgsRange;
5571 ArgsRange = SourceRange(Args[0]->getLocStart(),
5572 Args[NumArgs - 1]->getLocEnd());
5574 if (Failure == FK_ListConstructorOverloadFailed) {
5575 assert(NumArgs == 1 && "List construction from other than 1 argument.");
5576 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5577 Args = InitList->getInits();
5578 NumArgs = InitList->getNumInits();
5581 // FIXME: Using "DestType" for the entity we're printing is probably
5583 switch (FailedOverloadResult) {
5585 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5586 << DestType << ArgsRange;
5587 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5588 llvm::makeArrayRef(Args, NumArgs));
5591 case OR_No_Viable_Function:
5592 if (Kind.getKind() == InitializationKind::IK_Default &&
5593 (Entity.getKind() == InitializedEntity::EK_Base ||
5594 Entity.getKind() == InitializedEntity::EK_Member) &&
5595 isa<CXXConstructorDecl>(S.CurContext)) {
5596 // This is implicit default initialization of a member or
5597 // base within a constructor. If no viable function was
5598 // found, notify the user that she needs to explicitly
5599 // initialize this base/member.
5600 CXXConstructorDecl *Constructor
5601 = cast<CXXConstructorDecl>(S.CurContext);
5602 if (Entity.getKind() == InitializedEntity::EK_Base) {
5603 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5604 << Constructor->isImplicit()
5605 << S.Context.getTypeDeclType(Constructor->getParent())
5607 << Entity.getType();
5609 RecordDecl *BaseDecl
5610 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5612 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5613 << S.Context.getTagDeclType(BaseDecl);
5615 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5616 << Constructor->isImplicit()
5617 << S.Context.getTypeDeclType(Constructor->getParent())
5619 << Entity.getName();
5620 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5622 if (const RecordType *Record
5623 = Entity.getType()->getAs<RecordType>())
5624 S.Diag(Record->getDecl()->getLocation(),
5625 diag::note_previous_decl)
5626 << S.Context.getTagDeclType(Record->getDecl());
5631 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5632 << DestType << ArgsRange;
5633 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates,
5634 llvm::makeArrayRef(Args, NumArgs));
5638 OverloadCandidateSet::iterator Best;
5639 OverloadingResult Ovl
5640 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
5641 if (Ovl != OR_Deleted) {
5642 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5643 << true << DestType << ArgsRange;
5644 llvm_unreachable("Inconsistent overload resolution?");
5648 // If this is a defaulted or implicitly-declared function, then
5649 // it was implicitly deleted. Make it clear that the deletion was
5651 if (S.isImplicitlyDeleted(Best->Function))
5652 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
5653 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
5654 << DestType << ArgsRange;
5656 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5657 << true << DestType << ArgsRange;
5659 S.NoteDeletedFunction(Best->Function);
5664 llvm_unreachable("Conversion did not fail!");
5669 case FK_DefaultInitOfConst:
5670 if (Entity.getKind() == InitializedEntity::EK_Member &&
5671 isa<CXXConstructorDecl>(S.CurContext)) {
5672 // This is implicit default-initialization of a const member in
5673 // a constructor. Complain that it needs to be explicitly
5675 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5676 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5677 << Constructor->isImplicit()
5678 << S.Context.getTypeDeclType(Constructor->getParent())
5680 << Entity.getName();
5681 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5682 << Entity.getName();
5684 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5685 << DestType << (bool)DestType->getAs<RecordType>();
5690 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
5691 diag::err_init_incomplete_type);
5694 case FK_ListInitializationFailed: {
5695 // Run the init list checker again to emit diagnostics.
5696 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5697 QualType DestType = Entity.getType();
5698 InitListChecker DiagnoseInitList(S, Entity, InitList,
5699 DestType, /*VerifyOnly=*/false,
5700 Kind.getKind() != InitializationKind::IK_DirectList ||
5701 !S.getLangOpts().CPlusPlus0x);
5702 assert(DiagnoseInitList.HadError() &&
5703 "Inconsistent init list check result.");
5707 case FK_PlaceholderType: {
5708 // FIXME: Already diagnosed!
5712 case FK_InitListElementCopyFailure: {
5713 // Try to perform all copies again.
5714 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5715 unsigned NumInits = InitList->getNumInits();
5716 QualType DestType = Entity.getType();
5718 bool Success = S.isStdInitializerList(DestType, &E);
5720 assert(Success && "Where did the std::initializer_list go?");
5721 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5722 S.Context.getConstantArrayType(E,
5723 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5725 ArrayType::Normal, 0));
5726 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
5728 // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
5729 // where the init list type is wrong, e.g.
5730 // std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
5731 // FIXME: Emit a note if we hit the limit?
5733 for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
5734 Element.setElementIndex(i);
5735 ExprResult Init = S.Owned(InitList->getInit(i));
5736 if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
5743 case FK_ExplicitConstructor: {
5744 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
5745 << Args[0]->getSourceRange();
5746 OverloadCandidateSet::iterator Best;
5747 OverloadingResult Ovl
5748 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
5750 assert(Ovl == OR_Success && "Inconsistent overload resolution");
5751 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
5752 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
5757 PrintInitLocationNote(S, Entity);
5761 void InitializationSequence::dump(raw_ostream &OS) const {
5762 switch (SequenceKind) {
5763 case FailedSequence: {
5764 OS << "Failed sequence: ";
5766 case FK_TooManyInitsForReference:
5767 OS << "too many initializers for reference";
5770 case FK_ArrayNeedsInitList:
5771 OS << "array requires initializer list";
5774 case FK_ArrayNeedsInitListOrStringLiteral:
5775 OS << "array requires initializer list or string literal";
5778 case FK_ArrayTypeMismatch:
5779 OS << "array type mismatch";
5782 case FK_NonConstantArrayInit:
5783 OS << "non-constant array initializer";
5786 case FK_AddressOfOverloadFailed:
5787 OS << "address of overloaded function failed";
5790 case FK_ReferenceInitOverloadFailed:
5791 OS << "overload resolution for reference initialization failed";
5794 case FK_NonConstLValueReferenceBindingToTemporary:
5795 OS << "non-const lvalue reference bound to temporary";
5798 case FK_NonConstLValueReferenceBindingToUnrelated:
5799 OS << "non-const lvalue reference bound to unrelated type";
5802 case FK_RValueReferenceBindingToLValue:
5803 OS << "rvalue reference bound to an lvalue";
5806 case FK_ReferenceInitDropsQualifiers:
5807 OS << "reference initialization drops qualifiers";
5810 case FK_ReferenceInitFailed:
5811 OS << "reference initialization failed";
5814 case FK_ConversionFailed:
5815 OS << "conversion failed";
5818 case FK_ConversionFromPropertyFailed:
5819 OS << "conversion from property failed";
5822 case FK_TooManyInitsForScalar:
5823 OS << "too many initializers for scalar";
5826 case FK_ReferenceBindingToInitList:
5827 OS << "referencing binding to initializer list";
5830 case FK_InitListBadDestinationType:
5831 OS << "initializer list for non-aggregate, non-scalar type";
5834 case FK_UserConversionOverloadFailed:
5835 OS << "overloading failed for user-defined conversion";
5838 case FK_ConstructorOverloadFailed:
5839 OS << "constructor overloading failed";
5842 case FK_DefaultInitOfConst:
5843 OS << "default initialization of a const variable";
5847 OS << "initialization of incomplete type";
5850 case FK_ListInitializationFailed:
5851 OS << "list initialization checker failure";
5854 case FK_VariableLengthArrayHasInitializer:
5855 OS << "variable length array has an initializer";
5858 case FK_PlaceholderType:
5859 OS << "initializer expression isn't contextually valid";
5862 case FK_ListConstructorOverloadFailed:
5863 OS << "list constructor overloading failed";
5866 case FK_InitListElementCopyFailure:
5867 OS << "copy construction of initializer list element failed";
5870 case FK_ExplicitConstructor:
5871 OS << "list copy initialization chose explicit constructor";
5878 case DependentSequence:
5879 OS << "Dependent sequence\n";
5882 case NormalSequence:
5883 OS << "Normal sequence: ";
5887 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5888 if (S != step_begin()) {
5893 case SK_ResolveAddressOfOverloadedFunction:
5894 OS << "resolve address of overloaded function";
5897 case SK_CastDerivedToBaseRValue:
5898 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5901 case SK_CastDerivedToBaseXValue:
5902 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5905 case SK_CastDerivedToBaseLValue:
5906 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5909 case SK_BindReference:
5910 OS << "bind reference to lvalue";
5913 case SK_BindReferenceToTemporary:
5914 OS << "bind reference to a temporary";
5917 case SK_ExtraneousCopyToTemporary:
5918 OS << "extraneous C++03 copy to temporary";
5921 case SK_UserConversion:
5922 OS << "user-defined conversion via " << *S->Function.Function;
5925 case SK_QualificationConversionRValue:
5926 OS << "qualification conversion (rvalue)";
5929 case SK_QualificationConversionXValue:
5930 OS << "qualification conversion (xvalue)";
5933 case SK_QualificationConversionLValue:
5934 OS << "qualification conversion (lvalue)";
5937 case SK_ConversionSequence:
5938 OS << "implicit conversion sequence (";
5939 S->ICS->DebugPrint(); // FIXME: use OS
5943 case SK_ListInitialization:
5944 OS << "list aggregate initialization";
5947 case SK_ListConstructorCall:
5948 OS << "list initialization via constructor";
5951 case SK_UnwrapInitList:
5952 OS << "unwrap reference initializer list";
5955 case SK_RewrapInitList:
5956 OS << "rewrap reference initializer list";
5959 case SK_ConstructorInitialization:
5960 OS << "constructor initialization";
5963 case SK_ZeroInitialization:
5964 OS << "zero initialization";
5967 case SK_CAssignment:
5968 OS << "C assignment";
5972 OS << "string initialization";
5975 case SK_ObjCObjectConversion:
5976 OS << "Objective-C object conversion";
5980 OS << "array initialization";
5983 case SK_ParenthesizedArrayInit:
5984 OS << "parenthesized array initialization";
5987 case SK_PassByIndirectCopyRestore:
5988 OS << "pass by indirect copy and restore";
5991 case SK_PassByIndirectRestore:
5992 OS << "pass by indirect restore";
5995 case SK_ProduceObjCObject:
5996 OS << "Objective-C object retension";
5999 case SK_StdInitializerList:
6000 OS << "std::initializer_list from initializer list";
6006 void InitializationSequence::dump() const {
6010 static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
6011 QualType EntityType,
6012 const Expr *PreInit,
6013 const Expr *PostInit) {
6014 if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
6017 // A narrowing conversion can only appear as the final implicit conversion in
6018 // an initialization sequence.
6019 const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
6020 if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
6023 const ImplicitConversionSequence &ICS = *LastStep.ICS;
6024 const StandardConversionSequence *SCS = 0;
6025 switch (ICS.getKind()) {
6026 case ImplicitConversionSequence::StandardConversion:
6027 SCS = &ICS.Standard;
6029 case ImplicitConversionSequence::UserDefinedConversion:
6030 SCS = &ICS.UserDefined.After;
6032 case ImplicitConversionSequence::AmbiguousConversion:
6033 case ImplicitConversionSequence::EllipsisConversion:
6034 case ImplicitConversionSequence::BadConversion:
6038 // Determine the type prior to the narrowing conversion. If a conversion
6039 // operator was used, this may be different from both the type of the entity
6040 // and of the pre-initialization expression.
6041 QualType PreNarrowingType = PreInit->getType();
6042 if (Seq.step_begin() + 1 != Seq.step_end())
6043 PreNarrowingType = Seq.step_end()[-2].Type;
6045 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
6046 APValue ConstantValue;
6047 QualType ConstantType;
6048 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
6050 case NK_Not_Narrowing:
6051 // No narrowing occurred.
6054 case NK_Type_Narrowing:
6055 // This was a floating-to-integer conversion, which is always considered a
6056 // narrowing conversion even if the value is a constant and can be
6057 // represented exactly as an integer.
6058 S.Diag(PostInit->getLocStart(),
6059 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus0x?
6060 diag::warn_init_list_type_narrowing
6061 : S.isSFINAEContext()?
6062 diag::err_init_list_type_narrowing_sfinae
6063 : diag::err_init_list_type_narrowing)
6064 << PostInit->getSourceRange()
6065 << PreNarrowingType.getLocalUnqualifiedType()
6066 << EntityType.getLocalUnqualifiedType();
6069 case NK_Constant_Narrowing:
6070 // A constant value was narrowed.
6071 S.Diag(PostInit->getLocStart(),
6072 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus0x?
6073 diag::warn_init_list_constant_narrowing
6074 : S.isSFINAEContext()?
6075 diag::err_init_list_constant_narrowing_sfinae
6076 : diag::err_init_list_constant_narrowing)
6077 << PostInit->getSourceRange()
6078 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
6079 << EntityType.getLocalUnqualifiedType();
6082 case NK_Variable_Narrowing:
6083 // A variable's value may have been narrowed.
6084 S.Diag(PostInit->getLocStart(),
6085 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus0x?
6086 diag::warn_init_list_variable_narrowing
6087 : S.isSFINAEContext()?
6088 diag::err_init_list_variable_narrowing_sfinae
6089 : diag::err_init_list_variable_narrowing)
6090 << PostInit->getSourceRange()
6091 << PreNarrowingType.getLocalUnqualifiedType()
6092 << EntityType.getLocalUnqualifiedType();
6096 SmallString<128> StaticCast;
6097 llvm::raw_svector_ostream OS(StaticCast);
6098 OS << "static_cast<";
6099 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
6100 // It's important to use the typedef's name if there is one so that the
6101 // fixit doesn't break code using types like int64_t.
6103 // FIXME: This will break if the typedef requires qualification. But
6104 // getQualifiedNameAsString() includes non-machine-parsable components.
6105 OS << *TT->getDecl();
6106 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
6107 OS << BT->getName(S.getLangOpts());
6109 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
6110 // with a broken cast.
6114 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
6115 << PostInit->getSourceRange()
6116 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
6117 << FixItHint::CreateInsertion(
6118 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
6121 //===----------------------------------------------------------------------===//
6122 // Initialization helper functions
6123 //===----------------------------------------------------------------------===//
6125 Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
6127 if (Init.isInvalid())
6130 Expr *InitE = Init.get();
6131 assert(InitE && "No initialization expression");
6133 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
6135 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
6136 return !Seq.Failed();
6140 Sema::PerformCopyInitialization(const InitializedEntity &Entity,
6141 SourceLocation EqualLoc,
6143 bool TopLevelOfInitList,
6144 bool AllowExplicit) {
6145 if (Init.isInvalid())
6148 Expr *InitE = Init.get();
6149 assert(InitE && "No initialization expression?");
6151 if (EqualLoc.isInvalid())
6152 EqualLoc = InitE->getLocStart();
6154 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
6157 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
6160 ExprResult Result = Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
6162 if (!Result.isInvalid() && TopLevelOfInitList)
6163 DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
6164 InitE, Result.get());