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/Initialization.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/ExprCXX.h"
18 #include "clang/AST/ExprObjC.h"
19 #include "clang/AST/TypeLoc.h"
20 #include "clang/Lex/Preprocessor.h"
21 #include "clang/Sema/Designator.h"
22 #include "clang/Sema/Lookup.h"
23 #include "clang/Sema/SemaInternal.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 /// Update the type of a string literal, including any surrounding parentheses,
86 /// to match the type of the object which it is initializing.
87 static void updateStringLiteralType(Expr *E, QualType Ty) {
90 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
92 else if (ParenExpr *PE = dyn_cast<ParenExpr>(E))
94 else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
96 else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E))
97 E = GSE->getResultExpr();
99 llvm_unreachable("unexpected expr in string literal init");
103 static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
105 // Get the length of the string as parsed.
107 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
110 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
111 // C99 6.7.8p14. We have an array of character type with unknown size
112 // being initialized to a string literal.
113 llvm::APInt ConstVal(32, StrLength);
114 // Return a new array type (C99 6.7.8p22).
115 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
117 ArrayType::Normal, 0);
118 updateStringLiteralType(Str, DeclT);
122 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
124 // We have an array of character type with known size. However,
125 // the size may be smaller or larger than the string we are initializing.
126 // FIXME: Avoid truncation for 64-bit length strings.
127 if (S.getLangOpts().CPlusPlus) {
128 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
129 // For Pascal strings it's OK to strip off the terminating null character,
130 // so the example below is valid:
132 // unsigned char a[2] = "\pa";
137 // [dcl.init.string]p2
138 if (StrLength > CAT->getSize().getZExtValue())
139 S.Diag(Str->getLocStart(),
140 diag::err_initializer_string_for_char_array_too_long)
141 << Str->getSourceRange();
144 if (StrLength-1 > CAT->getSize().getZExtValue())
145 S.Diag(Str->getLocStart(),
146 diag::warn_initializer_string_for_char_array_too_long)
147 << Str->getSourceRange();
150 // Set the type to the actual size that we are initializing. If we have
152 // char x[1] = "foo";
153 // then this will set the string literal's type to char[1].
154 updateStringLiteralType(Str, DeclT);
157 //===----------------------------------------------------------------------===//
158 // Semantic checking for initializer lists.
159 //===----------------------------------------------------------------------===//
161 /// @brief Semantic checking for initializer lists.
163 /// The InitListChecker class contains a set of routines that each
164 /// handle the initialization of a certain kind of entity, e.g.,
165 /// arrays, vectors, struct/union types, scalars, etc. The
166 /// InitListChecker itself performs a recursive walk of the subobject
167 /// structure of the type to be initialized, while stepping through
168 /// the initializer list one element at a time. The IList and Index
169 /// parameters to each of the Check* routines contain the active
170 /// (syntactic) initializer list and the index into that initializer
171 /// list that represents the current initializer. Each routine is
172 /// responsible for moving that Index forward as it consumes elements.
174 /// Each Check* routine also has a StructuredList/StructuredIndex
175 /// arguments, which contains the current "structured" (semantic)
176 /// initializer list and the index into that initializer list where we
177 /// are copying initializers as we map them over to the semantic
178 /// list. Once we have completed our recursive walk of the subobject
179 /// structure, we will have constructed a full semantic initializer
182 /// C99 designators cause changes in the initializer list traversal,
183 /// because they make the initialization "jump" into a specific
184 /// subobject and then continue the initialization from that
185 /// point. CheckDesignatedInitializer() recursively steps into the
186 /// designated subobject and manages backing out the recursion to
187 /// initialize the subobjects after the one designated.
189 class InitListChecker {
192 bool VerifyOnly; // no diagnostics, no structure building
193 bool AllowBraceElision;
194 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
195 InitListExpr *FullyStructuredList;
197 void CheckImplicitInitList(const InitializedEntity &Entity,
198 InitListExpr *ParentIList, QualType T,
199 unsigned &Index, InitListExpr *StructuredList,
200 unsigned &StructuredIndex);
201 void CheckExplicitInitList(const InitializedEntity &Entity,
202 InitListExpr *IList, QualType &T,
203 unsigned &Index, InitListExpr *StructuredList,
204 unsigned &StructuredIndex,
205 bool TopLevelObject = false);
206 void CheckListElementTypes(const InitializedEntity &Entity,
207 InitListExpr *IList, QualType &DeclType,
208 bool SubobjectIsDesignatorContext,
210 InitListExpr *StructuredList,
211 unsigned &StructuredIndex,
212 bool TopLevelObject = false);
213 void CheckSubElementType(const InitializedEntity &Entity,
214 InitListExpr *IList, QualType ElemType,
216 InitListExpr *StructuredList,
217 unsigned &StructuredIndex);
218 void CheckComplexType(const InitializedEntity &Entity,
219 InitListExpr *IList, QualType DeclType,
221 InitListExpr *StructuredList,
222 unsigned &StructuredIndex);
223 void CheckScalarType(const InitializedEntity &Entity,
224 InitListExpr *IList, QualType DeclType,
226 InitListExpr *StructuredList,
227 unsigned &StructuredIndex);
228 void CheckReferenceType(const InitializedEntity &Entity,
229 InitListExpr *IList, QualType DeclType,
231 InitListExpr *StructuredList,
232 unsigned &StructuredIndex);
233 void CheckVectorType(const InitializedEntity &Entity,
234 InitListExpr *IList, QualType DeclType, unsigned &Index,
235 InitListExpr *StructuredList,
236 unsigned &StructuredIndex);
237 void CheckStructUnionTypes(const InitializedEntity &Entity,
238 InitListExpr *IList, QualType DeclType,
239 RecordDecl::field_iterator Field,
240 bool SubobjectIsDesignatorContext, unsigned &Index,
241 InitListExpr *StructuredList,
242 unsigned &StructuredIndex,
243 bool TopLevelObject = false);
244 void CheckArrayType(const InitializedEntity &Entity,
245 InitListExpr *IList, QualType &DeclType,
246 llvm::APSInt elementIndex,
247 bool SubobjectIsDesignatorContext, unsigned &Index,
248 InitListExpr *StructuredList,
249 unsigned &StructuredIndex);
250 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
251 InitListExpr *IList, DesignatedInitExpr *DIE,
253 QualType &CurrentObjectType,
254 RecordDecl::field_iterator *NextField,
255 llvm::APSInt *NextElementIndex,
257 InitListExpr *StructuredList,
258 unsigned &StructuredIndex,
259 bool FinishSubobjectInit,
260 bool TopLevelObject);
261 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
262 QualType CurrentObjectType,
263 InitListExpr *StructuredList,
264 unsigned StructuredIndex,
265 SourceRange InitRange);
266 void UpdateStructuredListElement(InitListExpr *StructuredList,
267 unsigned &StructuredIndex,
269 int numArrayElements(QualType DeclType);
270 int numStructUnionElements(QualType DeclType);
272 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
273 const InitializedEntity &ParentEntity,
274 InitListExpr *ILE, bool &RequiresSecondPass);
275 void FillInValueInitializations(const InitializedEntity &Entity,
276 InitListExpr *ILE, bool &RequiresSecondPass);
277 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
278 Expr *InitExpr, FieldDecl *Field,
279 bool TopLevelObject);
280 void CheckValueInitializable(const InitializedEntity &Entity);
283 InitListChecker(Sema &S, const InitializedEntity &Entity,
284 InitListExpr *IL, QualType &T, bool VerifyOnly,
285 bool AllowBraceElision);
286 bool HadError() { return hadError; }
288 // @brief Retrieves the fully-structured initializer list used for
289 // semantic analysis and code generation.
290 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
292 } // end anonymous namespace
294 void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
296 "CheckValueInitializable is only inteded for verification mode.");
299 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
301 InitializationSequence InitSeq(SemaRef, Entity, Kind, None);
302 if (InitSeq.Failed())
306 void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
307 const InitializedEntity &ParentEntity,
309 bool &RequiresSecondPass) {
310 SourceLocation Loc = ILE->getLocStart();
311 unsigned NumInits = ILE->getNumInits();
312 InitializedEntity MemberEntity
313 = InitializedEntity::InitializeMember(Field, &ParentEntity);
314 if (Init >= NumInits || !ILE->getInit(Init)) {
315 // If there's no explicit initializer but we have a default initializer, use
316 // that. This only happens in C++1y, since classes with default
317 // initializers are not aggregates in C++11.
318 if (Field->hasInClassInitializer()) {
319 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
320 ILE->getRBraceLoc(), Field);
322 ILE->setInit(Init, DIE);
324 ILE->updateInit(SemaRef.Context, Init, DIE);
325 RequiresSecondPass = true;
330 // FIXME: We probably don't need to handle references
331 // specially here, since value-initialization of references is
332 // handled in InitializationSequence.
333 if (Field->getType()->isReferenceType()) {
334 // C++ [dcl.init.aggr]p9:
335 // If an incomplete or empty initializer-list leaves a
336 // member of reference type uninitialized, the program is
338 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
340 << ILE->getSyntacticForm()->getSourceRange();
341 SemaRef.Diag(Field->getLocation(),
342 diag::note_uninit_reference_member);
347 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
349 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, None);
351 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, None);
356 ExprResult MemberInit
357 = InitSeq.Perform(SemaRef, MemberEntity, Kind, None);
358 if (MemberInit.isInvalid()) {
365 } else if (Init < NumInits) {
366 ILE->setInit(Init, MemberInit.takeAs<Expr>());
367 } else if (InitSeq.isConstructorInitialization()) {
368 // Value-initialization requires a constructor call, so
369 // extend the initializer list to include the constructor
370 // call and make a note that we'll need to take another pass
371 // through the initializer list.
372 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
373 RequiresSecondPass = true;
375 } else if (InitListExpr *InnerILE
376 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
377 FillInValueInitializations(MemberEntity, InnerILE,
381 /// Recursively replaces NULL values within the given initializer list
382 /// with expressions that perform value-initialization of the
383 /// appropriate type.
385 InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
387 bool &RequiresSecondPass) {
388 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
389 "Should not have void type");
390 SourceLocation Loc = ILE->getLocStart();
391 if (ILE->getSyntacticForm())
392 Loc = ILE->getSyntacticForm()->getLocStart();
394 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
395 const RecordDecl *RDecl = RType->getDecl();
396 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
397 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
398 Entity, ILE, RequiresSecondPass);
399 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
400 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
401 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
402 FieldEnd = RDecl->field_end();
403 Field != FieldEnd; ++Field) {
404 if (Field->hasInClassInitializer()) {
405 FillInValueInitForField(0, *Field, Entity, ILE, RequiresSecondPass);
411 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
412 FieldEnd = RDecl->field_end();
413 Field != FieldEnd; ++Field) {
414 if (Field->isUnnamedBitfield())
420 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
426 // Only look at the first initialization of a union.
427 if (RDecl->isUnion())
435 QualType ElementType;
437 InitializedEntity ElementEntity = Entity;
438 unsigned NumInits = ILE->getNumInits();
439 unsigned NumElements = NumInits;
440 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
441 ElementType = AType->getElementType();
442 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
443 NumElements = CAType->getSize().getZExtValue();
444 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
446 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
447 ElementType = VType->getElementType();
448 NumElements = VType->getNumElements();
449 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
452 ElementType = ILE->getType();
455 for (unsigned Init = 0; Init != NumElements; ++Init) {
459 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
460 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
461 ElementEntity.setElementIndex(Init);
463 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
464 if (!InitExpr && !ILE->hasArrayFiller()) {
465 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
467 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, None);
469 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, None);
474 ExprResult ElementInit
475 = InitSeq.Perform(SemaRef, ElementEntity, Kind, None);
476 if (ElementInit.isInvalid()) {
483 } else if (Init < NumInits) {
484 // For arrays, just set the expression used for value-initialization
485 // of the "holes" in the array.
486 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
487 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
489 ILE->setInit(Init, ElementInit.takeAs<Expr>());
491 // For arrays, just set the expression used for value-initialization
492 // of the rest of elements and exit.
493 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
494 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
498 if (InitSeq.isConstructorInitialization()) {
499 // Value-initialization requires a constructor call, so
500 // extend the initializer list to include the constructor
501 // call and make a note that we'll need to take another pass
502 // through the initializer list.
503 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
504 RequiresSecondPass = true;
507 } else if (InitListExpr *InnerILE
508 = dyn_cast_or_null<InitListExpr>(InitExpr))
509 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
514 InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
515 InitListExpr *IL, QualType &T,
516 bool VerifyOnly, bool AllowBraceElision)
517 : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
520 unsigned newIndex = 0;
521 unsigned newStructuredIndex = 0;
523 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
524 CheckExplicitInitList(Entity, IL, T, newIndex,
525 FullyStructuredList, newStructuredIndex,
526 /*TopLevelObject=*/true);
528 if (!hadError && !VerifyOnly) {
529 bool RequiresSecondPass = false;
530 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
531 if (RequiresSecondPass && !hadError)
532 FillInValueInitializations(Entity, FullyStructuredList,
537 int InitListChecker::numArrayElements(QualType DeclType) {
538 // FIXME: use a proper constant
539 int maxElements = 0x7FFFFFFF;
540 if (const ConstantArrayType *CAT =
541 SemaRef.Context.getAsConstantArrayType(DeclType)) {
542 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
547 int InitListChecker::numStructUnionElements(QualType DeclType) {
548 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
549 int InitializableMembers = 0;
550 for (RecordDecl::field_iterator
551 Field = structDecl->field_begin(),
552 FieldEnd = structDecl->field_end();
553 Field != FieldEnd; ++Field) {
554 if (!Field->isUnnamedBitfield())
555 ++InitializableMembers;
557 if (structDecl->isUnion())
558 return std::min(InitializableMembers, 1);
559 return InitializableMembers - structDecl->hasFlexibleArrayMember();
562 void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
563 InitListExpr *ParentIList,
564 QualType T, unsigned &Index,
565 InitListExpr *StructuredList,
566 unsigned &StructuredIndex) {
569 if (T->isArrayType())
570 maxElements = numArrayElements(T);
571 else if (T->isRecordType())
572 maxElements = numStructUnionElements(T);
573 else if (T->isVectorType())
574 maxElements = T->getAs<VectorType>()->getNumElements();
576 llvm_unreachable("CheckImplicitInitList(): Illegal type");
578 if (maxElements == 0) {
580 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
581 diag::err_implicit_empty_initializer);
587 // Build a structured initializer list corresponding to this subobject.
588 InitListExpr *StructuredSubobjectInitList
589 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
591 SourceRange(ParentIList->getInit(Index)->getLocStart(),
592 ParentIList->getSourceRange().getEnd()));
593 unsigned StructuredSubobjectInitIndex = 0;
595 // Check the element types and build the structural subobject.
596 unsigned StartIndex = Index;
597 CheckListElementTypes(Entity, ParentIList, T,
598 /*SubobjectIsDesignatorContext=*/false, Index,
599 StructuredSubobjectInitList,
600 StructuredSubobjectInitIndex);
603 if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
606 StructuredSubobjectInitList->setType(T);
608 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
609 // Update the structured sub-object initializer so that it's ending
610 // range corresponds with the end of the last initializer it used.
611 if (EndIndex < ParentIList->getNumInits()) {
612 SourceLocation EndLoc
613 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
614 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
617 // Complain about missing braces.
618 if (T->isArrayType() || T->isRecordType()) {
619 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
620 AllowBraceElision ? diag::warn_missing_braces :
621 diag::err_missing_braces)
622 << StructuredSubobjectInitList->getSourceRange()
623 << FixItHint::CreateInsertion(
624 StructuredSubobjectInitList->getLocStart(), "{")
625 << FixItHint::CreateInsertion(
626 SemaRef.PP.getLocForEndOfToken(
627 StructuredSubobjectInitList->getLocEnd()),
629 if (!AllowBraceElision)
635 void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
636 InitListExpr *IList, QualType &T,
638 InitListExpr *StructuredList,
639 unsigned &StructuredIndex,
640 bool TopLevelObject) {
641 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
643 SyntacticToSemantic[IList] = StructuredList;
644 StructuredList->setSyntacticForm(IList);
646 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
647 Index, StructuredList, StructuredIndex, TopLevelObject);
650 if (!ExprTy->isArrayType())
651 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
652 IList->setType(ExprTy);
653 StructuredList->setType(ExprTy);
658 if (Index < IList->getNumInits()) {
659 // We have leftover initializers
661 if (SemaRef.getLangOpts().CPlusPlus ||
662 (SemaRef.getLangOpts().OpenCL &&
663 IList->getType()->isVectorType())) {
669 if (StructuredIndex == 1 &&
670 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
671 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
672 if (SemaRef.getLangOpts().CPlusPlus) {
673 DK = diag::err_excess_initializers_in_char_array_initializer;
677 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
678 << IList->getInit(Index)->getSourceRange();
679 } else if (!T->isIncompleteType()) {
680 // Don't complain for incomplete types, since we'll get an error
682 QualType CurrentObjectType = StructuredList->getType();
684 CurrentObjectType->isArrayType()? 0 :
685 CurrentObjectType->isVectorType()? 1 :
686 CurrentObjectType->isScalarType()? 2 :
687 CurrentObjectType->isUnionType()? 3 :
690 unsigned DK = diag::warn_excess_initializers;
691 if (SemaRef.getLangOpts().CPlusPlus) {
692 DK = diag::err_excess_initializers;
695 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
696 DK = diag::err_excess_initializers;
700 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
701 << initKind << IList->getInit(Index)->getSourceRange();
705 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
707 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
708 << IList->getSourceRange()
709 << FixItHint::CreateRemoval(IList->getLocStart())
710 << FixItHint::CreateRemoval(IList->getLocEnd());
713 void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
716 bool SubobjectIsDesignatorContext,
718 InitListExpr *StructuredList,
719 unsigned &StructuredIndex,
720 bool TopLevelObject) {
721 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
722 // Explicitly braced initializer for complex type can be real+imaginary
724 CheckComplexType(Entity, IList, DeclType, Index,
725 StructuredList, StructuredIndex);
726 } else if (DeclType->isScalarType()) {
727 CheckScalarType(Entity, IList, DeclType, Index,
728 StructuredList, StructuredIndex);
729 } else if (DeclType->isVectorType()) {
730 CheckVectorType(Entity, IList, DeclType, Index,
731 StructuredList, StructuredIndex);
732 } else if (DeclType->isRecordType()) {
733 assert(DeclType->isAggregateType() &&
734 "non-aggregate records should be handed in CheckSubElementType");
735 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
736 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
737 SubobjectIsDesignatorContext, Index,
738 StructuredList, StructuredIndex,
740 } else if (DeclType->isArrayType()) {
742 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
744 CheckArrayType(Entity, IList, DeclType, Zero,
745 SubobjectIsDesignatorContext, Index,
746 StructuredList, StructuredIndex);
747 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
748 // This type is invalid, issue a diagnostic.
751 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
754 } else if (DeclType->isReferenceType()) {
755 CheckReferenceType(Entity, IList, DeclType, Index,
756 StructuredList, StructuredIndex);
757 } else if (DeclType->isObjCObjectType()) {
759 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
764 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
770 void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
774 InitListExpr *StructuredList,
775 unsigned &StructuredIndex) {
776 Expr *expr = IList->getInit(Index);
778 if (ElemType->isReferenceType())
779 return CheckReferenceType(Entity, IList, ElemType, Index,
780 StructuredList, StructuredIndex);
782 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
783 if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
784 unsigned newIndex = 0;
785 unsigned newStructuredIndex = 0;
786 InitListExpr *newStructuredList
787 = getStructuredSubobjectInit(IList, Index, ElemType,
788 StructuredList, StructuredIndex,
789 SubInitList->getSourceRange());
790 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
791 newStructuredList, newStructuredIndex);
796 assert(SemaRef.getLangOpts().CPlusPlus &&
797 "non-aggregate records are only possible in C++");
798 // C++ initialization is handled later.
801 // FIXME: Need to handle atomic aggregate types with implicit init lists.
802 if (ElemType->isScalarType() || ElemType->isAtomicType())
803 return CheckScalarType(Entity, IList, ElemType, Index,
804 StructuredList, StructuredIndex);
806 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
807 ElemType->isArrayType()) && "Unexpected type");
809 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
810 // arrayType can be incomplete if we're initializing a flexible
811 // array member. There's nothing we can do with the completed
812 // type here, though.
814 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
816 CheckStringInit(Str, ElemType, arrayType, SemaRef);
817 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
823 // Fall through for subaggregate initialization.
825 } else if (SemaRef.getLangOpts().CPlusPlus) {
826 // C++ [dcl.init.aggr]p12:
827 // All implicit type conversions (clause 4) are considered when
828 // initializing the aggregate member with an initializer from
829 // an initializer-list. If the initializer can initialize a
830 // member, the member is initialized. [...]
832 // FIXME: Better EqualLoc?
833 InitializationKind Kind =
834 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
835 InitializationSequence Seq(SemaRef, Entity, Kind, expr);
840 Seq.Perform(SemaRef, Entity, Kind, expr);
841 if (Result.isInvalid())
844 UpdateStructuredListElement(StructuredList, StructuredIndex,
845 Result.takeAs<Expr>());
851 // Fall through for subaggregate initialization
855 // The initializer for a structure or union object that has
856 // automatic storage duration shall be either an initializer
857 // list as described below, or a single expression that has
858 // compatible structure or union type. In the latter case, the
859 // initial value of the object, including unnamed members, is
860 // that of the expression.
861 ExprResult ExprRes = SemaRef.Owned(expr);
862 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
863 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
865 == Sema::Compatible) {
866 if (ExprRes.isInvalid())
869 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
870 if (ExprRes.isInvalid())
873 UpdateStructuredListElement(StructuredList, StructuredIndex,
874 ExprRes.takeAs<Expr>());
879 // Fall through for subaggregate initialization
882 // C++ [dcl.init.aggr]p12:
884 // [...] Otherwise, if the member is itself a non-empty
885 // subaggregate, brace elision is assumed and the initializer is
886 // considered for the initialization of the first member of
888 if (!SemaRef.getLangOpts().OpenCL &&
889 (ElemType->isAggregateType() || ElemType->isVectorType())) {
890 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
895 // We cannot initialize this element, so let
896 // PerformCopyInitialization produce the appropriate diagnostic.
897 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
899 /*TopLevelOfInitList=*/true);
907 void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
908 InitListExpr *IList, QualType DeclType,
910 InitListExpr *StructuredList,
911 unsigned &StructuredIndex) {
912 assert(Index == 0 && "Index in explicit init list must be zero");
914 // As an extension, clang supports complex initializers, which initialize
915 // a complex number component-wise. When an explicit initializer list for
916 // a complex number contains two two initializers, this extension kicks in:
917 // it exepcts the initializer list to contain two elements convertible to
918 // the element type of the complex type. The first element initializes
919 // the real part, and the second element intitializes the imaginary part.
921 if (IList->getNumInits() != 2)
922 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
925 // This is an extension in C. (The builtin _Complex type does not exist
926 // in the C++ standard.)
927 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
928 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
929 << IList->getSourceRange();
931 // Initialize the complex number.
932 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
933 InitializedEntity ElementEntity =
934 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
936 for (unsigned i = 0; i < 2; ++i) {
937 ElementEntity.setElementIndex(Index);
938 CheckSubElementType(ElementEntity, IList, elementType, Index,
939 StructuredList, StructuredIndex);
944 void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
945 InitListExpr *IList, QualType DeclType,
947 InitListExpr *StructuredList,
948 unsigned &StructuredIndex) {
949 if (Index >= IList->getNumInits()) {
951 SemaRef.Diag(IList->getLocStart(),
952 SemaRef.getLangOpts().CPlusPlus11 ?
953 diag::warn_cxx98_compat_empty_scalar_initializer :
954 diag::err_empty_scalar_initializer)
955 << IList->getSourceRange();
956 hadError = !SemaRef.getLangOpts().CPlusPlus11;
962 Expr *expr = IList->getInit(Index);
963 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
965 SemaRef.Diag(SubIList->getLocStart(),
966 diag::warn_many_braces_around_scalar_init)
967 << SubIList->getSourceRange();
969 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
972 } else if (isa<DesignatedInitExpr>(expr)) {
974 SemaRef.Diag(expr->getLocStart(),
975 diag::err_designator_for_scalar_init)
976 << DeclType << expr->getSourceRange();
984 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
991 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
993 /*TopLevelOfInitList=*/true);
995 Expr *ResultExpr = 0;
997 if (Result.isInvalid())
998 hadError = true; // types weren't compatible.
1000 ResultExpr = Result.takeAs<Expr>();
1002 if (ResultExpr != expr) {
1003 // The type was promoted, update initializer list.
1004 IList->setInit(Index, ResultExpr);
1010 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1014 void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1015 InitListExpr *IList, QualType DeclType,
1017 InitListExpr *StructuredList,
1018 unsigned &StructuredIndex) {
1019 if (Index >= IList->getNumInits()) {
1020 // FIXME: It would be wonderful if we could point at the actual member. In
1021 // general, it would be useful to pass location information down the stack,
1022 // so that we know the location (or decl) of the "current object" being
1025 SemaRef.Diag(IList->getLocStart(),
1026 diag::err_init_reference_member_uninitialized)
1028 << IList->getSourceRange();
1035 Expr *expr = IList->getInit(Index);
1036 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1038 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1039 << DeclType << IList->getSourceRange();
1047 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1054 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1055 SemaRef.Owned(expr),
1056 /*TopLevelOfInitList=*/true);
1058 if (Result.isInvalid())
1061 expr = Result.takeAs<Expr>();
1062 IList->setInit(Index, expr);
1067 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1071 void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1072 InitListExpr *IList, QualType DeclType,
1074 InitListExpr *StructuredList,
1075 unsigned &StructuredIndex) {
1076 const VectorType *VT = DeclType->getAs<VectorType>();
1077 unsigned maxElements = VT->getNumElements();
1078 unsigned numEltsInit = 0;
1079 QualType elementType = VT->getElementType();
1081 if (Index >= IList->getNumInits()) {
1082 // Make sure the element type can be value-initialized.
1084 CheckValueInitializable(
1085 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1089 if (!SemaRef.getLangOpts().OpenCL) {
1090 // If the initializing element is a vector, try to copy-initialize
1091 // instead of breaking it apart (which is doomed to failure anyway).
1092 Expr *Init = IList->getInit(Index);
1093 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1095 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1102 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
1103 SemaRef.Owned(Init),
1104 /*TopLevelOfInitList=*/true);
1106 Expr *ResultExpr = 0;
1107 if (Result.isInvalid())
1108 hadError = true; // types weren't compatible.
1110 ResultExpr = Result.takeAs<Expr>();
1112 if (ResultExpr != Init) {
1113 // The type was promoted, update initializer list.
1114 IList->setInit(Index, ResultExpr);
1120 UpdateStructuredListElement(StructuredList, StructuredIndex,
1126 InitializedEntity ElementEntity =
1127 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1129 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1130 // Don't attempt to go past the end of the init list
1131 if (Index >= IList->getNumInits()) {
1133 CheckValueInitializable(ElementEntity);
1137 ElementEntity.setElementIndex(Index);
1138 CheckSubElementType(ElementEntity, IList, elementType, Index,
1139 StructuredList, StructuredIndex);
1144 InitializedEntity ElementEntity =
1145 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1147 // OpenCL initializers allows vectors to be constructed from vectors.
1148 for (unsigned i = 0; i < maxElements; ++i) {
1149 // Don't attempt to go past the end of the init list
1150 if (Index >= IList->getNumInits())
1153 ElementEntity.setElementIndex(Index);
1155 QualType IType = IList->getInit(Index)->getType();
1156 if (!IType->isVectorType()) {
1157 CheckSubElementType(ElementEntity, IList, elementType, Index,
1158 StructuredList, StructuredIndex);
1162 const VectorType *IVT = IType->getAs<VectorType>();
1163 unsigned numIElts = IVT->getNumElements();
1165 if (IType->isExtVectorType())
1166 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1168 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1169 IVT->getVectorKind());
1170 CheckSubElementType(ElementEntity, IList, VecType, Index,
1171 StructuredList, StructuredIndex);
1172 numEltsInit += numIElts;
1176 // OpenCL requires all elements to be initialized.
1177 if (numEltsInit != maxElements) {
1179 SemaRef.Diag(IList->getLocStart(),
1180 diag::err_vector_incorrect_num_initializers)
1181 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1186 void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1187 InitListExpr *IList, QualType &DeclType,
1188 llvm::APSInt elementIndex,
1189 bool SubobjectIsDesignatorContext,
1191 InitListExpr *StructuredList,
1192 unsigned &StructuredIndex) {
1193 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1195 // Check for the special-case of initializing an array with a string.
1196 if (Index < IList->getNumInits()) {
1197 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
1199 // We place the string literal directly into the resulting
1200 // initializer list. This is the only place where the structure
1201 // of the structured initializer list doesn't match exactly,
1202 // because doing so would involve allocating one character
1203 // constant for each string.
1205 CheckStringInit(Str, DeclType, arrayType, SemaRef);
1206 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1207 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1213 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1214 // Check for VLAs; in standard C it would be possible to check this
1215 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1216 // them in all sorts of strange places).
1218 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1219 diag::err_variable_object_no_init)
1220 << VAT->getSizeExpr()->getSourceRange();
1227 // We might know the maximum number of elements in advance.
1228 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1229 elementIndex.isUnsigned());
1230 bool maxElementsKnown = false;
1231 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
1232 maxElements = CAT->getSize();
1233 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
1234 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1235 maxElementsKnown = true;
1238 QualType elementType = arrayType->getElementType();
1239 while (Index < IList->getNumInits()) {
1240 Expr *Init = IList->getInit(Index);
1241 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1242 // If we're not the subobject that matches up with the '{' for
1243 // the designator, we shouldn't be handling the
1244 // designator. Return immediately.
1245 if (!SubobjectIsDesignatorContext)
1248 // Handle this designated initializer. elementIndex will be
1249 // updated to be the next array element we'll initialize.
1250 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1251 DeclType, 0, &elementIndex, Index,
1252 StructuredList, StructuredIndex, true,
1258 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1259 maxElements = maxElements.extend(elementIndex.getBitWidth());
1260 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1261 elementIndex = elementIndex.extend(maxElements.getBitWidth());
1262 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1264 // If the array is of incomplete type, keep track of the number of
1265 // elements in the initializer.
1266 if (!maxElementsKnown && elementIndex > maxElements)
1267 maxElements = elementIndex;
1272 // If we know the maximum number of elements, and we've already
1273 // hit it, stop consuming elements in the initializer list.
1274 if (maxElementsKnown && elementIndex == maxElements)
1277 InitializedEntity ElementEntity =
1278 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1280 // Check this element.
1281 CheckSubElementType(ElementEntity, IList, elementType, Index,
1282 StructuredList, StructuredIndex);
1285 // If the array is of incomplete type, keep track of the number of
1286 // elements in the initializer.
1287 if (!maxElementsKnown && elementIndex > maxElements)
1288 maxElements = elementIndex;
1290 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
1291 // If this is an incomplete array type, the actual type needs to
1292 // be calculated here.
1293 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
1294 if (maxElements == Zero) {
1295 // Sizing an array implicitly to zero is not allowed by ISO C,
1296 // but is supported by GNU.
1297 SemaRef.Diag(IList->getLocStart(),
1298 diag::ext_typecheck_zero_array_size);
1301 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
1302 ArrayType::Normal, 0);
1304 if (!hadError && VerifyOnly) {
1305 // Check if there are any members of the array that get value-initialized.
1306 // If so, check if doing that is possible.
1307 // FIXME: This needs to detect holes left by designated initializers too.
1308 if (maxElementsKnown && elementIndex < maxElements)
1309 CheckValueInitializable(InitializedEntity::InitializeElement(
1310 SemaRef.Context, 0, Entity));
1314 bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1317 bool TopLevelObject) {
1318 // Handle GNU flexible array initializers.
1319 unsigned FlexArrayDiag;
1320 if (isa<InitListExpr>(InitExpr) &&
1321 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1322 // Empty flexible array init always allowed as an extension
1323 FlexArrayDiag = diag::ext_flexible_array_init;
1324 } else if (SemaRef.getLangOpts().CPlusPlus) {
1325 // Disallow flexible array init in C++; it is not required for gcc
1326 // compatibility, and it needs work to IRGen correctly in general.
1327 FlexArrayDiag = diag::err_flexible_array_init;
1328 } else if (!TopLevelObject) {
1329 // Disallow flexible array init on non-top-level object
1330 FlexArrayDiag = diag::err_flexible_array_init;
1331 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1332 // Disallow flexible array init on anything which is not a variable.
1333 FlexArrayDiag = diag::err_flexible_array_init;
1334 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1335 // Disallow flexible array init on local variables.
1336 FlexArrayDiag = diag::err_flexible_array_init;
1338 // Allow other cases.
1339 FlexArrayDiag = diag::ext_flexible_array_init;
1343 SemaRef.Diag(InitExpr->getLocStart(),
1345 << InitExpr->getLocStart();
1346 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1350 return FlexArrayDiag != diag::ext_flexible_array_init;
1353 void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
1354 InitListExpr *IList,
1356 RecordDecl::field_iterator Field,
1357 bool SubobjectIsDesignatorContext,
1359 InitListExpr *StructuredList,
1360 unsigned &StructuredIndex,
1361 bool TopLevelObject) {
1362 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
1364 // If the record is invalid, some of it's members are invalid. To avoid
1365 // confusion, we forgo checking the intializer for the entire record.
1366 if (structDecl->isInvalidDecl()) {
1367 // Assume it was supposed to consume a single initializer.
1373 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1374 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1376 // If there's a default initializer, use it.
1377 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1380 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1381 Field != FieldEnd; ++Field) {
1382 if (Field->hasInClassInitializer()) {
1383 StructuredList->setInitializedFieldInUnion(*Field);
1384 // FIXME: Actually build a CXXDefaultInitExpr?
1390 // Value-initialize the first named member of the union.
1391 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1392 Field != FieldEnd; ++Field) {
1393 if (Field->getDeclName()) {
1395 CheckValueInitializable(
1396 InitializedEntity::InitializeMember(*Field, &Entity));
1398 StructuredList->setInitializedFieldInUnion(*Field);
1405 // If structDecl is a forward declaration, this loop won't do
1406 // anything except look at designated initializers; That's okay,
1407 // because an error should get printed out elsewhere. It might be
1408 // worthwhile to skip over the rest of the initializer, though.
1409 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1410 RecordDecl::field_iterator FieldEnd = RD->field_end();
1411 bool InitializedSomething = false;
1412 bool CheckForMissingFields = true;
1413 while (Index < IList->getNumInits()) {
1414 Expr *Init = IList->getInit(Index);
1416 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1417 // If we're not the subobject that matches up with the '{' for
1418 // the designator, we shouldn't be handling the
1419 // designator. Return immediately.
1420 if (!SubobjectIsDesignatorContext)
1423 // Handle this designated initializer. Field will be updated to
1424 // the next field that we'll be initializing.
1425 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1426 DeclType, &Field, 0, Index,
1427 StructuredList, StructuredIndex,
1428 true, TopLevelObject))
1431 InitializedSomething = true;
1433 // Disable check for missing fields when designators are used.
1434 // This matches gcc behaviour.
1435 CheckForMissingFields = false;
1439 if (Field == FieldEnd) {
1440 // We've run out of fields. We're done.
1444 // We've already initialized a member of a union. We're done.
1445 if (InitializedSomething && DeclType->isUnionType())
1448 // If we've hit the flexible array member at the end, we're done.
1449 if (Field->getType()->isIncompleteArrayType())
1452 if (Field->isUnnamedBitfield()) {
1453 // Don't initialize unnamed bitfields, e.g. "int : 20;"
1458 // Make sure we can use this declaration.
1461 InvalidUse = !SemaRef.CanUseDecl(*Field);
1463 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1464 IList->getInit(Index)->getLocStart());
1472 InitializedEntity MemberEntity =
1473 InitializedEntity::InitializeMember(*Field, &Entity);
1474 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1475 StructuredList, StructuredIndex);
1476 InitializedSomething = true;
1478 if (DeclType->isUnionType() && !VerifyOnly) {
1479 // Initialize the first field within the union.
1480 StructuredList->setInitializedFieldInUnion(*Field);
1486 // Emit warnings for missing struct field initializers.
1487 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1488 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1489 !DeclType->isUnionType()) {
1490 // It is possible we have one or more unnamed bitfields remaining.
1491 // Find first (if any) named field and emit warning.
1492 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1494 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
1495 SemaRef.Diag(IList->getSourceRange().getEnd(),
1496 diag::warn_missing_field_initializers) << it->getName();
1502 // Check that any remaining fields can be value-initialized.
1503 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1504 !Field->getType()->isIncompleteArrayType()) {
1505 // FIXME: Should check for holes left by designated initializers too.
1506 for (; Field != FieldEnd && !hadError; ++Field) {
1507 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
1508 CheckValueInitializable(
1509 InitializedEntity::InitializeMember(*Field, &Entity));
1513 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
1514 Index >= IList->getNumInits())
1517 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1524 InitializedEntity MemberEntity =
1525 InitializedEntity::InitializeMember(*Field, &Entity);
1527 if (isa<InitListExpr>(IList->getInit(Index)))
1528 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1529 StructuredList, StructuredIndex);
1531 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
1532 StructuredList, StructuredIndex);
1535 /// \brief Expand a field designator that refers to a member of an
1536 /// anonymous struct or union into a series of field designators that
1537 /// refers to the field within the appropriate subobject.
1539 static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1540 DesignatedInitExpr *DIE,
1542 IndirectFieldDecl *IndirectField) {
1543 typedef DesignatedInitExpr::Designator Designator;
1545 // Build the replacement designators.
1546 SmallVector<Designator, 4> Replacements;
1547 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1548 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1550 Replacements.push_back(Designator((IdentifierInfo *)0,
1551 DIE->getDesignator(DesigIdx)->getDotLoc(),
1552 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1554 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1556 assert(isa<FieldDecl>(*PI));
1557 Replacements.back().setField(cast<FieldDecl>(*PI));
1560 // Expand the current designator into the set of replacement
1561 // designators, so we have a full subobject path down to where the
1562 // member of the anonymous struct/union is actually stored.
1563 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
1564 &Replacements[0] + Replacements.size());
1567 /// \brief Given an implicit anonymous field, search the IndirectField that
1568 /// corresponds to FieldName.
1569 static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1570 IdentifierInfo *FieldName) {
1574 assert(AnonField->isAnonymousStructOrUnion());
1575 Decl *NextDecl = AnonField->getNextDeclInContext();
1576 while (IndirectFieldDecl *IF =
1577 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
1578 if (FieldName == IF->getAnonField()->getIdentifier())
1580 NextDecl = NextDecl->getNextDeclInContext();
1585 static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1586 DesignatedInitExpr *DIE) {
1587 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1588 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1589 for (unsigned I = 0; I < NumIndexExprs; ++I)
1590 IndexExprs[I] = DIE->getSubExpr(I + 1);
1591 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1592 DIE->size(), IndexExprs,
1593 DIE->getEqualOrColonLoc(),
1594 DIE->usesGNUSyntax(), DIE->getInit());
1599 // Callback to only accept typo corrections that are for field members of
1600 // the given struct or union.
1601 class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1603 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1606 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1607 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1608 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1617 /// @brief Check the well-formedness of a C99 designated initializer.
1619 /// Determines whether the designated initializer @p DIE, which
1620 /// resides at the given @p Index within the initializer list @p
1621 /// IList, is well-formed for a current object of type @p DeclType
1622 /// (C99 6.7.8). The actual subobject that this designator refers to
1623 /// within the current subobject is returned in either
1624 /// @p NextField or @p NextElementIndex (whichever is appropriate).
1626 /// @param IList The initializer list in which this designated
1627 /// initializer occurs.
1629 /// @param DIE The designated initializer expression.
1631 /// @param DesigIdx The index of the current designator.
1633 /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
1634 /// into which the designation in @p DIE should refer.
1636 /// @param NextField If non-NULL and the first designator in @p DIE is
1637 /// a field, this will be set to the field declaration corresponding
1638 /// to the field named by the designator.
1640 /// @param NextElementIndex If non-NULL and the first designator in @p
1641 /// DIE is an array designator or GNU array-range designator, this
1642 /// will be set to the last index initialized by this designator.
1644 /// @param Index Index into @p IList where the designated initializer
1647 /// @param StructuredList The initializer list expression that
1648 /// describes all of the subobject initializers in the order they'll
1649 /// actually be initialized.
1651 /// @returns true if there was an error, false otherwise.
1653 InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
1654 InitListExpr *IList,
1655 DesignatedInitExpr *DIE,
1657 QualType &CurrentObjectType,
1658 RecordDecl::field_iterator *NextField,
1659 llvm::APSInt *NextElementIndex,
1661 InitListExpr *StructuredList,
1662 unsigned &StructuredIndex,
1663 bool FinishSubobjectInit,
1664 bool TopLevelObject) {
1665 if (DesigIdx == DIE->size()) {
1666 // Check the actual initialization for the designated object type.
1667 bool prevHadError = hadError;
1669 // Temporarily remove the designator expression from the
1670 // initializer list that the child calls see, so that we don't try
1671 // to re-process the designator.
1672 unsigned OldIndex = Index;
1673 IList->setInit(OldIndex, DIE->getInit());
1675 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
1676 StructuredList, StructuredIndex);
1678 // Restore the designated initializer expression in the syntactic
1679 // form of the initializer list.
1680 if (IList->getInit(OldIndex) != DIE->getInit())
1681 DIE->setInit(IList->getInit(OldIndex));
1682 IList->setInit(OldIndex, DIE);
1684 return hadError && !prevHadError;
1687 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
1688 bool IsFirstDesignator = (DesigIdx == 0);
1690 assert((IsFirstDesignator || StructuredList) &&
1691 "Need a non-designated initializer list to start from");
1693 // Determine the structural initializer list that corresponds to the
1694 // current subobject.
1695 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
1696 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1697 StructuredList, StructuredIndex,
1698 SourceRange(D->getLocStart(),
1700 assert(StructuredList && "Expected a structured initializer list");
1703 if (D->isFieldDesignator()) {
1706 // If a designator has the form
1710 // then the current object (defined below) shall have
1711 // structure or union type and the identifier shall be the
1712 // name of a member of that type.
1713 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
1715 SourceLocation Loc = D->getDotLoc();
1716 if (Loc.isInvalid())
1717 Loc = D->getFieldLoc();
1719 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1720 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
1725 // Note: we perform a linear search of the fields here, despite
1726 // the fact that we have a faster lookup method, because we always
1727 // need to compute the field's index.
1728 FieldDecl *KnownField = D->getField();
1729 IdentifierInfo *FieldName = D->getFieldName();
1730 unsigned FieldIndex = 0;
1731 RecordDecl::field_iterator
1732 Field = RT->getDecl()->field_begin(),
1733 FieldEnd = RT->getDecl()->field_end();
1734 for (; Field != FieldEnd; ++Field) {
1735 if (Field->isUnnamedBitfield())
1738 // If we find a field representing an anonymous field, look in the
1739 // IndirectFieldDecl that follow for the designated initializer.
1740 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1741 if (IndirectFieldDecl *IF =
1742 FindIndirectFieldDesignator(*Field, FieldName)) {
1743 // In verify mode, don't modify the original.
1745 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
1746 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1747 D = DIE->getDesignator(DesigIdx);
1751 if (KnownField && KnownField == *Field)
1753 if (FieldName && FieldName == Field->getIdentifier())
1759 if (Field == FieldEnd) {
1762 return true; // No typo correction when just trying this out.
1765 // There was no normal field in the struct with the designated
1766 // name. Perform another lookup for this name, which may find
1767 // something that we can't designate (e.g., a member function),
1768 // may find nothing, or may find a member of an anonymous
1770 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
1771 FieldDecl *ReplacementField = 0;
1772 if (Lookup.empty()) {
1773 // Name lookup didn't find anything. Determine whether this
1774 // was a typo for another field name.
1775 FieldInitializerValidatorCCC Validator(RT->getDecl());
1776 TypoCorrection Corrected = SemaRef.CorrectTypo(
1777 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1778 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator,
1781 std::string CorrectedStr(
1782 Corrected.getAsString(SemaRef.getLangOpts()));
1783 std::string CorrectedQuotedStr(
1784 Corrected.getQuoted(SemaRef.getLangOpts()));
1785 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
1786 SemaRef.Diag(D->getFieldLoc(),
1787 diag::err_field_designator_unknown_suggest)
1788 << FieldName << CurrentObjectType << CorrectedQuotedStr
1789 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
1790 SemaRef.Diag(ReplacementField->getLocation(),
1791 diag::note_previous_decl) << CorrectedQuotedStr;
1794 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1795 << FieldName << CurrentObjectType;
1801 if (!ReplacementField) {
1802 // Name lookup found something, but it wasn't a field.
1803 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
1805 SemaRef.Diag(Lookup.front()->getLocation(),
1806 diag::note_field_designator_found);
1812 // The replacement field comes from typo correction; find it
1813 // in the list of fields.
1815 Field = RT->getDecl()->field_begin();
1816 for (; Field != FieldEnd; ++Field) {
1817 if (Field->isUnnamedBitfield())
1820 if (ReplacementField == *Field ||
1821 Field->getIdentifier() == ReplacementField->getIdentifier())
1829 // All of the fields of a union are located at the same place in
1830 // the initializer list.
1831 if (RT->getDecl()->isUnion()) {
1834 StructuredList->setInitializedFieldInUnion(*Field);
1837 // Make sure we can use this declaration.
1840 InvalidUse = !SemaRef.CanUseDecl(*Field);
1842 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1849 // Update the designator with the field declaration.
1850 D->setField(*Field);
1852 // Make sure that our non-designated initializer list has space
1853 // for a subobject corresponding to this field.
1854 if (FieldIndex >= StructuredList->getNumInits())
1855 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1858 // This designator names a flexible array member.
1859 if (Field->getType()->isIncompleteArrayType()) {
1860 bool Invalid = false;
1861 if ((DesigIdx + 1) != DIE->size()) {
1862 // We can't designate an object within the flexible array
1863 // member (because GCC doesn't allow it).
1865 DesignatedInitExpr::Designator *NextD
1866 = DIE->getDesignator(DesigIdx + 1);
1867 SemaRef.Diag(NextD->getLocStart(),
1868 diag::err_designator_into_flexible_array_member)
1869 << SourceRange(NextD->getLocStart(),
1871 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1877 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1878 !isa<StringLiteral>(DIE->getInit())) {
1879 // The initializer is not an initializer list.
1881 SemaRef.Diag(DIE->getInit()->getLocStart(),
1882 diag::err_flexible_array_init_needs_braces)
1883 << DIE->getInit()->getSourceRange();
1884 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1890 // Check GNU flexible array initializer.
1891 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1900 // Initialize the array.
1901 bool prevHadError = hadError;
1902 unsigned newStructuredIndex = FieldIndex;
1903 unsigned OldIndex = Index;
1904 IList->setInit(Index, DIE->getInit());
1906 InitializedEntity MemberEntity =
1907 InitializedEntity::InitializeMember(*Field, &Entity);
1908 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1909 StructuredList, newStructuredIndex);
1911 IList->setInit(OldIndex, DIE);
1912 if (hadError && !prevHadError) {
1917 StructuredIndex = FieldIndex;
1921 // Recurse to check later designated subobjects.
1922 QualType FieldType = Field->getType();
1923 unsigned newStructuredIndex = FieldIndex;
1925 InitializedEntity MemberEntity =
1926 InitializedEntity::InitializeMember(*Field, &Entity);
1927 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1928 FieldType, 0, 0, Index,
1929 StructuredList, newStructuredIndex,
1934 // Find the position of the next field to be initialized in this
1939 // If this the first designator, our caller will continue checking
1940 // the rest of this struct/class/union subobject.
1941 if (IsFirstDesignator) {
1944 StructuredIndex = FieldIndex;
1948 if (!FinishSubobjectInit)
1951 // We've already initialized something in the union; we're done.
1952 if (RT->getDecl()->isUnion())
1955 // Check the remaining fields within this class/struct/union subobject.
1956 bool prevHadError = hadError;
1958 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
1959 StructuredList, FieldIndex);
1960 return hadError && !prevHadError;
1965 // If a designator has the form
1967 // [ constant-expression ]
1969 // then the current object (defined below) shall have array
1970 // type and the expression shall be an integer constant
1971 // expression. If the array is of unknown size, any
1972 // nonnegative value is valid.
1974 // Additionally, cope with the GNU extension that permits
1975 // designators of the form
1977 // [ constant-expression ... constant-expression ]
1978 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
1981 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1982 << CurrentObjectType;
1987 Expr *IndexExpr = 0;
1988 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1989 if (D->isArrayDesignator()) {
1990 IndexExpr = DIE->getArrayIndex(*D);
1991 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
1992 DesignatedEndIndex = DesignatedStartIndex;
1994 assert(D->isArrayRangeDesignator() && "Need array-range designator");
1996 DesignatedStartIndex =
1997 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
1998 DesignatedEndIndex =
1999 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
2000 IndexExpr = DIE->getArrayRangeEnd(*D);
2002 // Codegen can't handle evaluating array range designators that have side
2003 // effects, because we replicate the AST value for each initialized element.
2004 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2005 // elements with something that has a side effect, so codegen can emit an
2006 // "error unsupported" error instead of miscompiling the app.
2007 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
2008 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
2009 FullyStructuredList->sawArrayRangeDesignator();
2012 if (isa<ConstantArrayType>(AT)) {
2013 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
2014 DesignatedStartIndex
2015 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
2016 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
2018 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
2019 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2020 if (DesignatedEndIndex >= MaxElements) {
2022 SemaRef.Diag(IndexExpr->getLocStart(),
2023 diag::err_array_designator_too_large)
2024 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2025 << IndexExpr->getSourceRange();
2030 // Make sure the bit-widths and signedness match.
2031 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
2033 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
2034 else if (DesignatedStartIndex.getBitWidth() <
2035 DesignatedEndIndex.getBitWidth())
2036 DesignatedStartIndex
2037 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
2038 DesignatedStartIndex.setIsUnsigned(true);
2039 DesignatedEndIndex.setIsUnsigned(true);
2042 // Make sure that our non-designated initializer list has space
2043 // for a subobject corresponding to this array element.
2045 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
2046 StructuredList->resizeInits(SemaRef.Context,
2047 DesignatedEndIndex.getZExtValue() + 1);
2049 // Repeatedly perform subobject initializations in the range
2050 // [DesignatedStartIndex, DesignatedEndIndex].
2052 // Move to the next designator
2053 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2054 unsigned OldIndex = Index;
2056 InitializedEntity ElementEntity =
2057 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
2059 while (DesignatedStartIndex <= DesignatedEndIndex) {
2060 // Recurse to check later designated subobjects.
2061 QualType ElementType = AT->getElementType();
2064 ElementEntity.setElementIndex(ElementIndex);
2065 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2066 ElementType, 0, 0, Index,
2067 StructuredList, ElementIndex,
2068 (DesignatedStartIndex == DesignatedEndIndex),
2072 // Move to the next index in the array that we'll be initializing.
2073 ++DesignatedStartIndex;
2074 ElementIndex = DesignatedStartIndex.getZExtValue();
2077 // If this the first designator, our caller will continue checking
2078 // the rest of this array subobject.
2079 if (IsFirstDesignator) {
2080 if (NextElementIndex)
2081 *NextElementIndex = DesignatedStartIndex;
2082 StructuredIndex = ElementIndex;
2086 if (!FinishSubobjectInit)
2089 // Check the remaining elements within this array subobject.
2090 bool prevHadError = hadError;
2091 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
2092 /*SubobjectIsDesignatorContext=*/false, Index,
2093 StructuredList, ElementIndex);
2094 return hadError && !prevHadError;
2097 // Get the structured initializer list for a subobject of type
2098 // @p CurrentObjectType.
2100 InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2101 QualType CurrentObjectType,
2102 InitListExpr *StructuredList,
2103 unsigned StructuredIndex,
2104 SourceRange InitRange) {
2106 return 0; // No structured list in verification-only mode.
2107 Expr *ExistingInit = 0;
2108 if (!StructuredList)
2109 ExistingInit = SyntacticToSemantic.lookup(IList);
2110 else if (StructuredIndex < StructuredList->getNumInits())
2111 ExistingInit = StructuredList->getInit(StructuredIndex);
2113 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2117 // We are creating an initializer list that initializes the
2118 // subobjects of the current object, but there was already an
2119 // initialization that completely initialized the current
2120 // subobject, e.g., by a compound literal:
2122 // struct X { int a, b; };
2123 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2125 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2126 // designated initializer re-initializes the whole
2127 // subobject [0], overwriting previous initializers.
2128 SemaRef.Diag(InitRange.getBegin(),
2129 diag::warn_subobject_initializer_overrides)
2131 SemaRef.Diag(ExistingInit->getLocStart(),
2132 diag::note_previous_initializer)
2133 << /*FIXME:has side effects=*/0
2134 << ExistingInit->getSourceRange();
2137 InitListExpr *Result
2138 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2139 InitRange.getBegin(), None,
2140 InitRange.getEnd());
2142 QualType ResultType = CurrentObjectType;
2143 if (!ResultType->isArrayType())
2144 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2145 Result->setType(ResultType);
2147 // Pre-allocate storage for the structured initializer list.
2148 unsigned NumElements = 0;
2149 unsigned NumInits = 0;
2150 bool GotNumInits = false;
2151 if (!StructuredList) {
2152 NumInits = IList->getNumInits();
2154 } else if (Index < IList->getNumInits()) {
2155 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
2156 NumInits = SubList->getNumInits();
2161 if (const ArrayType *AType
2162 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2163 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2164 NumElements = CAType->getSize().getZExtValue();
2165 // Simple heuristic so that we don't allocate a very large
2166 // initializer with many empty entries at the end.
2167 if (GotNumInits && NumElements > NumInits)
2170 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
2171 NumElements = VType->getNumElements();
2172 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
2173 RecordDecl *RDecl = RType->getDecl();
2174 if (RDecl->isUnion())
2177 NumElements = std::distance(RDecl->field_begin(),
2178 RDecl->field_end());
2181 Result->reserveInits(SemaRef.Context, NumElements);
2183 // Link this new initializer list into the structured initializer
2186 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
2188 Result->setSyntacticForm(IList);
2189 SyntacticToSemantic[IList] = Result;
2195 /// Update the initializer at index @p StructuredIndex within the
2196 /// structured initializer list to the value @p expr.
2197 void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2198 unsigned &StructuredIndex,
2200 // No structured initializer list to update
2201 if (!StructuredList)
2204 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2205 StructuredIndex, expr)) {
2206 // This initializer overwrites a previous initializer. Warn.
2207 SemaRef.Diag(expr->getLocStart(),
2208 diag::warn_initializer_overrides)
2209 << expr->getSourceRange();
2210 SemaRef.Diag(PrevInit->getLocStart(),
2211 diag::note_previous_initializer)
2212 << /*FIXME:has side effects=*/0
2213 << PrevInit->getSourceRange();
2219 /// Check that the given Index expression is a valid array designator
2220 /// value. This is essentially just a wrapper around
2221 /// VerifyIntegerConstantExpression that also checks for negative values
2222 /// and produces a reasonable diagnostic if there is a
2223 /// failure. Returns the index expression, possibly with an implicit cast
2224 /// added, on success. If everything went okay, Value will receive the
2225 /// value of the constant expression.
2227 CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
2228 SourceLocation Loc = Index->getLocStart();
2230 // Make sure this is an integer constant expression.
2231 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2232 if (Result.isInvalid())
2235 if (Value.isSigned() && Value.isNegative())
2236 return S.Diag(Loc, diag::err_array_designator_negative)
2237 << Value.toString(10) << Index->getSourceRange();
2239 Value.setIsUnsigned(true);
2243 ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
2247 typedef DesignatedInitExpr::Designator ASTDesignator;
2249 bool Invalid = false;
2250 SmallVector<ASTDesignator, 32> Designators;
2251 SmallVector<Expr *, 32> InitExpressions;
2253 // Build designators and check array designator expressions.
2254 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2255 const Designator &D = Desig.getDesignator(Idx);
2256 switch (D.getKind()) {
2257 case Designator::FieldDesignator:
2258 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
2262 case Designator::ArrayDesignator: {
2263 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2264 llvm::APSInt IndexValue;
2265 if (!Index->isTypeDependent() && !Index->isValueDependent())
2266 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2270 Designators.push_back(ASTDesignator(InitExpressions.size(),
2272 D.getRBracketLoc()));
2273 InitExpressions.push_back(Index);
2278 case Designator::ArrayRangeDesignator: {
2279 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2280 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2281 llvm::APSInt StartValue;
2282 llvm::APSInt EndValue;
2283 bool StartDependent = StartIndex->isTypeDependent() ||
2284 StartIndex->isValueDependent();
2285 bool EndDependent = EndIndex->isTypeDependent() ||
2286 EndIndex->isValueDependent();
2287 if (!StartDependent)
2289 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2291 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2293 if (!StartIndex || !EndIndex)
2296 // Make sure we're comparing values with the same bit width.
2297 if (StartDependent || EndDependent) {
2298 // Nothing to compute.
2299 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
2300 EndValue = EndValue.extend(StartValue.getBitWidth());
2301 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
2302 StartValue = StartValue.extend(EndValue.getBitWidth());
2304 if (!StartDependent && !EndDependent && EndValue < StartValue) {
2305 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
2306 << StartValue.toString(10) << EndValue.toString(10)
2307 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2310 Designators.push_back(ASTDesignator(InitExpressions.size(),
2313 D.getRBracketLoc()));
2314 InitExpressions.push_back(StartIndex);
2315 InitExpressions.push_back(EndIndex);
2323 if (Invalid || Init.isInvalid())
2326 // Clear out the expressions within the designation.
2327 Desig.ClearExprs(*this);
2329 DesignatedInitExpr *DIE
2330 = DesignatedInitExpr::Create(Context,
2331 Designators.data(), Designators.size(),
2332 InitExpressions, Loc, GNUSyntax,
2333 Init.takeAs<Expr>());
2335 if (!getLangOpts().C99)
2336 Diag(DIE->getLocStart(), diag::ext_designated_init)
2337 << DIE->getSourceRange();
2342 //===----------------------------------------------------------------------===//
2343 // Initialization entity
2344 //===----------------------------------------------------------------------===//
2346 InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
2347 const InitializedEntity &Parent)
2348 : Parent(&Parent), Index(Index)
2350 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2351 Kind = EK_ArrayElement;
2352 Type = AT->getElementType();
2353 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
2354 Kind = EK_VectorElement;
2355 Type = VT->getElementType();
2357 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2358 assert(CT && "Unexpected type");
2359 Kind = EK_ComplexElement;
2360 Type = CT->getElementType();
2364 InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
2365 CXXBaseSpecifier *Base,
2366 bool IsInheritedVirtualBase)
2368 InitializedEntity Result;
2369 Result.Kind = EK_Base;
2370 Result.Base = reinterpret_cast<uintptr_t>(Base);
2371 if (IsInheritedVirtualBase)
2372 Result.Base |= 0x01;
2374 Result.Type = Base->getType();
2378 DeclarationName InitializedEntity::getName() const {
2379 switch (getKind()) {
2380 case EK_Parameter: {
2381 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2382 return (D ? D->getDeclName() : DeclarationName());
2387 return VariableOrMember->getDeclName();
2389 case EK_LambdaCapture:
2390 return Capture.Var->getDeclName();
2398 case EK_ArrayElement:
2399 case EK_VectorElement:
2400 case EK_ComplexElement:
2401 case EK_BlockElement:
2402 case EK_CompoundLiteralInit:
2403 return DeclarationName();
2406 llvm_unreachable("Invalid EntityKind!");
2409 DeclaratorDecl *InitializedEntity::getDecl() const {
2410 switch (getKind()) {
2413 return VariableOrMember;
2416 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2424 case EK_ArrayElement:
2425 case EK_VectorElement:
2426 case EK_ComplexElement:
2427 case EK_BlockElement:
2428 case EK_LambdaCapture:
2429 case EK_CompoundLiteralInit:
2433 llvm_unreachable("Invalid EntityKind!");
2436 bool InitializedEntity::allowsNRVO() const {
2437 switch (getKind()) {
2440 return LocAndNRVO.NRVO;
2447 case EK_CompoundLiteralInit:
2450 case EK_ArrayElement:
2451 case EK_VectorElement:
2452 case EK_ComplexElement:
2453 case EK_BlockElement:
2454 case EK_LambdaCapture:
2461 //===----------------------------------------------------------------------===//
2462 // Initialization sequence
2463 //===----------------------------------------------------------------------===//
2465 void InitializationSequence::Step::Destroy() {
2467 case SK_ResolveAddressOfOverloadedFunction:
2468 case SK_CastDerivedToBaseRValue:
2469 case SK_CastDerivedToBaseXValue:
2470 case SK_CastDerivedToBaseLValue:
2471 case SK_BindReference:
2472 case SK_BindReferenceToTemporary:
2473 case SK_ExtraneousCopyToTemporary:
2474 case SK_UserConversion:
2475 case SK_QualificationConversionRValue:
2476 case SK_QualificationConversionXValue:
2477 case SK_QualificationConversionLValue:
2478 case SK_LValueToRValue:
2479 case SK_ListInitialization:
2480 case SK_ListConstructorCall:
2481 case SK_UnwrapInitList:
2482 case SK_RewrapInitList:
2483 case SK_ConstructorInitialization:
2484 case SK_ZeroInitialization:
2485 case SK_CAssignment:
2487 case SK_ObjCObjectConversion:
2489 case SK_ParenthesizedArrayInit:
2490 case SK_PassByIndirectCopyRestore:
2491 case SK_PassByIndirectRestore:
2492 case SK_ProduceObjCObject:
2493 case SK_StdInitializerList:
2494 case SK_OCLSamplerInit:
2495 case SK_OCLZeroEvent:
2498 case SK_ConversionSequence:
2503 bool InitializationSequence::isDirectReferenceBinding() const {
2504 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
2507 bool InitializationSequence::isAmbiguous() const {
2511 switch (getFailureKind()) {
2512 case FK_TooManyInitsForReference:
2513 case FK_ArrayNeedsInitList:
2514 case FK_ArrayNeedsInitListOrStringLiteral:
2515 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2516 case FK_NonConstLValueReferenceBindingToTemporary:
2517 case FK_NonConstLValueReferenceBindingToUnrelated:
2518 case FK_RValueReferenceBindingToLValue:
2519 case FK_ReferenceInitDropsQualifiers:
2520 case FK_ReferenceInitFailed:
2521 case FK_ConversionFailed:
2522 case FK_ConversionFromPropertyFailed:
2523 case FK_TooManyInitsForScalar:
2524 case FK_ReferenceBindingToInitList:
2525 case FK_InitListBadDestinationType:
2526 case FK_DefaultInitOfConst:
2528 case FK_ArrayTypeMismatch:
2529 case FK_NonConstantArrayInit:
2530 case FK_ListInitializationFailed:
2531 case FK_VariableLengthArrayHasInitializer:
2532 case FK_PlaceholderType:
2533 case FK_InitListElementCopyFailure:
2534 case FK_ExplicitConstructor:
2537 case FK_ReferenceInitOverloadFailed:
2538 case FK_UserConversionOverloadFailed:
2539 case FK_ConstructorOverloadFailed:
2540 case FK_ListConstructorOverloadFailed:
2541 return FailedOverloadResult == OR_Ambiguous;
2544 llvm_unreachable("Invalid EntityKind!");
2547 bool InitializationSequence::isConstructorInitialization() const {
2548 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2552 InitializationSequence
2553 ::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2554 DeclAccessPair Found,
2555 bool HadMultipleCandidates) {
2557 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2558 S.Type = Function->getType();
2559 S.Function.HadMultipleCandidates = HadMultipleCandidates;
2560 S.Function.Function = Function;
2561 S.Function.FoundDecl = Found;
2565 void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2569 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2570 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2571 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
2577 void InitializationSequence::AddReferenceBindingStep(QualType T,
2578 bool BindingTemporary) {
2580 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2585 void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2587 S.Kind = SK_ExtraneousCopyToTemporary;
2593 InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2594 DeclAccessPair FoundDecl,
2596 bool HadMultipleCandidates) {
2598 S.Kind = SK_UserConversion;
2600 S.Function.HadMultipleCandidates = HadMultipleCandidates;
2601 S.Function.Function = Function;
2602 S.Function.FoundDecl = FoundDecl;
2606 void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2609 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
2612 S.Kind = SK_QualificationConversionRValue;
2615 S.Kind = SK_QualificationConversionXValue;
2618 S.Kind = SK_QualificationConversionLValue;
2625 void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2626 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2629 S.Kind = SK_LValueToRValue;
2634 void InitializationSequence::AddConversionSequenceStep(
2635 const ImplicitConversionSequence &ICS,
2638 S.Kind = SK_ConversionSequence;
2640 S.ICS = new ImplicitConversionSequence(ICS);
2644 void InitializationSequence::AddListInitializationStep(QualType T) {
2646 S.Kind = SK_ListInitialization;
2652 InitializationSequence
2653 ::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2654 AccessSpecifier Access,
2656 bool HadMultipleCandidates,
2657 bool FromInitList, bool AsInitList) {
2659 S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2660 : SK_ConstructorInitialization;
2662 S.Function.HadMultipleCandidates = HadMultipleCandidates;
2663 S.Function.Function = Constructor;
2664 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
2668 void InitializationSequence::AddZeroInitializationStep(QualType T) {
2670 S.Kind = SK_ZeroInitialization;
2675 void InitializationSequence::AddCAssignmentStep(QualType T) {
2677 S.Kind = SK_CAssignment;
2682 void InitializationSequence::AddStringInitStep(QualType T) {
2684 S.Kind = SK_StringInit;
2689 void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2691 S.Kind = SK_ObjCObjectConversion;
2696 void InitializationSequence::AddArrayInitStep(QualType T) {
2698 S.Kind = SK_ArrayInit;
2703 void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2705 S.Kind = SK_ParenthesizedArrayInit;
2710 void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2713 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2714 : SK_PassByIndirectRestore);
2719 void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2721 S.Kind = SK_ProduceObjCObject;
2726 void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2728 S.Kind = SK_StdInitializerList;
2733 void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
2735 S.Kind = SK_OCLSamplerInit;
2740 void InitializationSequence::AddOCLZeroEventStep(QualType T) {
2742 S.Kind = SK_OCLZeroEvent;
2747 void InitializationSequence::RewrapReferenceInitList(QualType T,
2748 InitListExpr *Syntactic) {
2749 assert(Syntactic->getNumInits() == 1 &&
2750 "Can only rewrap trivial init lists.");
2752 S.Kind = SK_UnwrapInitList;
2753 S.Type = Syntactic->getInit(0)->getType();
2754 Steps.insert(Steps.begin(), S);
2756 S.Kind = SK_RewrapInitList;
2758 S.WrappingSyntacticList = Syntactic;
2762 void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2763 OverloadingResult Result) {
2764 setSequenceKind(FailedSequence);
2765 this->Failure = Failure;
2766 this->FailedOverloadResult = Result;
2769 //===----------------------------------------------------------------------===//
2770 // Attempt initialization
2771 //===----------------------------------------------------------------------===//
2773 static void MaybeProduceObjCObject(Sema &S,
2774 InitializationSequence &Sequence,
2775 const InitializedEntity &Entity) {
2776 if (!S.getLangOpts().ObjCAutoRefCount) return;
2778 /// When initializing a parameter, produce the value if it's marked
2779 /// __attribute__((ns_consumed)).
2780 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2781 if (!Entity.isParameterConsumed())
2784 assert(Entity.getType()->isObjCRetainableType() &&
2785 "consuming an object of unretainable type?");
2786 Sequence.AddProduceObjCObjectStep(Entity.getType());
2788 /// When initializing a return value, if the return type is a
2789 /// retainable type, then returns need to immediately retain the
2790 /// object. If an autorelease is required, it will be done at the
2792 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2793 if (!Entity.getType()->isObjCRetainableType())
2796 Sequence.AddProduceObjCObjectStep(Entity.getType());
2800 /// \brief When initializing from init list via constructor, handle
2801 /// initialization of an object of type std::initializer_list<T>.
2803 /// \return true if we have handled initialization of an object of type
2804 /// std::initializer_list<T>, false otherwise.
2805 static bool TryInitializerListConstruction(Sema &S,
2808 InitializationSequence &Sequence) {
2810 if (!S.isStdInitializerList(DestType, &E))
2813 // Check that each individual element can be copy-constructed. But since we
2814 // have no place to store further information, we'll recalculate everything
2816 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2817 S.Context.getConstantArrayType(E,
2818 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2819 List->getNumInits()),
2820 ArrayType::Normal, 0));
2821 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2823 for (unsigned i = 0, n = List->getNumInits(); i < n; ++i) {
2824 Element.setElementIndex(i);
2825 if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) {
2827 InitializationSequence::FK_InitListElementCopyFailure);
2831 Sequence.AddStdInitializerListConstructionStep(DestType);
2835 static OverloadingResult
2836 ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
2838 OverloadCandidateSet &CandidateSet,
2839 ArrayRef<NamedDecl *> Ctors,
2840 OverloadCandidateSet::iterator &Best,
2841 bool CopyInitializing, bool AllowExplicit,
2842 bool OnlyListConstructors, bool InitListSyntax) {
2843 CandidateSet.clear();
2845 for (ArrayRef<NamedDecl *>::iterator
2846 Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
2847 NamedDecl *D = *Con;
2848 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2849 bool SuppressUserConversions = false;
2851 // Find the constructor (which may be a template).
2852 CXXConstructorDecl *Constructor = 0;
2853 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2854 if (ConstructorTmpl)
2855 Constructor = cast<CXXConstructorDecl>(
2856 ConstructorTmpl->getTemplatedDecl());
2858 Constructor = cast<CXXConstructorDecl>(D);
2860 // If we're performing copy initialization using a copy constructor, we
2861 // suppress user-defined conversions on the arguments. We do the same for
2862 // move constructors.
2863 if ((CopyInitializing || (InitListSyntax && Args.size() == 1)) &&
2864 Constructor->isCopyOrMoveConstructor())
2865 SuppressUserConversions = true;
2868 if (!Constructor->isInvalidDecl() &&
2869 (AllowExplicit || !Constructor->isExplicit()) &&
2870 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
2871 if (ConstructorTmpl)
2872 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2873 /*ExplicitArgs*/ 0, Args,
2874 CandidateSet, SuppressUserConversions);
2876 // C++ [over.match.copy]p1:
2877 // - When initializing a temporary to be bound to the first parameter
2878 // of a constructor that takes a reference to possibly cv-qualified
2879 // T as its first argument, called with a single argument in the
2880 // context of direct-initialization, explicit conversion functions
2881 // are also considered.
2882 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
2884 Constructor->isCopyOrMoveConstructor();
2885 S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
2886 SuppressUserConversions,
2887 /*PartialOverloading=*/false,
2888 /*AllowExplicit=*/AllowExplicitConv);
2893 // Perform overload resolution and return the result.
2894 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
2897 /// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2898 /// enumerates the constructors of the initialized entity and performs overload
2899 /// resolution to select the best.
2900 /// If InitListSyntax is true, this is list-initialization of a non-aggregate
2902 static void TryConstructorInitialization(Sema &S,
2903 const InitializedEntity &Entity,
2904 const InitializationKind &Kind,
2905 MultiExprArg Args, QualType DestType,
2906 InitializationSequence &Sequence,
2907 bool InitListSyntax = false) {
2908 assert((!InitListSyntax || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
2909 "InitListSyntax must come with a single initializer list argument.");
2911 // The type we're constructing needs to be complete.
2912 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
2913 Sequence.setIncompleteTypeFailure(DestType);
2917 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2918 assert(DestRecordType && "Constructor initialization requires record type");
2919 CXXRecordDecl *DestRecordDecl
2920 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2922 // Build the candidate set directly in the initialization sequence
2923 // structure, so that it will persist if we fail.
2924 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2926 // Determine whether we are allowed to call explicit constructors or
2927 // explicit conversion operators.
2928 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
2929 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
2931 // - Otherwise, if T is a class type, constructors are considered. The
2932 // applicable constructors are enumerated, and the best one is chosen
2933 // through overload resolution.
2934 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
2935 // The container holding the constructors can under certain conditions
2936 // be changed while iterating (e.g. because of deserialization).
2937 // To be safe we copy the lookup results to a new container.
2938 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
2940 OverloadingResult Result = OR_No_Viable_Function;
2941 OverloadCandidateSet::iterator Best;
2942 bool AsInitializerList = false;
2944 // C++11 [over.match.list]p1:
2945 // When objects of non-aggregate type T are list-initialized, overload
2946 // resolution selects the constructor in two phases:
2947 // - Initially, the candidate functions are the initializer-list
2948 // constructors of the class T and the argument list consists of the
2949 // initializer list as a single argument.
2950 if (InitListSyntax) {
2951 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
2952 AsInitializerList = true;
2954 // If the initializer list has no elements and T has a default constructor,
2955 // the first phase is omitted.
2956 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
2957 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
2958 CandidateSet, Ctors, Best,
2959 CopyInitialization, AllowExplicit,
2960 /*OnlyListConstructor=*/true,
2963 // Time to unwrap the init list.
2964 Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
2967 // C++11 [over.match.list]p1:
2968 // - If no viable initializer-list constructor is found, overload resolution
2969 // is performed again, where the candidate functions are all the
2970 // constructors of the class T and the argument list consists of the
2971 // elements of the initializer list.
2972 if (Result == OR_No_Viable_Function) {
2973 AsInitializerList = false;
2974 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
2975 CandidateSet, Ctors, Best,
2976 CopyInitialization, AllowExplicit,
2977 /*OnlyListConstructors=*/false,
2981 Sequence.SetOverloadFailure(InitListSyntax ?
2982 InitializationSequence::FK_ListConstructorOverloadFailed :
2983 InitializationSequence::FK_ConstructorOverloadFailed,
2988 // C++11 [dcl.init]p6:
2989 // If a program calls for the default initialization of an object
2990 // of a const-qualified type T, T shall be a class type with a
2991 // user-provided default constructor.
2992 if (Kind.getKind() == InitializationKind::IK_Default &&
2993 Entity.getType().isConstQualified() &&
2994 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
2995 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2999 // C++11 [over.match.list]p1:
3000 // In copy-list-initialization, if an explicit constructor is chosen, the
3001 // initializer is ill-formed.
3002 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3003 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3004 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3008 // Add the constructor initialization step. Any cv-qualification conversion is
3009 // subsumed by the initialization.
3010 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3011 Sequence.AddConstructorInitializationStep(CtorDecl,
3012 Best->FoundDecl.getAccess(),
3013 DestType, HadMultipleCandidates,
3014 InitListSyntax, AsInitializerList);
3018 ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3020 QualType &SourceType,
3021 QualType &UnqualifiedSourceType,
3022 QualType UnqualifiedTargetType,
3023 InitializationSequence &Sequence) {
3024 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3025 S.Context.OverloadTy) {
3026 DeclAccessPair Found;
3027 bool HadMultipleCandidates = false;
3028 if (FunctionDecl *Fn
3029 = S.ResolveAddressOfOverloadedFunction(Initializer,
3030 UnqualifiedTargetType,
3032 &HadMultipleCandidates)) {
3033 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3034 HadMultipleCandidates);
3035 SourceType = Fn->getType();
3036 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3037 } else if (!UnqualifiedTargetType->isRecordType()) {
3038 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3045 static void TryReferenceInitializationCore(Sema &S,
3046 const InitializedEntity &Entity,
3047 const InitializationKind &Kind,
3049 QualType cv1T1, QualType T1,
3051 QualType cv2T2, QualType T2,
3053 InitializationSequence &Sequence);
3055 static void TryValueInitialization(Sema &S,
3056 const InitializedEntity &Entity,
3057 const InitializationKind &Kind,
3058 InitializationSequence &Sequence,
3059 InitListExpr *InitList = 0);
3061 static void TryListInitialization(Sema &S,
3062 const InitializedEntity &Entity,
3063 const InitializationKind &Kind,
3064 InitListExpr *InitList,
3065 InitializationSequence &Sequence);
3067 /// \brief Attempt list initialization of a reference.
3068 static void TryReferenceListInitialization(Sema &S,
3069 const InitializedEntity &Entity,
3070 const InitializationKind &Kind,
3071 InitListExpr *InitList,
3072 InitializationSequence &Sequence)
3074 // First, catch C++03 where this isn't possible.
3075 if (!S.getLangOpts().CPlusPlus11) {
3076 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3080 QualType DestType = Entity.getType();
3081 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3083 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3085 // Reference initialization via an initializer list works thus:
3086 // If the initializer list consists of a single element that is
3087 // reference-related to the referenced type, bind directly to that element
3088 // (possibly creating temporaries).
3089 // Otherwise, initialize a temporary with the initializer list and
3091 if (InitList->getNumInits() == 1) {
3092 Expr *Initializer = InitList->getInit(0);
3093 QualType cv2T2 = Initializer->getType();
3095 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3097 // If this fails, creating a temporary wouldn't work either.
3098 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3102 SourceLocation DeclLoc = Initializer->getLocStart();
3103 bool dummy1, dummy2, dummy3;
3104 Sema::ReferenceCompareResult RefRelationship
3105 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3107 if (RefRelationship >= Sema::Ref_Related) {
3108 // Try to bind the reference here.
3109 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3110 T1Quals, cv2T2, T2, T2Quals, Sequence);
3112 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3116 // Update the initializer if we've resolved an overloaded function.
3117 if (Sequence.step_begin() != Sequence.step_end())
3118 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3121 // Not reference-related. Create a temporary and bind to that.
3122 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3124 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3126 if (DestType->isRValueReferenceType() ||
3127 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3128 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3131 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3135 /// \brief Attempt list initialization (C++0x [dcl.init.list])
3136 static void TryListInitialization(Sema &S,
3137 const InitializedEntity &Entity,
3138 const InitializationKind &Kind,
3139 InitListExpr *InitList,
3140 InitializationSequence &Sequence) {
3141 QualType DestType = Entity.getType();
3143 // C++ doesn't allow scalar initialization with more than one argument.
3144 // But C99 complex numbers are scalars and it makes sense there.
3145 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
3146 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3147 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3150 if (DestType->isReferenceType()) {
3151 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
3154 if (DestType->isRecordType()) {
3155 if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
3156 Sequence.setIncompleteTypeFailure(DestType);
3160 // C++11 [dcl.init.list]p3:
3161 // - If T is an aggregate, aggregate initialization is performed.
3162 if (!DestType->isAggregateType()) {
3163 if (S.getLangOpts().CPlusPlus11) {
3164 // - Otherwise, if the initializer list has no elements and T is a
3165 // class type with a default constructor, the object is
3166 // value-initialized.
3167 if (InitList->getNumInits() == 0) {
3168 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
3169 if (RD->hasDefaultConstructor()) {
3170 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3175 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3176 // an initializer_list object constructed [...]
3177 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3180 // - Otherwise, if T is a class type, constructors are considered.
3181 Expr *InitListAsExpr = InitList;
3182 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
3183 Sequence, /*InitListSyntax*/true);
3186 InitializationSequence::FK_InitListBadDestinationType);
3191 InitListChecker CheckInitList(S, Entity, InitList,
3192 DestType, /*VerifyOnly=*/true,
3193 Kind.getKind() != InitializationKind::IK_DirectList ||
3194 !S.getLangOpts().CPlusPlus11);
3195 if (CheckInitList.HadError()) {
3196 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3200 // Add the list initialization step with the built init list.
3201 Sequence.AddListInitializationStep(DestType);
3204 /// \brief Try a reference initialization that involves calling a conversion
3206 static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3207 const InitializedEntity &Entity,
3208 const InitializationKind &Kind,
3211 InitializationSequence &Sequence) {
3212 QualType DestType = Entity.getType();
3213 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3214 QualType T1 = cv1T1.getUnqualifiedType();
3215 QualType cv2T2 = Initializer->getType();
3216 QualType T2 = cv2T2.getUnqualifiedType();
3219 bool ObjCConversion;
3220 bool ObjCLifetimeConversion;
3221 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
3222 T1, T2, DerivedToBase,
3224 ObjCLifetimeConversion) &&
3225 "Must have incompatible references when binding via conversion");
3226 (void)DerivedToBase;
3227 (void)ObjCConversion;
3228 (void)ObjCLifetimeConversion;
3230 // Build the candidate set directly in the initialization sequence
3231 // structure, so that it will persist if we fail.
3232 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3233 CandidateSet.clear();
3235 // Determine whether we are allowed to call explicit constructors or
3236 // explicit conversion operators.
3237 bool AllowExplicit = Kind.AllowExplicit();
3238 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctions();
3240 const RecordType *T1RecordType = 0;
3241 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3242 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
3243 // The type we're converting to is a class type. Enumerate its constructors
3244 // to see if there is a suitable conversion.
3245 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
3247 DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
3248 // The container holding the constructors can under certain conditions
3249 // be changed while iterating (e.g. because of deserialization).
3250 // To be safe we copy the lookup results to a new container.
3251 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
3252 for (SmallVector<NamedDecl*, 16>::iterator
3253 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3255 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3257 // Find the constructor (which may be a template).
3258 CXXConstructorDecl *Constructor = 0;
3259 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3260 if (ConstructorTmpl)
3261 Constructor = cast<CXXConstructorDecl>(
3262 ConstructorTmpl->getTemplatedDecl());
3264 Constructor = cast<CXXConstructorDecl>(D);
3266 if (!Constructor->isInvalidDecl() &&
3267 Constructor->isConvertingConstructor(AllowExplicit)) {
3268 if (ConstructorTmpl)
3269 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3271 Initializer, CandidateSet,
3272 /*SuppressUserConversions=*/true);
3274 S.AddOverloadCandidate(Constructor, FoundDecl,
3275 Initializer, CandidateSet,
3276 /*SuppressUserConversions=*/true);
3280 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3281 return OR_No_Viable_Function;
3283 const RecordType *T2RecordType = 0;
3284 if ((T2RecordType = T2->getAs<RecordType>()) &&
3285 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
3286 // The type we're converting from is a class type, enumerate its conversion
3288 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3290 std::pair<CXXRecordDecl::conversion_iterator,
3291 CXXRecordDecl::conversion_iterator>
3292 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3293 for (CXXRecordDecl::conversion_iterator
3294 I = Conversions.first, E = Conversions.second; I != E; ++I) {
3296 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3297 if (isa<UsingShadowDecl>(D))
3298 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3300 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3301 CXXConversionDecl *Conv;
3303 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3305 Conv = cast<CXXConversionDecl>(D);
3307 // If the conversion function doesn't return a reference type,
3308 // it can't be considered for this conversion unless we're allowed to
3309 // consider rvalues.
3310 // FIXME: Do we need to make sure that we only consider conversion
3311 // candidates with reference-compatible results? That might be needed to
3313 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
3314 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3316 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3317 ActingDC, Initializer,
3318 DestType, CandidateSet);
3320 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
3321 Initializer, DestType, CandidateSet);
3325 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3326 return OR_No_Viable_Function;
3328 SourceLocation DeclLoc = Initializer->getLocStart();
3330 // Perform overload resolution. If it fails, return the failed result.
3331 OverloadCandidateSet::iterator Best;
3332 if (OverloadingResult Result
3333 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
3336 FunctionDecl *Function = Best->Function;
3337 // This is the overload that will be used for this initialization step if we
3338 // use this initialization. Mark it as referenced.
3339 Function->setReferenced();
3341 // Compute the returned type of the conversion.
3342 if (isa<CXXConversionDecl>(Function))
3343 T2 = Function->getResultType();
3347 // Add the user-defined conversion step.
3348 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3349 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3350 T2.getNonLValueExprType(S.Context),
3351 HadMultipleCandidates);
3353 // Determine whether we need to perform derived-to-base or
3354 // cv-qualification adjustments.
3355 ExprValueKind VK = VK_RValue;
3356 if (T2->isLValueReferenceType())
3358 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
3359 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
3361 bool NewDerivedToBase = false;
3362 bool NewObjCConversion = false;
3363 bool NewObjCLifetimeConversion = false;
3364 Sema::ReferenceCompareResult NewRefRelationship
3365 = S.CompareReferenceRelationship(DeclLoc, T1,
3366 T2.getNonLValueExprType(S.Context),
3367 NewDerivedToBase, NewObjCConversion,
3368 NewObjCLifetimeConversion);
3369 if (NewRefRelationship == Sema::Ref_Incompatible) {
3370 // If the type we've converted to is not reference-related to the
3371 // type we're looking for, then there is another conversion step
3372 // we need to perform to produce a temporary of the right type
3373 // that we'll be binding to.
3374 ImplicitConversionSequence ICS;
3376 ICS.Standard = Best->FinalConversion;
3377 T2 = ICS.Standard.getToType(2);
3378 Sequence.AddConversionSequenceStep(ICS, T2);
3379 } else if (NewDerivedToBase)
3380 Sequence.AddDerivedToBaseCastStep(
3381 S.Context.getQualifiedType(T1,
3382 T2.getNonReferenceType().getQualifiers()),
3384 else if (NewObjCConversion)
3385 Sequence.AddObjCObjectConversionStep(
3386 S.Context.getQualifiedType(T1,
3387 T2.getNonReferenceType().getQualifiers()));
3389 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
3390 Sequence.AddQualificationConversionStep(cv1T1, VK);
3392 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3396 static void CheckCXX98CompatAccessibleCopy(Sema &S,
3397 const InitializedEntity &Entity,
3400 /// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3401 static void TryReferenceInitialization(Sema &S,
3402 const InitializedEntity &Entity,
3403 const InitializationKind &Kind,
3405 InitializationSequence &Sequence) {
3406 QualType DestType = Entity.getType();
3407 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3409 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3410 QualType cv2T2 = Initializer->getType();
3412 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3414 // If the initializer is the address of an overloaded function, try
3415 // to resolve the overloaded function. If all goes well, T2 is the
3416 // type of the resulting function.
3417 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3421 // Delegate everything else to a subfunction.
3422 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3423 T1Quals, cv2T2, T2, T2Quals, Sequence);
3426 /// Converts the target of reference initialization so that it has the
3427 /// appropriate qualifiers and value kind.
3429 /// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3432 /// const int &r = x;
3435 /// In this case the reference is binding to a bitfield lvalue, which isn't
3436 /// valid. Perform a load to create a lifetime-extended temporary instead.
3438 /// const int &r = someStruct.bitfield;
3440 static ExprValueKind
3441 convertQualifiersAndValueKindIfNecessary(Sema &S,
3442 InitializationSequence &Sequence,
3448 bool IsNonAddressableType = Initializer->refersToBitField() ||
3449 Initializer->refersToVectorElement();
3451 if (IsNonAddressableType) {
3452 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3453 // lvalue reference to a non-volatile const type, or the reference shall be
3454 // an rvalue reference.
3456 // If not, we can't make a temporary and bind to that. Give up and allow the
3457 // error to be diagnosed later.
3458 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3459 assert(Initializer->isGLValue());
3460 return Initializer->getValueKind();
3463 // Force a load so we can materialize a temporary.
3464 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3468 if (T1Quals != T2Quals) {
3469 Sequence.AddQualificationConversionStep(cv1T1,
3470 Initializer->getValueKind());
3473 return Initializer->getValueKind();
3477 /// \brief Reference initialization without resolving overloaded functions.
3478 static void TryReferenceInitializationCore(Sema &S,
3479 const InitializedEntity &Entity,
3480 const InitializationKind &Kind,
3482 QualType cv1T1, QualType T1,
3484 QualType cv2T2, QualType T2,
3486 InitializationSequence &Sequence) {
3487 QualType DestType = Entity.getType();
3488 SourceLocation DeclLoc = Initializer->getLocStart();
3489 // Compute some basic properties of the types and the initializer.
3490 bool isLValueRef = DestType->isLValueReferenceType();
3491 bool isRValueRef = !isLValueRef;
3492 bool DerivedToBase = false;
3493 bool ObjCConversion = false;
3494 bool ObjCLifetimeConversion = false;
3495 Expr::Classification InitCategory = Initializer->Classify(S.Context);
3496 Sema::ReferenceCompareResult RefRelationship
3497 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
3498 ObjCConversion, ObjCLifetimeConversion);
3500 // C++0x [dcl.init.ref]p5:
3501 // A reference to type "cv1 T1" is initialized by an expression of type
3502 // "cv2 T2" as follows:
3504 // - If the reference is an lvalue reference and the initializer
3506 // Note the analogous bullet points for rvlaue refs to functions. Because
3507 // there are no function rvalues in C++, rvalue refs to functions are treated
3508 // like lvalue refs.
3509 OverloadingResult ConvOvlResult = OR_Success;
3510 bool T1Function = T1->isFunctionType();
3511 if (isLValueRef || T1Function) {
3512 if (InitCategory.isLValue() &&
3513 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
3514 (Kind.isCStyleOrFunctionalCast() &&
3515 RefRelationship == Sema::Ref_Related))) {
3516 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
3517 // reference-compatible with "cv2 T2," or
3519 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
3520 // bit-field when we're determining whether the reference initialization
3521 // can occur. However, we do pay attention to whether it is a bit-field
3522 // to decide whether we're actually binding to a temporary created from
3525 Sequence.AddDerivedToBaseCastStep(
3526 S.Context.getQualifiedType(T1, T2Quals),
3528 else if (ObjCConversion)
3529 Sequence.AddObjCObjectConversionStep(
3530 S.Context.getQualifiedType(T1, T2Quals));
3532 ExprValueKind ValueKind =
3533 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3534 cv1T1, T1Quals, T2Quals,
3536 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
3540 // - has a class type (i.e., T2 is a class type), where T1 is not
3541 // reference-related to T2, and can be implicitly converted to an
3542 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3543 // with "cv3 T3" (this conversion is selected by enumerating the
3544 // applicable conversion functions (13.3.1.6) and choosing the best
3545 // one through overload resolution (13.3)),
3546 // If we have an rvalue ref to function type here, the rhs must be
3548 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3549 (isLValueRef || InitCategory.isRValue())) {
3550 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
3552 /*AllowRValues=*/isRValueRef,
3554 if (ConvOvlResult == OR_Success)
3556 if (ConvOvlResult != OR_No_Viable_Function) {
3557 Sequence.SetOverloadFailure(
3558 InitializationSequence::FK_ReferenceInitOverloadFailed,
3564 // - Otherwise, the reference shall be an lvalue reference to a
3565 // non-volatile const type (i.e., cv1 shall be const), or the reference
3566 // shall be an rvalue reference.
3567 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
3568 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3569 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3570 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3571 Sequence.SetOverloadFailure(
3572 InitializationSequence::FK_ReferenceInitOverloadFailed,
3575 Sequence.SetFailed(InitCategory.isLValue()
3576 ? (RefRelationship == Sema::Ref_Related
3577 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3578 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3579 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3584 // - If the initializer expression
3585 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3586 // "cv1 T1" is reference-compatible with "cv2 T2"
3587 // Note: functions are handled below.
3589 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
3590 (Kind.isCStyleOrFunctionalCast() &&
3591 RefRelationship == Sema::Ref_Related)) &&
3592 (InitCategory.isXValue() ||
3593 (InitCategory.isPRValue() && T2->isRecordType()) ||
3594 (InitCategory.isPRValue() && T2->isArrayType()))) {
3595 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3596 if (InitCategory.isPRValue() && T2->isRecordType()) {
3597 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3598 // compiler the freedom to perform a copy here or bind to the
3599 // object, while C++0x requires that we bind directly to the
3600 // object. Hence, we always bind to the object without making an
3601 // extra copy. However, in C++03 requires that we check for the
3602 // presence of a suitable copy constructor:
3604 // The constructor that would be used to make the copy shall
3605 // be callable whether or not the copy is actually done.
3606 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
3607 Sequence.AddExtraneousCopyToTemporary(cv2T2);
3608 else if (S.getLangOpts().CPlusPlus11)
3609 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
3613 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3615 else if (ObjCConversion)
3616 Sequence.AddObjCObjectConversionStep(
3617 S.Context.getQualifiedType(T1, T2Quals));
3619 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3624 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
3628 // - has a class type (i.e., T2 is a class type), where T1 is not
3629 // reference-related to T2, and can be implicitly converted to an
3630 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3631 // where "cv1 T1" is reference-compatible with "cv3 T3",
3632 if (T2->isRecordType()) {
3633 if (RefRelationship == Sema::Ref_Incompatible) {
3634 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3636 /*AllowRValues=*/true,
3639 Sequence.SetOverloadFailure(
3640 InitializationSequence::FK_ReferenceInitOverloadFailed,
3646 if ((RefRelationship == Sema::Ref_Compatible ||
3647 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3648 isRValueRef && InitCategory.isLValue()) {
3650 InitializationSequence::FK_RValueReferenceBindingToLValue);
3654 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3658 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
3659 // from the initializer expression using the rules for a non-reference
3660 // copy initialization (8.5). The reference is then bound to the
3663 // Determine whether we are allowed to call explicit constructors or
3664 // explicit conversion operators.
3665 bool AllowExplicit = Kind.AllowExplicit();
3667 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3669 ImplicitConversionSequence ICS
3670 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
3671 /*SuppressUserConversions*/ false,
3673 /*FIXME:InOverloadResolution=*/false,
3674 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3675 /*AllowObjCWritebackConversion=*/false);
3678 // FIXME: Use the conversion function set stored in ICS to turn
3679 // this into an overloading ambiguity diagnostic. However, we need
3680 // to keep that set as an OverloadCandidateSet rather than as some
3681 // other kind of set.
3682 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3683 Sequence.SetOverloadFailure(
3684 InitializationSequence::FK_ReferenceInitOverloadFailed,
3686 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3687 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3689 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
3692 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
3695 // [...] If T1 is reference-related to T2, cv1 must be the
3696 // same cv-qualification as, or greater cv-qualification
3697 // than, cv2; otherwise, the program is ill-formed.
3698 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3699 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
3700 if (RefRelationship == Sema::Ref_Related &&
3701 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
3702 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3706 // [...] If T1 is reference-related to T2 and the reference is an rvalue
3707 // reference, the initializer expression shall not be an lvalue.
3708 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
3709 InitCategory.isLValue()) {
3711 InitializationSequence::FK_RValueReferenceBindingToLValue);
3715 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3719 /// \brief Attempt character array initialization from a string literal
3720 /// (C++ [dcl.init.string], C99 6.7.8).
3721 static void TryStringLiteralInitialization(Sema &S,
3722 const InitializedEntity &Entity,
3723 const InitializationKind &Kind,
3725 InitializationSequence &Sequence) {
3726 Sequence.AddStringInitStep(Entity.getType());
3729 /// \brief Attempt value initialization (C++ [dcl.init]p7).
3730 static void TryValueInitialization(Sema &S,
3731 const InitializedEntity &Entity,
3732 const InitializationKind &Kind,
3733 InitializationSequence &Sequence,
3734 InitListExpr *InitList) {
3735 assert((!InitList || InitList->getNumInits() == 0) &&
3736 "Shouldn't use value-init for non-empty init lists");
3738 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
3740 // To value-initialize an object of type T means:
3741 QualType T = Entity.getType();
3743 // -- if T is an array type, then each element is value-initialized;
3744 T = S.Context.getBaseElementType(T);
3746 if (const RecordType *RT = T->getAs<RecordType>()) {
3747 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3748 bool NeedZeroInitialization = true;
3749 if (!S.getLangOpts().CPlusPlus11) {
3751 // -- if T is a class type (clause 9) with a user-declared constructor
3752 // (12.1), then the default constructor for T is called (and the
3753 // initialization is ill-formed if T has no accessible default
3755 if (ClassDecl->hasUserDeclaredConstructor())
3756 NeedZeroInitialization = false;
3759 // -- if T is a class type (clause 9) with either no default constructor
3760 // (12.1 [class.ctor]) or a default constructor that is user-provided
3761 // or deleted, then the object is default-initialized;
3762 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3763 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
3764 NeedZeroInitialization = false;
3767 // -- if T is a (possibly cv-qualified) non-union class type without a
3768 // user-provided or deleted default constructor, then the object is
3769 // zero-initialized and, if T has a non-trivial default constructor,
3770 // default-initialized;
3771 // The 'non-union' here was removed by DR1502. The 'non-trivial default
3772 // constructor' part was removed by DR1507.
3773 if (NeedZeroInitialization)
3774 Sequence.AddZeroInitializationStep(Entity.getType());
3777 // -- if T is a non-union class type without a user-declared constructor,
3778 // then every non-static data member and base class component of T is
3779 // value-initialized;
3780 // [...] A program that calls for [...] value-initialization of an
3781 // entity of reference type is ill-formed.
3783 // C++11 doesn't need this handling, because value-initialization does not
3784 // occur recursively there, and the implicit default constructor is
3785 // defined as deleted in the problematic cases.
3786 if (!S.getLangOpts().CPlusPlus11 &&
3787 ClassDecl->hasUninitializedReferenceMember()) {
3788 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
3792 // If this is list-value-initialization, pass the empty init list on when
3793 // building the constructor call. This affects the semantics of a few
3794 // things (such as whether an explicit default constructor can be called).
3795 Expr *InitListAsExpr = InitList;
3796 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
3797 bool InitListSyntax = InitList;
3799 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
3804 Sequence.AddZeroInitializationStep(Entity.getType());
3807 /// \brief Attempt default initialization (C++ [dcl.init]p6).
3808 static void TryDefaultInitialization(Sema &S,
3809 const InitializedEntity &Entity,
3810 const InitializationKind &Kind,
3811 InitializationSequence &Sequence) {
3812 assert(Kind.getKind() == InitializationKind::IK_Default);
3814 // C++ [dcl.init]p6:
3815 // To default-initialize an object of type T means:
3816 // - if T is an array type, each element is default-initialized;
3817 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3819 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3820 // constructor for T is called (and the initialization is ill-formed if
3821 // T has no accessible default constructor);
3822 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
3823 TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
3827 // - otherwise, no initialization is performed.
3829 // If a program calls for the default initialization of an object of
3830 // a const-qualified type T, T shall be a class type with a user-provided
3831 // default constructor.
3832 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
3833 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3837 // If the destination type has a lifetime property, zero-initialize it.
3838 if (DestType.getQualifiers().hasObjCLifetime()) {
3839 Sequence.AddZeroInitializationStep(Entity.getType());
3844 /// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3845 /// which enumerates all conversion functions and performs overload resolution
3846 /// to select the best.
3847 static void TryUserDefinedConversion(Sema &S,
3848 const InitializedEntity &Entity,
3849 const InitializationKind &Kind,
3851 InitializationSequence &Sequence) {
3852 QualType DestType = Entity.getType();
3853 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3854 QualType SourceType = Initializer->getType();
3855 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3856 "Must have a class type to perform a user-defined conversion");
3858 // Build the candidate set directly in the initialization sequence
3859 // structure, so that it will persist if we fail.
3860 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3861 CandidateSet.clear();
3863 // Determine whether we are allowed to call explicit constructors or
3864 // explicit conversion operators.
3865 bool AllowExplicit = Kind.AllowExplicit();
3867 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3868 // The type we're converting to is a class type. Enumerate its constructors
3869 // to see if there is a suitable conversion.
3870 CXXRecordDecl *DestRecordDecl
3871 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3873 // Try to complete the type we're converting to.
3874 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
3875 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
3876 // The container holding the constructors can under certain conditions
3877 // be changed while iterating. To be safe we copy the lookup results
3878 // to a new container.
3879 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
3880 for (SmallVector<NamedDecl*, 8>::iterator
3881 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
3882 Con != ConEnd; ++Con) {
3883 NamedDecl *D = *Con;
3884 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3886 // Find the constructor (which may be a template).
3887 CXXConstructorDecl *Constructor = 0;
3888 FunctionTemplateDecl *ConstructorTmpl
3889 = dyn_cast<FunctionTemplateDecl>(D);
3890 if (ConstructorTmpl)
3891 Constructor = cast<CXXConstructorDecl>(
3892 ConstructorTmpl->getTemplatedDecl());
3894 Constructor = cast<CXXConstructorDecl>(D);
3896 if (!Constructor->isInvalidDecl() &&
3897 Constructor->isConvertingConstructor(AllowExplicit)) {
3898 if (ConstructorTmpl)
3899 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3901 Initializer, CandidateSet,
3902 /*SuppressUserConversions=*/true);
3904 S.AddOverloadCandidate(Constructor, FoundDecl,
3905 Initializer, CandidateSet,
3906 /*SuppressUserConversions=*/true);
3912 SourceLocation DeclLoc = Initializer->getLocStart();
3914 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3915 // The type we're converting from is a class type, enumerate its conversion
3918 // We can only enumerate the conversion functions for a complete type; if
3919 // the type isn't complete, simply skip this step.
3920 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3921 CXXRecordDecl *SourceRecordDecl
3922 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
3924 std::pair<CXXRecordDecl::conversion_iterator,
3925 CXXRecordDecl::conversion_iterator>
3926 Conversions = SourceRecordDecl->getVisibleConversionFunctions();
3927 for (CXXRecordDecl::conversion_iterator
3928 I = Conversions.first, E = Conversions.second; I != E; ++I) {
3930 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3931 if (isa<UsingShadowDecl>(D))
3932 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3934 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3935 CXXConversionDecl *Conv;
3937 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3939 Conv = cast<CXXConversionDecl>(D);
3941 if (AllowExplicit || !Conv->isExplicit()) {
3943 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3944 ActingDC, Initializer, DestType,
3947 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
3948 Initializer, DestType, CandidateSet);
3954 // Perform overload resolution. If it fails, return the failed result.
3955 OverloadCandidateSet::iterator Best;
3956 if (OverloadingResult Result
3957 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
3958 Sequence.SetOverloadFailure(
3959 InitializationSequence::FK_UserConversionOverloadFailed,
3964 FunctionDecl *Function = Best->Function;
3965 Function->setReferenced();
3966 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3968 if (isa<CXXConstructorDecl>(Function)) {
3969 // Add the user-defined conversion step. Any cv-qualification conversion is
3970 // subsumed by the initialization. Per DR5, the created temporary is of the
3971 // cv-unqualified type of the destination.
3972 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3973 DestType.getUnqualifiedType(),
3974 HadMultipleCandidates);
3978 // Add the user-defined conversion step that calls the conversion function.
3979 QualType ConvType = Function->getCallResultType();
3980 if (ConvType->getAs<RecordType>()) {
3981 // If we're converting to a class type, there may be an copy of
3982 // the resulting temporary object (possible to create an object of
3983 // a base class type). That copy is not a separate conversion, so
3984 // we just make a note of the actual destination type (possibly a
3985 // base class of the type returned by the conversion function) and
3986 // let the user-defined conversion step handle the conversion.
3987 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3988 HadMultipleCandidates);
3992 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3993 HadMultipleCandidates);
3995 // If the conversion following the call to the conversion function
3996 // is interesting, add it as a separate step.
3997 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3998 Best->FinalConversion.Third) {
3999 ImplicitConversionSequence ICS;
4001 ICS.Standard = Best->FinalConversion;
4002 Sequence.AddConversionSequenceStep(ICS, DestType);
4006 /// The non-zero enum values here are indexes into diagnostic alternatives.
4007 enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4009 /// Determines whether this expression is an acceptable ICR source.
4010 static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
4011 bool isAddressOf, bool &isWeakAccess) {
4013 e = e->IgnoreParens();
4015 // Skip address-of nodes.
4016 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4017 if (op->getOpcode() == UO_AddrOf)
4018 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4021 // Skip certain casts.
4022 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4023 switch (ce->getCastKind()) {
4026 case CK_LValueBitCast:
4028 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
4030 case CK_ArrayToPointerDecay:
4031 return IIK_nonscalar;
4033 case CK_NullToPointer:
4040 // If we have a declaration reference, it had better be a local variable.
4041 } else if (isa<DeclRefExpr>(e)) {
4042 // set isWeakAccess to true, to mean that there will be an implicit
4043 // load which requires a cleanup.
4044 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4045 isWeakAccess = true;
4047 if (!isAddressOf) return IIK_nonlocal;
4049 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4050 if (!var) return IIK_nonlocal;
4052 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
4054 // If we have a conditional operator, check both sides.
4055 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
4056 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4060 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
4062 // These are never scalar.
4063 } else if (isa<ArraySubscriptExpr>(e)) {
4064 return IIK_nonscalar;
4066 // Otherwise, it needs to be a null pointer constant.
4068 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4069 ? IIK_okay : IIK_nonlocal);
4072 return IIK_nonlocal;
4075 /// Check whether the given expression is a valid operand for an
4076 /// indirect copy/restore.
4077 static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4078 assert(src->isRValue());
4079 bool isWeakAccess = false;
4080 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4081 // If isWeakAccess to true, there will be an implicit
4082 // load which requires a cleanup.
4083 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4084 S.ExprNeedsCleanups = true;
4086 if (iik == IIK_okay) return;
4088 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4089 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4090 << src->getSourceRange();
4093 /// \brief Determine whether we have compatible array types for the
4094 /// purposes of GNU by-copy array initialization.
4095 static bool hasCompatibleArrayTypes(ASTContext &Context,
4096 const ArrayType *Dest,
4097 const ArrayType *Source) {
4098 // If the source and destination array types are equivalent, we're
4100 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4103 // Make sure that the element types are the same.
4104 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4107 // The only mismatch we allow is when the destination is an
4108 // incomplete array type and the source is a constant array type.
4109 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4112 static bool tryObjCWritebackConversion(Sema &S,
4113 InitializationSequence &Sequence,
4114 const InitializedEntity &Entity,
4115 Expr *Initializer) {
4116 bool ArrayDecay = false;
4117 QualType ArgType = Initializer->getType();
4118 QualType ArgPointee;
4119 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4121 ArgPointee = ArgArrayType->getElementType();
4122 ArgType = S.Context.getPointerType(ArgPointee);
4125 // Handle write-back conversion.
4126 QualType ConvertedArgType;
4127 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4131 // We should copy unless we're passing to an argument explicitly
4133 bool ShouldCopy = true;
4134 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4135 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4137 // Do we need an lvalue conversion?
4138 if (ArrayDecay || Initializer->isGLValue()) {
4139 ImplicitConversionSequence ICS;
4141 ICS.Standard.setAsIdentityConversion();
4143 QualType ResultType;
4145 ICS.Standard.First = ICK_Array_To_Pointer;
4146 ResultType = S.Context.getPointerType(ArgPointee);
4148 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4149 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4152 Sequence.AddConversionSequenceStep(ICS, ResultType);
4155 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4159 static bool TryOCLSamplerInitialization(Sema &S,
4160 InitializationSequence &Sequence,
4162 Expr *Initializer) {
4163 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4164 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4167 Sequence.AddOCLSamplerInitStep(DestType);
4172 // OpenCL 1.2 spec, s6.12.10
4174 // The event argument can also be used to associate the
4175 // async_work_group_copy with a previous async copy allowing
4176 // an event to be shared by multiple async copies; otherwise
4177 // event should be zero.
4179 static bool TryOCLZeroEventInitialization(Sema &S,
4180 InitializationSequence &Sequence,
4182 Expr *Initializer) {
4183 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4184 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4185 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4188 Sequence.AddOCLZeroEventStep(DestType);
4192 InitializationSequence::InitializationSequence(Sema &S,
4193 const InitializedEntity &Entity,
4194 const InitializationKind &Kind,
4196 : FailedCandidateSet(Kind.getLocation()) {
4197 ASTContext &Context = S.Context;
4199 // Eliminate non-overload placeholder types in the arguments. We
4200 // need to do this before checking whether types are dependent
4201 // because lowering a pseudo-object expression might well give us
4202 // something of dependent type.
4203 for (unsigned I = 0, E = Args.size(); I != E; ++I)
4204 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4205 // FIXME: should we be doing this here?
4206 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4207 if (result.isInvalid()) {
4208 SetFailed(FK_PlaceholderType);
4211 Args[I] = result.take();
4214 // C++0x [dcl.init]p16:
4215 // The semantics of initializers are as follows. The destination type is
4216 // the type of the object or reference being initialized and the source
4217 // type is the type of the initializer expression. The source type is not
4218 // defined when the initializer is a braced-init-list or when it is a
4219 // parenthesized list of expressions.
4220 QualType DestType = Entity.getType();
4222 if (DestType->isDependentType() ||
4223 Expr::hasAnyTypeDependentArguments(Args)) {
4224 SequenceKind = DependentSequence;
4228 // Almost everything is a normal sequence.
4229 setSequenceKind(NormalSequence);
4231 QualType SourceType;
4232 Expr *Initializer = 0;
4233 if (Args.size() == 1) {
4234 Initializer = Args[0];
4235 if (!isa<InitListExpr>(Initializer))
4236 SourceType = Initializer->getType();
4239 // - If the initializer is a (non-parenthesized) braced-init-list, the
4240 // object is list-initialized (8.5.4).
4241 if (Kind.getKind() != InitializationKind::IK_Direct) {
4242 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4243 TryListInitialization(S, Entity, Kind, InitList, *this);
4248 // - If the destination type is a reference type, see 8.5.3.
4249 if (DestType->isReferenceType()) {
4250 // C++0x [dcl.init.ref]p1:
4251 // A variable declared to be a T& or T&&, that is, "reference to type T"
4252 // (8.3.2), shall be initialized by an object, or function, of type T or
4253 // by an object that can be converted into a T.
4254 // (Therefore, multiple arguments are not permitted.)
4255 if (Args.size() != 1)
4256 SetFailed(FK_TooManyInitsForReference);
4258 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
4262 // - If the initializer is (), the object is value-initialized.
4263 if (Kind.getKind() == InitializationKind::IK_Value ||
4264 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
4265 TryValueInitialization(S, Entity, Kind, *this);
4269 // Handle default initialization.
4270 if (Kind.getKind() == InitializationKind::IK_Default) {
4271 TryDefaultInitialization(S, Entity, Kind, *this);
4275 // - If the destination type is an array of characters, an array of
4276 // char16_t, an array of char32_t, or an array of wchar_t, and the
4277 // initializer is a string literal, see 8.5.2.
4278 // - Otherwise, if the destination type is an array, the program is
4280 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
4281 if (Initializer && isa<VariableArrayType>(DestAT)) {
4282 SetFailed(FK_VariableLengthArrayHasInitializer);
4286 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
4287 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4291 // Note: as an GNU C extension, we allow initialization of an
4292 // array from a compound literal that creates an array of the same
4293 // type, so long as the initializer has no side effects.
4294 if (!S.getLangOpts().CPlusPlus && Initializer &&
4295 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4296 Initializer->getType()->isArrayType()) {
4297 const ArrayType *SourceAT
4298 = Context.getAsArrayType(Initializer->getType());
4299 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
4300 SetFailed(FK_ArrayTypeMismatch);
4301 else if (Initializer->HasSideEffects(S.Context))
4302 SetFailed(FK_NonConstantArrayInit);
4304 AddArrayInitStep(DestType);
4307 // Note: as a GNU C++ extension, we allow list-initialization of a
4308 // class member of array type from a parenthesized initializer list.
4309 else if (S.getLangOpts().CPlusPlus &&
4310 Entity.getKind() == InitializedEntity::EK_Member &&
4311 Initializer && isa<InitListExpr>(Initializer)) {
4312 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4314 AddParenthesizedArrayInitStep(DestType);
4315 } else if (DestAT->getElementType()->isAnyCharacterType())
4316 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
4318 SetFailed(FK_ArrayNeedsInitList);
4323 // Determine whether we should consider writeback conversions for
4325 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
4326 Entity.getKind() == InitializedEntity::EK_Parameter;
4328 // We're at the end of the line for C: it's either a write-back conversion
4329 // or it's a C assignment. There's no need to check anything else.
4330 if (!S.getLangOpts().CPlusPlus) {
4331 // If allowed, check whether this is an Objective-C writeback conversion.
4332 if (allowObjCWritebackConversion &&
4333 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
4337 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4340 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4343 // Handle initialization in C
4344 AddCAssignmentStep(DestType);
4345 MaybeProduceObjCObject(S, *this, Entity);
4349 assert(S.getLangOpts().CPlusPlus);
4351 // - If the destination type is a (possibly cv-qualified) class type:
4352 if (DestType->isRecordType()) {
4353 // - If the initialization is direct-initialization, or if it is
4354 // copy-initialization where the cv-unqualified version of the
4355 // source type is the same class as, or a derived class of, the
4356 // class of the destination, constructors are considered. [...]
4357 if (Kind.getKind() == InitializationKind::IK_Direct ||
4358 (Kind.getKind() == InitializationKind::IK_Copy &&
4359 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4360 S.IsDerivedFrom(SourceType, DestType))))
4361 TryConstructorInitialization(S, Entity, Kind, Args,
4362 Entity.getType(), *this);
4363 // - Otherwise (i.e., for the remaining copy-initialization cases),
4364 // user-defined conversion sequences that can convert from the source
4365 // type to the destination type or (when a conversion function is
4366 // used) to a derived class thereof are enumerated as described in
4367 // 13.3.1.4, and the best one is chosen through overload resolution
4370 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4374 if (Args.size() > 1) {
4375 SetFailed(FK_TooManyInitsForScalar);
4378 assert(Args.size() == 1 && "Zero-argument case handled above");
4380 // - Otherwise, if the source type is a (possibly cv-qualified) class
4381 // type, conversion functions are considered.
4382 if (!SourceType.isNull() && SourceType->isRecordType()) {
4383 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4384 MaybeProduceObjCObject(S, *this, Entity);
4388 // - Otherwise, the initial value of the object being initialized is the
4389 // (possibly converted) value of the initializer expression. Standard
4390 // conversions (Clause 4) will be used, if necessary, to convert the
4391 // initializer expression to the cv-unqualified version of the
4392 // destination type; no user-defined conversions are considered.
4394 ImplicitConversionSequence ICS
4395 = S.TryImplicitConversion(Initializer, Entity.getType(),
4396 /*SuppressUserConversions*/true,
4397 /*AllowExplicitConversions*/ false,
4398 /*InOverloadResolution*/ false,
4399 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4400 allowObjCWritebackConversion);
4402 if (ICS.isStandard() &&
4403 ICS.Standard.Second == ICK_Writeback_Conversion) {
4404 // Objective-C ARC writeback conversion.
4406 // We should copy unless we're passing to an argument explicitly
4408 bool ShouldCopy = true;
4409 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4410 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4412 // If there was an lvalue adjustment, add it as a separate conversion.
4413 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4414 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4415 ImplicitConversionSequence LvalueICS;
4416 LvalueICS.setStandard();
4417 LvalueICS.Standard.setAsIdentityConversion();
4418 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4419 LvalueICS.Standard.First = ICS.Standard.First;
4420 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
4423 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4424 } else if (ICS.isBad()) {
4426 if (Initializer->getType() == Context.OverloadTy &&
4427 !S.ResolveAddressOfOverloadedFunction(Initializer
4428 , DestType, false, dap))
4429 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4431 SetFailed(InitializationSequence::FK_ConversionFailed);
4433 AddConversionSequenceStep(ICS, Entity.getType());
4435 MaybeProduceObjCObject(S, *this, Entity);
4439 InitializationSequence::~InitializationSequence() {
4440 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
4441 StepEnd = Steps.end();
4442 Step != StepEnd; ++Step)
4446 //===----------------------------------------------------------------------===//
4447 // Perform initialization
4448 //===----------------------------------------------------------------------===//
4449 static Sema::AssignmentAction
4450 getAssignmentAction(const InitializedEntity &Entity) {
4451 switch(Entity.getKind()) {
4452 case InitializedEntity::EK_Variable:
4453 case InitializedEntity::EK_New:
4454 case InitializedEntity::EK_Exception:
4455 case InitializedEntity::EK_Base:
4456 case InitializedEntity::EK_Delegating:
4457 return Sema::AA_Initializing;
4459 case InitializedEntity::EK_Parameter:
4460 if (Entity.getDecl() &&
4461 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4462 return Sema::AA_Sending;
4464 return Sema::AA_Passing;
4466 case InitializedEntity::EK_Result:
4467 return Sema::AA_Returning;
4469 case InitializedEntity::EK_Temporary:
4470 // FIXME: Can we tell apart casting vs. converting?
4471 return Sema::AA_Casting;
4473 case InitializedEntity::EK_Member:
4474 case InitializedEntity::EK_ArrayElement:
4475 case InitializedEntity::EK_VectorElement:
4476 case InitializedEntity::EK_ComplexElement:
4477 case InitializedEntity::EK_BlockElement:
4478 case InitializedEntity::EK_LambdaCapture:
4479 case InitializedEntity::EK_CompoundLiteralInit:
4480 return Sema::AA_Initializing;
4483 llvm_unreachable("Invalid EntityKind!");
4486 /// \brief Whether we should bind a created object as a temporary when
4487 /// initializing the given entity.
4488 static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
4489 switch (Entity.getKind()) {
4490 case InitializedEntity::EK_ArrayElement:
4491 case InitializedEntity::EK_Member:
4492 case InitializedEntity::EK_Result:
4493 case InitializedEntity::EK_New:
4494 case InitializedEntity::EK_Variable:
4495 case InitializedEntity::EK_Base:
4496 case InitializedEntity::EK_Delegating:
4497 case InitializedEntity::EK_VectorElement:
4498 case InitializedEntity::EK_ComplexElement:
4499 case InitializedEntity::EK_Exception:
4500 case InitializedEntity::EK_BlockElement:
4501 case InitializedEntity::EK_LambdaCapture:
4502 case InitializedEntity::EK_CompoundLiteralInit:
4505 case InitializedEntity::EK_Parameter:
4506 case InitializedEntity::EK_Temporary:
4510 llvm_unreachable("missed an InitializedEntity kind?");
4513 /// \brief Whether the given entity, when initialized with an object
4514 /// created for that initialization, requires destruction.
4515 static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4516 switch (Entity.getKind()) {
4517 case InitializedEntity::EK_Result:
4518 case InitializedEntity::EK_New:
4519 case InitializedEntity::EK_Base:
4520 case InitializedEntity::EK_Delegating:
4521 case InitializedEntity::EK_VectorElement:
4522 case InitializedEntity::EK_ComplexElement:
4523 case InitializedEntity::EK_BlockElement:
4524 case InitializedEntity::EK_LambdaCapture:
4527 case InitializedEntity::EK_Member:
4528 case InitializedEntity::EK_Variable:
4529 case InitializedEntity::EK_Parameter:
4530 case InitializedEntity::EK_Temporary:
4531 case InitializedEntity::EK_ArrayElement:
4532 case InitializedEntity::EK_Exception:
4533 case InitializedEntity::EK_CompoundLiteralInit:
4537 llvm_unreachable("missed an InitializedEntity kind?");
4540 /// \brief Look for copy and move constructors and constructor templates, for
4541 /// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4542 static void LookupCopyAndMoveConstructors(Sema &S,
4543 OverloadCandidateSet &CandidateSet,
4544 CXXRecordDecl *Class,
4545 Expr *CurInitExpr) {
4546 DeclContext::lookup_result R = S.LookupConstructors(Class);
4547 // The container holding the constructors can under certain conditions
4548 // be changed while iterating (e.g. because of deserialization).
4549 // To be safe we copy the lookup results to a new container.
4550 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
4551 for (SmallVector<NamedDecl*, 16>::iterator
4552 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4554 CXXConstructorDecl *Constructor = 0;
4556 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
4557 // Handle copy/moveconstructors, only.
4558 if (!Constructor || Constructor->isInvalidDecl() ||
4559 !Constructor->isCopyOrMoveConstructor() ||
4560 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4563 DeclAccessPair FoundDecl
4564 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4565 S.AddOverloadCandidate(Constructor, FoundDecl,
4566 CurInitExpr, CandidateSet);
4570 // Handle constructor templates.
4571 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
4572 if (ConstructorTmpl->isInvalidDecl())
4575 Constructor = cast<CXXConstructorDecl>(
4576 ConstructorTmpl->getTemplatedDecl());
4577 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4580 // FIXME: Do we need to limit this to copy-constructor-like
4582 DeclAccessPair FoundDecl
4583 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4584 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4585 CurInitExpr, CandidateSet, true);
4589 /// \brief Get the location at which initialization diagnostics should appear.
4590 static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4591 Expr *Initializer) {
4592 switch (Entity.getKind()) {
4593 case InitializedEntity::EK_Result:
4594 return Entity.getReturnLoc();
4596 case InitializedEntity::EK_Exception:
4597 return Entity.getThrowLoc();
4599 case InitializedEntity::EK_Variable:
4600 return Entity.getDecl()->getLocation();
4602 case InitializedEntity::EK_LambdaCapture:
4603 return Entity.getCaptureLoc();
4605 case InitializedEntity::EK_ArrayElement:
4606 case InitializedEntity::EK_Member:
4607 case InitializedEntity::EK_Parameter:
4608 case InitializedEntity::EK_Temporary:
4609 case InitializedEntity::EK_New:
4610 case InitializedEntity::EK_Base:
4611 case InitializedEntity::EK_Delegating:
4612 case InitializedEntity::EK_VectorElement:
4613 case InitializedEntity::EK_ComplexElement:
4614 case InitializedEntity::EK_BlockElement:
4615 case InitializedEntity::EK_CompoundLiteralInit:
4616 return Initializer->getLocStart();
4618 llvm_unreachable("missed an InitializedEntity kind?");
4621 /// \brief Make a (potentially elidable) temporary copy of the object
4622 /// provided by the given initializer by calling the appropriate copy
4625 /// \param S The Sema object used for type-checking.
4627 /// \param T The type of the temporary object, which must either be
4628 /// the type of the initializer expression or a superclass thereof.
4630 /// \param Entity The entity being initialized.
4632 /// \param CurInit The initializer expression.
4634 /// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4635 /// is permitted in C++03 (but not C++0x) when binding a reference to
4638 /// \returns An expression that copies the initializer expression into
4639 /// a temporary object, or an error expression if a copy could not be
4641 static ExprResult CopyObject(Sema &S,
4643 const InitializedEntity &Entity,
4645 bool IsExtraneousCopy) {
4646 // Determine which class type we're copying to.
4647 Expr *CurInitExpr = (Expr *)CurInit.get();
4648 CXXRecordDecl *Class = 0;
4649 if (const RecordType *Record = T->getAs<RecordType>())
4650 Class = cast<CXXRecordDecl>(Record->getDecl());
4654 // C++0x [class.copy]p32:
4655 // When certain criteria are met, an implementation is allowed to
4656 // omit the copy/move construction of a class object, even if the
4657 // copy/move constructor and/or destructor for the object have
4658 // side effects. [...]
4659 // - when a temporary class object that has not been bound to a
4660 // reference (12.2) would be copied/moved to a class object
4661 // with the same cv-unqualified type, the copy/move operation
4662 // can be omitted by constructing the temporary object
4663 // directly into the target of the omitted copy/move
4665 // Note that the other three bullets are handled elsewhere. Copy
4666 // elision for return statements and throw expressions are handled as part
4667 // of constructor initialization, while copy elision for exception handlers
4668 // is handled by the run-time.
4669 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
4670 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
4672 // Make sure that the type we are copying is complete.
4673 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
4676 // Perform overload resolution using the class's copy/move constructors.
4677 // Only consider constructors and constructor templates. Per
4678 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4679 // is direct-initialization.
4680 OverloadCandidateSet CandidateSet(Loc);
4681 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
4683 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4685 OverloadCandidateSet::iterator Best;
4686 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
4690 case OR_No_Viable_Function:
4691 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4692 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4693 : diag::err_temp_copy_no_viable)
4694 << (int)Entity.getKind() << CurInitExpr->getType()
4695 << CurInitExpr->getSourceRange();
4696 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
4697 if (!IsExtraneousCopy || S.isSFINAEContext())
4702 S.Diag(Loc, diag::err_temp_copy_ambiguous)
4703 << (int)Entity.getKind() << CurInitExpr->getType()
4704 << CurInitExpr->getSourceRange();
4705 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
4709 S.Diag(Loc, diag::err_temp_copy_deleted)
4710 << (int)Entity.getKind() << CurInitExpr->getType()
4711 << CurInitExpr->getSourceRange();
4712 S.NoteDeletedFunction(Best->Function);
4716 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
4717 SmallVector<Expr*, 8> ConstructorArgs;
4718 CurInit.release(); // Ownership transferred into MultiExprArg, below.
4720 S.CheckConstructorAccess(Loc, Constructor, Entity,
4721 Best->FoundDecl.getAccess(), IsExtraneousCopy);
4723 if (IsExtraneousCopy) {
4724 // If this is a totally extraneous copy for C++03 reference
4725 // binding purposes, just return the original initialization
4726 // expression. We don't generate an (elided) copy operation here
4727 // because doing so would require us to pass down a flag to avoid
4728 // infinite recursion, where each step adds another extraneous,
4731 // Instantiate the default arguments of any extra parameters in
4732 // the selected copy constructor, as if we were going to create a
4733 // proper call to the copy constructor.
4734 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4735 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4736 if (S.RequireCompleteType(Loc, Parm->getType(),
4737 diag::err_call_incomplete_argument))
4740 // Build the default argument expression; we don't actually care
4741 // if this succeeds or not, because this routine will complain
4742 // if there was a problem.
4743 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4746 return S.Owned(CurInitExpr);
4749 // Determine the arguments required to actually perform the
4750 // constructor call (we might have derived-to-base conversions, or
4751 // the copy constructor may have default arguments).
4752 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
4755 // Actually perform the constructor call.
4756 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
4758 HadMultipleCandidates,
4761 CXXConstructExpr::CK_Complete,
4764 // If we're supposed to bind temporaries, do so.
4765 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4766 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4770 /// \brief Check whether elidable copy construction for binding a reference to
4771 /// a temporary would have succeeded if we were building in C++98 mode, for
4773 static void CheckCXX98CompatAccessibleCopy(Sema &S,
4774 const InitializedEntity &Entity,
4775 Expr *CurInitExpr) {
4776 assert(S.getLangOpts().CPlusPlus11);
4778 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4782 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4783 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4784 == DiagnosticsEngine::Ignored)
4787 // Find constructors which would have been considered.
4788 OverloadCandidateSet CandidateSet(Loc);
4789 LookupCopyAndMoveConstructors(
4790 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4792 // Perform overload resolution.
4793 OverloadCandidateSet::iterator Best;
4794 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4796 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4797 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4798 << CurInitExpr->getSourceRange();
4802 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
4803 Entity, Best->FoundDecl.getAccess(), Diag);
4804 // FIXME: Check default arguments as far as that's possible.
4807 case OR_No_Viable_Function:
4809 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
4814 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
4819 S.NoteDeletedFunction(Best->Function);
4824 void InitializationSequence::PrintInitLocationNote(Sema &S,
4825 const InitializedEntity &Entity) {
4826 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4827 if (Entity.getDecl()->getLocation().isInvalid())
4830 if (Entity.getDecl()->getDeclName())
4831 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4832 << Entity.getDecl()->getDeclName();
4834 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4838 static bool isReferenceBinding(const InitializationSequence::Step &s) {
4839 return s.Kind == InitializationSequence::SK_BindReference ||
4840 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4843 /// Returns true if the parameters describe a constructor initialization of
4844 /// an explicit temporary object, e.g. "Point(x, y)".
4845 static bool isExplicitTemporary(const InitializedEntity &Entity,
4846 const InitializationKind &Kind,
4848 switch (Entity.getKind()) {
4849 case InitializedEntity::EK_Temporary:
4850 case InitializedEntity::EK_CompoundLiteralInit:
4856 switch (Kind.getKind()) {
4857 case InitializationKind::IK_DirectList:
4859 // FIXME: Hack to work around cast weirdness.
4860 case InitializationKind::IK_Direct:
4861 case InitializationKind::IK_Value:
4862 return NumArgs != 1;
4869 PerformConstructorInitialization(Sema &S,
4870 const InitializedEntity &Entity,
4871 const InitializationKind &Kind,
4873 const InitializationSequence::Step& Step,
4874 bool &ConstructorInitRequiresZeroInit,
4875 bool IsListInitialization) {
4876 unsigned NumArgs = Args.size();
4877 CXXConstructorDecl *Constructor
4878 = cast<CXXConstructorDecl>(Step.Function.Function);
4879 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4881 // Build a call to the selected constructor.
4882 SmallVector<Expr*, 8> ConstructorArgs;
4883 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4884 ? Kind.getEqualLoc()
4885 : Kind.getLocation();
4887 if (Kind.getKind() == InitializationKind::IK_Default) {
4888 // Force even a trivial, implicit default constructor to be
4889 // semantically checked. We do this explicitly because we don't build
4890 // the definition for completely trivial constructors.
4891 assert(Constructor->getParent() && "No parent class for constructor.");
4892 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
4893 Constructor->isTrivial() && !Constructor->isUsed(false))
4894 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4897 ExprResult CurInit = S.Owned((Expr *)0);
4899 // C++ [over.match.copy]p1:
4900 // - When initializing a temporary to be bound to the first parameter
4901 // of a constructor that takes a reference to possibly cv-qualified
4902 // T as its first argument, called with a single argument in the
4903 // context of direct-initialization, explicit conversion functions
4904 // are also considered.
4905 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
4907 Constructor->isCopyOrMoveConstructor();
4909 // Determine the arguments required to actually perform the constructor
4911 if (S.CompleteConstructorCall(Constructor, Args,
4912 Loc, ConstructorArgs,
4914 IsListInitialization))
4918 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
4919 // An explicitly-constructed temporary, e.g., X(1, 2).
4920 S.MarkFunctionReferenced(Loc, Constructor);
4921 if (S.DiagnoseUseOfDecl(Constructor, Loc))
4924 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4926 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
4927 SourceRange ParenRange;
4928 if (Kind.getKind() != InitializationKind::IK_DirectList)
4929 ParenRange = Kind.getParenRange();
4932 new (S.Context) CXXTemporaryObjectExpr(S.Context, Constructor,
4933 TSInfo, ConstructorArgs,
4934 ParenRange, IsListInitialization,
4935 HadMultipleCandidates,
4936 ConstructorInitRequiresZeroInit));
4938 CXXConstructExpr::ConstructionKind ConstructKind =
4939 CXXConstructExpr::CK_Complete;
4941 if (Entity.getKind() == InitializedEntity::EK_Base) {
4942 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4943 CXXConstructExpr::CK_VirtualBase :
4944 CXXConstructExpr::CK_NonVirtualBase;
4945 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4946 ConstructKind = CXXConstructExpr::CK_Delegating;
4949 // Only get the parenthesis range if it is a direct construction.
4950 SourceRange parenRange =
4951 Kind.getKind() == InitializationKind::IK_Direct ?
4952 Kind.getParenRange() : SourceRange();
4954 // If the entity allows NRVO, mark the construction as elidable
4956 if (Entity.allowsNRVO())
4957 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4958 Constructor, /*Elidable=*/true,
4960 HadMultipleCandidates,
4961 IsListInitialization,
4962 ConstructorInitRequiresZeroInit,
4966 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4969 HadMultipleCandidates,
4970 IsListInitialization,
4971 ConstructorInitRequiresZeroInit,
4975 if (CurInit.isInvalid())
4978 // Only check access if all of that succeeded.
4979 S.CheckConstructorAccess(Loc, Constructor, Entity,
4980 Step.Function.FoundDecl.getAccess());
4981 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
4984 if (shouldBindAsTemporary(Entity))
4985 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4990 /// Determine whether the specified InitializedEntity definitely has a lifetime
4991 /// longer than the current full-expression. Conservatively returns false if
4994 InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
4995 const InitializedEntity *Top = &Entity;
4996 while (Top->getParent())
4997 Top = Top->getParent();
4999 switch (Top->getKind()) {
5000 case InitializedEntity::EK_Variable:
5001 case InitializedEntity::EK_Result:
5002 case InitializedEntity::EK_Exception:
5003 case InitializedEntity::EK_Member:
5004 case InitializedEntity::EK_New:
5005 case InitializedEntity::EK_Base:
5006 case InitializedEntity::EK_Delegating:
5009 case InitializedEntity::EK_ArrayElement:
5010 case InitializedEntity::EK_VectorElement:
5011 case InitializedEntity::EK_BlockElement:
5012 case InitializedEntity::EK_ComplexElement:
5013 // Could not determine what the full initialization is. Assume it might not
5014 // outlive the full-expression.
5017 case InitializedEntity::EK_Parameter:
5018 case InitializedEntity::EK_Temporary:
5019 case InitializedEntity::EK_LambdaCapture:
5020 case InitializedEntity::EK_CompoundLiteralInit:
5021 // The entity being initialized might not outlive the full-expression.
5025 llvm_unreachable("unknown entity kind");
5029 InitializationSequence::Perform(Sema &S,
5030 const InitializedEntity &Entity,
5031 const InitializationKind &Kind,
5033 QualType *ResultType) {
5035 Diagnose(S, Entity, Kind, Args);
5039 if (getKind() == DependentSequence) {
5040 // If the declaration is a non-dependent, incomplete array type
5041 // that has an initializer, then its type will be completed once
5042 // the initializer is instantiated.
5043 if (ResultType && !Entity.getType()->isDependentType() &&
5045 QualType DeclType = Entity.getType();
5046 if (const IncompleteArrayType *ArrayT
5047 = S.Context.getAsIncompleteArrayType(DeclType)) {
5048 // FIXME: We don't currently have the ability to accurately
5049 // compute the length of an initializer list without
5050 // performing full type-checking of the initializer list
5051 // (since we have to determine where braces are implicitly
5052 // introduced and such). So, we fall back to making the array
5053 // type a dependently-sized array type with no specified
5055 if (isa<InitListExpr>((Expr *)Args[0])) {
5056 SourceRange Brackets;
5058 // Scavange the location of the brackets from the entity, if we can.
5059 if (DeclaratorDecl *DD = Entity.getDecl()) {
5060 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5061 TypeLoc TL = TInfo->getTypeLoc();
5062 if (IncompleteArrayTypeLoc ArrayLoc =
5063 TL.getAs<IncompleteArrayTypeLoc>())
5064 Brackets = ArrayLoc.getBracketsRange();
5069 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
5071 ArrayT->getSizeModifier(),
5072 ArrayT->getIndexTypeCVRQualifiers(),
5078 if (Kind.getKind() == InitializationKind::IK_Direct &&
5079 !Kind.isExplicitCast()) {
5080 // Rebuild the ParenListExpr.
5081 SourceRange ParenRange = Kind.getParenRange();
5082 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
5085 assert(Kind.getKind() == InitializationKind::IK_Copy ||
5086 Kind.isExplicitCast() ||
5087 Kind.getKind() == InitializationKind::IK_DirectList);
5088 return ExprResult(Args[0]);
5091 // No steps means no initialization.
5093 return S.Owned((Expr *)0);
5095 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
5096 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
5097 Entity.getKind() != InitializedEntity::EK_Parameter) {
5098 // Produce a C++98 compatibility warning if we are initializing a reference
5099 // from an initializer list. For parameters, we produce a better warning
5101 Expr *Init = Args[0];
5102 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5103 << Init->getSourceRange();
5106 // Diagnose cases where we initialize a pointer to an array temporary, and the
5107 // pointer obviously outlives the temporary.
5108 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
5109 Entity.getType()->isPointerType() &&
5110 InitializedEntityOutlivesFullExpression(Entity)) {
5111 Expr *Init = Args[0];
5112 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5113 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5114 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5115 << Init->getSourceRange();
5118 QualType DestType = Entity.getType().getNonReferenceType();
5119 // FIXME: Ugly hack around the fact that Entity.getType() is not
5120 // the same as Entity.getDecl()->getType() in cases involving type merging,
5121 // and we want latter when it makes sense.
5123 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
5126 ExprResult CurInit = S.Owned((Expr *)0);
5128 // For initialization steps that start with a single initializer,
5129 // grab the only argument out the Args and place it into the "current"
5131 switch (Steps.front().Kind) {
5132 case SK_ResolveAddressOfOverloadedFunction:
5133 case SK_CastDerivedToBaseRValue:
5134 case SK_CastDerivedToBaseXValue:
5135 case SK_CastDerivedToBaseLValue:
5136 case SK_BindReference:
5137 case SK_BindReferenceToTemporary:
5138 case SK_ExtraneousCopyToTemporary:
5139 case SK_UserConversion:
5140 case SK_QualificationConversionLValue:
5141 case SK_QualificationConversionXValue:
5142 case SK_QualificationConversionRValue:
5143 case SK_LValueToRValue:
5144 case SK_ConversionSequence:
5145 case SK_ListInitialization:
5146 case SK_UnwrapInitList:
5147 case SK_RewrapInitList:
5148 case SK_CAssignment:
5150 case SK_ObjCObjectConversion:
5152 case SK_ParenthesizedArrayInit:
5153 case SK_PassByIndirectCopyRestore:
5154 case SK_PassByIndirectRestore:
5155 case SK_ProduceObjCObject:
5156 case SK_StdInitializerList:
5157 case SK_OCLSamplerInit:
5158 case SK_OCLZeroEvent: {
5159 assert(Args.size() == 1);
5161 if (!CurInit.get()) return ExprError();
5165 case SK_ConstructorInitialization:
5166 case SK_ListConstructorCall:
5167 case SK_ZeroInitialization:
5171 // Walk through the computed steps for the initialization sequence,
5172 // performing the specified conversions along the way.
5173 bool ConstructorInitRequiresZeroInit = false;
5174 for (step_iterator Step = step_begin(), StepEnd = step_end();
5175 Step != StepEnd; ++Step) {
5176 if (CurInit.isInvalid())
5179 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
5181 switch (Step->Kind) {
5182 case SK_ResolveAddressOfOverloadedFunction:
5183 // Overload resolution determined which function invoke; update the
5184 // initializer to reflect that choice.
5185 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
5186 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5188 CurInit = S.FixOverloadedFunctionReference(CurInit,
5189 Step->Function.FoundDecl,
5190 Step->Function.Function);
5193 case SK_CastDerivedToBaseRValue:
5194 case SK_CastDerivedToBaseXValue:
5195 case SK_CastDerivedToBaseLValue: {
5196 // We have a derived-to-base cast that produces either an rvalue or an
5197 // lvalue. Perform that cast.
5199 CXXCastPath BasePath;
5201 // Casts to inaccessible base classes are allowed with C-style casts.
5202 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5203 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
5204 CurInit.get()->getLocStart(),
5205 CurInit.get()->getSourceRange(),
5206 &BasePath, IgnoreBaseAccess))
5209 if (S.BasePathInvolvesVirtualBase(BasePath)) {
5210 QualType T = SourceType;
5211 if (const PointerType *Pointer = T->getAs<PointerType>())
5212 T = Pointer->getPointeeType();
5213 if (const RecordType *RecordTy = T->getAs<RecordType>())
5214 S.MarkVTableUsed(CurInit.get()->getLocStart(),
5215 cast<CXXRecordDecl>(RecordTy->getDecl()));
5219 Step->Kind == SK_CastDerivedToBaseLValue ?
5221 (Step->Kind == SK_CastDerivedToBaseXValue ?
5224 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
5232 case SK_BindReference:
5233 // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
5234 if (CurInit.get()->refersToBitField()) {
5235 // We don't necessarily have an unambiguous source bit-field.
5236 FieldDecl *BitField = CurInit.get()->getSourceBitField();
5237 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
5238 << Entity.getType().isVolatileQualified()
5239 << (BitField ? BitField->getDeclName() : DeclarationName())
5240 << (BitField != NULL)
5241 << CurInit.get()->getSourceRange();
5243 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5248 if (CurInit.get()->refersToVectorElement()) {
5249 // References cannot bind to vector elements.
5250 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5251 << Entity.getType().isVolatileQualified()
5252 << CurInit.get()->getSourceRange();
5253 PrintInitLocationNote(S, Entity);
5257 // Reference binding does not have any corresponding ASTs.
5259 // Check exception specifications
5260 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
5265 case SK_BindReferenceToTemporary:
5266 // Make sure the "temporary" is actually an rvalue.
5267 assert(CurInit.get()->isRValue() && "not a temporary");
5269 // Check exception specifications
5270 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
5273 // Materialize the temporary into memory.
5274 CurInit = new (S.Context) MaterializeTemporaryExpr(
5275 Entity.getType().getNonReferenceType(),
5277 Entity.getType()->isLValueReferenceType());
5279 // If we're binding to an Objective-C object that has lifetime, we
5281 if (S.getLangOpts().ObjCAutoRefCount &&
5282 CurInit.get()->getType()->isObjCLifetimeType())
5283 S.ExprNeedsCleanups = true;
5287 case SK_ExtraneousCopyToTemporary:
5288 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
5289 /*IsExtraneousCopy=*/true);
5292 case SK_UserConversion: {
5293 // We have a user-defined conversion that invokes either a constructor
5294 // or a conversion function.
5296 bool IsCopy = false;
5297 FunctionDecl *Fn = Step->Function.Function;
5298 DeclAccessPair FoundFn = Step->Function.FoundDecl;
5299 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
5300 bool CreatedObject = false;
5301 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
5302 // Build a call to the selected constructor.
5303 SmallVector<Expr*, 8> ConstructorArgs;
5304 SourceLocation Loc = CurInit.get()->getLocStart();
5305 CurInit.release(); // Ownership transferred into MultiExprArg, below.
5307 // Determine the arguments required to actually perform the constructor
5309 Expr *Arg = CurInit.get();
5310 if (S.CompleteConstructorCall(Constructor,
5311 MultiExprArg(&Arg, 1),
5312 Loc, ConstructorArgs))
5315 // Build an expression that constructs a temporary.
5316 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
5318 HadMultipleCandidates,
5321 CXXConstructExpr::CK_Complete,
5323 if (CurInit.isInvalid())
5326 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
5327 FoundFn.getAccess());
5328 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5331 CastKind = CK_ConstructorConversion;
5332 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5333 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5334 S.IsDerivedFrom(SourceType, Class))
5337 CreatedObject = true;
5339 // Build a call to the conversion function.
5340 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
5341 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
5343 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5346 // FIXME: Should we move this initialization into a separate
5347 // derived-to-base conversion? I believe the answer is "no", because
5348 // we don't want to turn off access control here for c-style casts.
5349 ExprResult CurInitExprRes =
5350 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5351 FoundFn, Conversion);
5352 if(CurInitExprRes.isInvalid())
5354 CurInit = CurInitExprRes;
5356 // Build the actual call to the conversion function.
5357 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5358 HadMultipleCandidates);
5359 if (CurInit.isInvalid() || !CurInit.get())
5362 CastKind = CK_UserDefinedConversion;
5364 CreatedObject = Conversion->getResultType()->isRecordType();
5367 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
5368 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5370 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
5371 QualType T = CurInit.get()->getType();
5372 if (const RecordType *Record = T->getAs<RecordType>()) {
5373 CXXDestructorDecl *Destructor
5374 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
5375 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
5376 S.PDiag(diag::err_access_dtor_temp) << T);
5377 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
5378 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
5383 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
5384 CurInit.get()->getType(),
5385 CastKind, CurInit.get(), 0,
5386 CurInit.get()->getValueKind()));
5387 if (MaybeBindToTemp)
5388 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
5390 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
5391 CurInit, /*IsExtraneousCopy=*/false);
5395 case SK_QualificationConversionLValue:
5396 case SK_QualificationConversionXValue:
5397 case SK_QualificationConversionRValue: {
5398 // Perform a qualification conversion; these can never go wrong.
5400 Step->Kind == SK_QualificationConversionLValue ?
5402 (Step->Kind == SK_QualificationConversionXValue ?
5405 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
5409 case SK_LValueToRValue: {
5410 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
5411 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
5419 case SK_ConversionSequence: {
5420 Sema::CheckedConversionKind CCK
5421 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5422 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
5423 : Kind.isExplicitCast()? Sema::CCK_OtherCast
5424 : Sema::CCK_ImplicitConversion;
5425 ExprResult CurInitExprRes =
5426 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
5427 getAssignmentAction(Entity), CCK);
5428 if (CurInitExprRes.isInvalid())
5430 CurInit = CurInitExprRes;
5434 case SK_ListInitialization: {
5435 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
5436 // Hack: We must pass *ResultType if available in order to set the type
5437 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5438 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5439 // temporary, not a reference, so we should pass Ty.
5440 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5441 // Since this step is never used for a reference directly, we explicitly
5442 // unwrap references here and rewrap them afterwards.
5443 // We also need to create a InitializeTemporary entity for this.
5444 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
5445 bool IsTemporary = Entity.getType()->isReferenceType();
5446 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
5447 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
5448 InitListChecker PerformInitList(S, InitEntity,
5449 InitList, Ty, /*VerifyOnly=*/false,
5450 Kind.getKind() != InitializationKind::IK_DirectList ||
5451 !S.getLangOpts().CPlusPlus11);
5452 if (PerformInitList.HadError())
5456 if ((*ResultType)->isRValueReferenceType())
5457 Ty = S.Context.getRValueReferenceType(Ty);
5458 else if ((*ResultType)->isLValueReferenceType())
5459 Ty = S.Context.getLValueReferenceType(Ty,
5460 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5464 InitListExpr *StructuredInitList =
5465 PerformInitList.getFullyStructuredList();
5467 CurInit = shouldBindAsTemporary(InitEntity)
5468 ? S.MaybeBindToTemporary(StructuredInitList)
5469 : S.Owned(StructuredInitList);
5473 case SK_ListConstructorCall: {
5474 // When an initializer list is passed for a parameter of type "reference
5475 // to object", we don't get an EK_Temporary entity, but instead an
5476 // EK_Parameter entity with reference type.
5477 // FIXME: This is a hack. What we really should do is create a user
5478 // conversion step for this case, but this makes it considerably more
5479 // complicated. For now, this will do.
5480 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5481 Entity.getType().getNonReferenceType());
5482 bool UseTemporary = Entity.getType()->isReferenceType();
5483 assert(Args.size() == 1 && "expected a single argument for list init");
5484 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5485 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
5486 << InitList->getSourceRange();
5487 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
5488 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
5491 ConstructorInitRequiresZeroInit,
5492 /*IsListInitialization*/ true);
5496 case SK_UnwrapInitList:
5497 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5500 case SK_RewrapInitList: {
5501 Expr *E = CurInit.take();
5502 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5503 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
5504 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
5505 ILE->setSyntacticForm(Syntactic);
5506 ILE->setType(E->getType());
5507 ILE->setValueKind(E->getValueKind());
5508 CurInit = S.Owned(ILE);
5512 case SK_ConstructorInitialization: {
5513 // When an initializer list is passed for a parameter of type "reference
5514 // to object", we don't get an EK_Temporary entity, but instead an
5515 // EK_Parameter entity with reference type.
5516 // FIXME: This is a hack. What we really should do is create a user
5517 // conversion step for this case, but this makes it considerably more
5518 // complicated. For now, this will do.
5519 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5520 Entity.getType().getNonReferenceType());
5521 bool UseTemporary = Entity.getType()->isReferenceType();
5522 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
5525 ConstructorInitRequiresZeroInit,
5526 /*IsListInitialization*/ false);
5530 case SK_ZeroInitialization: {
5531 step_iterator NextStep = Step;
5533 if (NextStep != StepEnd &&
5534 (NextStep->Kind == SK_ConstructorInitialization ||
5535 NextStep->Kind == SK_ListConstructorCall)) {
5536 // The need for zero-initialization is recorded directly into
5537 // the call to the object's constructor within the next step.
5538 ConstructorInitRequiresZeroInit = true;
5539 } else if (Kind.getKind() == InitializationKind::IK_Value &&
5540 S.getLangOpts().CPlusPlus &&
5541 !Kind.isImplicitValueInit()) {
5542 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5544 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
5545 Kind.getRange().getBegin());
5547 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5548 TSInfo->getType().getNonLValueExprType(S.Context),
5550 Kind.getRange().getEnd()));
5552 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
5557 case SK_CAssignment: {
5558 QualType SourceType = CurInit.get()->getType();
5559 ExprResult Result = CurInit;
5560 Sema::AssignConvertType ConvTy =
5561 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5562 if (Result.isInvalid())
5566 // If this is a call, allow conversion to a transparent union.
5567 ExprResult CurInitExprRes = CurInit;
5568 if (ConvTy != Sema::Compatible &&
5569 Entity.getKind() == InitializedEntity::EK_Parameter &&
5570 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
5571 == Sema::Compatible)
5572 ConvTy = Sema::Compatible;
5573 if (CurInitExprRes.isInvalid())
5575 CurInit = CurInitExprRes;
5578 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5579 Step->Type, SourceType,
5581 getAssignmentAction(Entity),
5583 PrintInitLocationNote(S, Entity);
5585 } else if (Complained)
5586 PrintInitLocationNote(S, Entity);
5590 case SK_StringInit: {
5591 QualType Ty = Step->Type;
5592 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
5593 S.Context.getAsArrayType(Ty), S);
5597 case SK_ObjCObjectConversion:
5598 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
5599 CK_ObjCObjectLValueCast,
5600 CurInit.get()->getValueKind());
5604 // Okay: we checked everything before creating this step. Note that
5605 // this is a GNU extension.
5606 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
5607 << Step->Type << CurInit.get()->getType()
5608 << CurInit.get()->getSourceRange();
5610 // If the destination type is an incomplete array type, update the
5611 // type accordingly.
5613 if (const IncompleteArrayType *IncompleteDest
5614 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5615 if (const ConstantArrayType *ConstantSource
5616 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
5617 *ResultType = S.Context.getConstantArrayType(
5618 IncompleteDest->getElementType(),
5619 ConstantSource->getSize(),
5620 ArrayType::Normal, 0);
5626 case SK_ParenthesizedArrayInit:
5627 // Okay: we checked everything before creating this step. Note that
5628 // this is a GNU extension.
5629 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
5630 << CurInit.get()->getSourceRange();
5633 case SK_PassByIndirectCopyRestore:
5634 case SK_PassByIndirectRestore:
5635 checkIndirectCopyRestoreSource(S, CurInit.get());
5636 CurInit = S.Owned(new (S.Context)
5637 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5638 Step->Kind == SK_PassByIndirectCopyRestore));
5641 case SK_ProduceObjCObject:
5642 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
5643 CK_ARCProduceObject,
5644 CurInit.take(), 0, VK_RValue));
5647 case SK_StdInitializerList: {
5648 QualType Dest = Step->Type;
5650 bool Success = S.isStdInitializerList(Dest.getNonReferenceType(), &E);
5652 assert(Success && "Destination type changed?");
5654 // If the element type has a destructor, check it.
5655 if (CXXRecordDecl *RD = E->getAsCXXRecordDecl()) {
5656 if (!RD->hasIrrelevantDestructor()) {
5657 if (CXXDestructorDecl *Destructor = S.LookupDestructor(RD)) {
5658 S.MarkFunctionReferenced(Kind.getLocation(), Destructor);
5659 S.CheckDestructorAccess(Kind.getLocation(), Destructor,
5660 S.PDiag(diag::err_access_dtor_temp) << E);
5661 if (S.DiagnoseUseOfDecl(Destructor, Kind.getLocation()))
5667 InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
5668 S.Diag(ILE->getExprLoc(), diag::warn_cxx98_compat_initializer_list_init)
5669 << ILE->getSourceRange();
5670 unsigned NumInits = ILE->getNumInits();
5671 SmallVector<Expr*, 16> Converted(NumInits);
5672 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5673 S.Context.getConstantArrayType(E,
5674 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5676 ArrayType::Normal, 0));
5677 InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5679 for (unsigned i = 0; i < NumInits; ++i) {
5680 Element.setElementIndex(i);
5681 ExprResult Init = S.Owned(ILE->getInit(i));
5682 ExprResult Res = S.PerformCopyInitialization(
5683 Element, Init.get()->getExprLoc(), Init,
5684 /*TopLevelOfInitList=*/ true);
5685 assert(!Res.isInvalid() && "Result changed since try phase.");
5686 Converted[i] = Res.take();
5688 InitListExpr *Semantic = new (S.Context)
5689 InitListExpr(S.Context, ILE->getLBraceLoc(),
5690 Converted, ILE->getRBraceLoc());
5691 Semantic->setSyntacticForm(ILE);
5692 Semantic->setType(Dest);
5693 Semantic->setInitializesStdInitializerList();
5694 CurInit = S.Owned(Semantic);
5697 case SK_OCLSamplerInit: {
5698 assert(Step->Type->isSamplerT() &&
5699 "Sampler initialization on non sampler type.");
5701 QualType SourceType = CurInit.get()->getType();
5702 InitializedEntity::EntityKind EntityKind = Entity.getKind();
5704 if (EntityKind == InitializedEntity::EK_Parameter) {
5705 if (!SourceType->isSamplerT())
5706 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
5708 } else if (EntityKind != InitializedEntity::EK_Variable) {
5709 llvm_unreachable("Invalid EntityKind!");
5714 case SK_OCLZeroEvent: {
5715 assert(Step->Type->isEventT() &&
5716 "Event initialization on non event type.");
5718 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
5720 CurInit.get()->getValueKind());
5726 // Diagnose non-fatal problems with the completed initialization.
5727 if (Entity.getKind() == InitializedEntity::EK_Member &&
5728 cast<FieldDecl>(Entity.getDecl())->isBitField())
5729 S.CheckBitFieldInitialization(Kind.getLocation(),
5730 cast<FieldDecl>(Entity.getDecl()),
5736 /// Somewhere within T there is an uninitialized reference subobject.
5737 /// Dig it out and diagnose it.
5738 static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
5740 if (T->isReferenceType()) {
5741 S.Diag(Loc, diag::err_reference_without_init)
5742 << T.getNonReferenceType();
5746 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5747 if (!RD || !RD->hasUninitializedReferenceMember())
5750 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5751 FE = RD->field_end(); FI != FE; ++FI) {
5752 if (FI->isUnnamedBitfield())
5755 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
5756 S.Diag(Loc, diag::note_value_initialization_here) << RD;
5761 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5762 BE = RD->bases_end();
5764 if (DiagnoseUninitializedReference(S, BI->getLocStart(), BI->getType())) {
5765 S.Diag(Loc, diag::note_value_initialization_here) << RD;
5774 //===----------------------------------------------------------------------===//
5775 // Diagnose initialization failures
5776 //===----------------------------------------------------------------------===//
5778 /// Emit notes associated with an initialization that failed due to a
5779 /// "simple" conversion failure.
5780 static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
5782 QualType destType = entity.getType();
5783 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
5784 op->getType()->isObjCObjectPointerType()) {
5786 // Emit a possible note about the conversion failing because the
5787 // operand is a message send with a related result type.
5788 S.EmitRelatedResultTypeNote(op);
5790 // Emit a possible note about a return failing because we're
5791 // expecting a related result type.
5792 if (entity.getKind() == InitializedEntity::EK_Result)
5793 S.EmitRelatedResultTypeNoteForReturn(destType);
5797 bool InitializationSequence::Diagnose(Sema &S,
5798 const InitializedEntity &Entity,
5799 const InitializationKind &Kind,
5800 ArrayRef<Expr *> Args) {
5804 QualType DestType = Entity.getType();
5806 case FK_TooManyInitsForReference:
5807 // FIXME: Customize for the initialized entity?
5809 // Dig out the reference subobject which is uninitialized and diagnose it.
5810 // If this is value-initialization, this could be nested some way within
5812 assert(Kind.getKind() == InitializationKind::IK_Value ||
5813 DestType->isReferenceType());
5815 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
5816 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
5818 } else // FIXME: diagnostic below could be better!
5819 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
5820 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
5823 case FK_ArrayNeedsInitList:
5824 case FK_ArrayNeedsInitListOrStringLiteral:
5825 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5826 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5829 case FK_ArrayTypeMismatch:
5830 case FK_NonConstantArrayInit:
5831 S.Diag(Kind.getLocation(),
5832 (Failure == FK_ArrayTypeMismatch
5833 ? diag::err_array_init_different_type
5834 : diag::err_array_init_non_constant_array))
5835 << DestType.getNonReferenceType()
5836 << Args[0]->getType()
5837 << Args[0]->getSourceRange();
5840 case FK_VariableLengthArrayHasInitializer:
5841 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5842 << Args[0]->getSourceRange();
5845 case FK_AddressOfOverloadFailed: {
5846 DeclAccessPair Found;
5847 S.ResolveAddressOfOverloadedFunction(Args[0],
5848 DestType.getNonReferenceType(),
5854 case FK_ReferenceInitOverloadFailed:
5855 case FK_UserConversionOverloadFailed:
5856 switch (FailedOverloadResult) {
5858 if (Failure == FK_UserConversionOverloadFailed)
5859 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5860 << Args[0]->getType() << DestType
5861 << Args[0]->getSourceRange();
5863 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5864 << DestType << Args[0]->getType()
5865 << Args[0]->getSourceRange();
5867 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
5870 case OR_No_Viable_Function:
5871 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5872 << Args[0]->getType() << DestType.getNonReferenceType()
5873 << Args[0]->getSourceRange();
5874 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
5878 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5879 << Args[0]->getType() << DestType.getNonReferenceType()
5880 << Args[0]->getSourceRange();
5881 OverloadCandidateSet::iterator Best;
5882 OverloadingResult Ovl
5883 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5885 if (Ovl == OR_Deleted) {
5886 S.NoteDeletedFunction(Best->Function);
5888 llvm_unreachable("Inconsistent overload resolution?");
5894 llvm_unreachable("Conversion did not fail!");
5898 case FK_NonConstLValueReferenceBindingToTemporary:
5899 if (isa<InitListExpr>(Args[0])) {
5900 S.Diag(Kind.getLocation(),
5901 diag::err_lvalue_reference_bind_to_initlist)
5902 << DestType.getNonReferenceType().isVolatileQualified()
5903 << DestType.getNonReferenceType()
5904 << Args[0]->getSourceRange();
5907 // Intentional fallthrough
5909 case FK_NonConstLValueReferenceBindingToUnrelated:
5910 S.Diag(Kind.getLocation(),
5911 Failure == FK_NonConstLValueReferenceBindingToTemporary
5912 ? diag::err_lvalue_reference_bind_to_temporary
5913 : diag::err_lvalue_reference_bind_to_unrelated)
5914 << DestType.getNonReferenceType().isVolatileQualified()
5915 << DestType.getNonReferenceType()
5916 << Args[0]->getType()
5917 << Args[0]->getSourceRange();
5920 case FK_RValueReferenceBindingToLValue:
5921 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
5922 << DestType.getNonReferenceType() << Args[0]->getType()
5923 << Args[0]->getSourceRange();
5926 case FK_ReferenceInitDropsQualifiers:
5927 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5928 << DestType.getNonReferenceType()
5929 << Args[0]->getType()
5930 << Args[0]->getSourceRange();
5933 case FK_ReferenceInitFailed:
5934 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5935 << DestType.getNonReferenceType()
5936 << Args[0]->isLValue()
5937 << Args[0]->getType()
5938 << Args[0]->getSourceRange();
5939 emitBadConversionNotes(S, Entity, Args[0]);
5942 case FK_ConversionFailed: {
5943 QualType FromType = Args[0]->getType();
5944 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
5945 << (int)Entity.getKind()
5947 << Args[0]->isLValue()
5949 << Args[0]->getSourceRange();
5950 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5951 S.Diag(Kind.getLocation(), PDiag);
5952 emitBadConversionNotes(S, Entity, Args[0]);
5956 case FK_ConversionFromPropertyFailed:
5957 // No-op. This error has already been reported.
5960 case FK_TooManyInitsForScalar: {
5963 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
5964 R = SourceRange(InitList->getInit(0)->getLocEnd(),
5965 InitList->getLocEnd());
5967 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
5969 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5970 if (Kind.isCStyleOrFunctionalCast())
5971 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5974 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5975 << /*scalar=*/2 << R;
5979 case FK_ReferenceBindingToInitList:
5980 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5981 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5984 case FK_InitListBadDestinationType:
5985 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5986 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5989 case FK_ListConstructorOverloadFailed:
5990 case FK_ConstructorOverloadFailed: {
5991 SourceRange ArgsRange;
5993 ArgsRange = SourceRange(Args.front()->getLocStart(),
5994 Args.back()->getLocEnd());
5996 if (Failure == FK_ListConstructorOverloadFailed) {
5997 assert(Args.size() == 1 && "List construction from other than 1 argument.");
5998 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5999 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
6002 // FIXME: Using "DestType" for the entity we're printing is probably
6004 switch (FailedOverloadResult) {
6006 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
6007 << DestType << ArgsRange;
6008 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
6011 case OR_No_Viable_Function:
6012 if (Kind.getKind() == InitializationKind::IK_Default &&
6013 (Entity.getKind() == InitializedEntity::EK_Base ||
6014 Entity.getKind() == InitializedEntity::EK_Member) &&
6015 isa<CXXConstructorDecl>(S.CurContext)) {
6016 // This is implicit default initialization of a member or
6017 // base within a constructor. If no viable function was
6018 // found, notify the user that she needs to explicitly
6019 // initialize this base/member.
6020 CXXConstructorDecl *Constructor
6021 = cast<CXXConstructorDecl>(S.CurContext);
6022 if (Entity.getKind() == InitializedEntity::EK_Base) {
6023 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
6024 << (Constructor->getInheritedConstructor() ? 2 :
6025 Constructor->isImplicit() ? 1 : 0)
6026 << S.Context.getTypeDeclType(Constructor->getParent())
6028 << Entity.getType();
6030 RecordDecl *BaseDecl
6031 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6033 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6034 << S.Context.getTagDeclType(BaseDecl);
6036 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
6037 << (Constructor->getInheritedConstructor() ? 2 :
6038 Constructor->isImplicit() ? 1 : 0)
6039 << S.Context.getTypeDeclType(Constructor->getParent())
6041 << Entity.getName();
6042 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
6044 if (const RecordType *Record
6045 = Entity.getType()->getAs<RecordType>())
6046 S.Diag(Record->getDecl()->getLocation(),
6047 diag::note_previous_decl)
6048 << S.Context.getTagDeclType(Record->getDecl());
6053 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6054 << DestType << ArgsRange;
6055 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
6059 OverloadCandidateSet::iterator Best;
6060 OverloadingResult Ovl
6061 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
6062 if (Ovl != OR_Deleted) {
6063 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6064 << true << DestType << ArgsRange;
6065 llvm_unreachable("Inconsistent overload resolution?");
6069 // If this is a defaulted or implicitly-declared function, then
6070 // it was implicitly deleted. Make it clear that the deletion was
6072 if (S.isImplicitlyDeleted(Best->Function))
6073 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
6074 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
6075 << DestType << ArgsRange;
6077 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6078 << true << DestType << ArgsRange;
6080 S.NoteDeletedFunction(Best->Function);
6085 llvm_unreachable("Conversion did not fail!");
6090 case FK_DefaultInitOfConst:
6091 if (Entity.getKind() == InitializedEntity::EK_Member &&
6092 isa<CXXConstructorDecl>(S.CurContext)) {
6093 // This is implicit default-initialization of a const member in
6094 // a constructor. Complain that it needs to be explicitly
6096 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6097 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
6098 << (Constructor->getInheritedConstructor() ? 2 :
6099 Constructor->isImplicit() ? 1 : 0)
6100 << S.Context.getTypeDeclType(Constructor->getParent())
6102 << Entity.getName();
6103 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6104 << Entity.getName();
6106 S.Diag(Kind.getLocation(), diag::err_default_init_const)
6107 << DestType << (bool)DestType->getAs<RecordType>();
6112 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
6113 diag::err_init_incomplete_type);
6116 case FK_ListInitializationFailed: {
6117 // Run the init list checker again to emit diagnostics.
6118 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
6119 QualType DestType = Entity.getType();
6120 InitListChecker DiagnoseInitList(S, Entity, InitList,
6121 DestType, /*VerifyOnly=*/false,
6122 Kind.getKind() != InitializationKind::IK_DirectList ||
6123 !S.getLangOpts().CPlusPlus11);
6124 assert(DiagnoseInitList.HadError() &&
6125 "Inconsistent init list check result.");
6129 case FK_PlaceholderType: {
6130 // FIXME: Already diagnosed!
6134 case FK_InitListElementCopyFailure: {
6135 // Try to perform all copies again.
6136 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
6137 unsigned NumInits = InitList->getNumInits();
6138 QualType DestType = Entity.getType();
6140 bool Success = S.isStdInitializerList(DestType.getNonReferenceType(), &E);
6142 assert(Success && "Where did the std::initializer_list go?");
6143 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
6144 S.Context.getConstantArrayType(E,
6145 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6147 ArrayType::Normal, 0));
6148 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
6150 // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
6151 // where the init list type is wrong, e.g.
6152 // std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
6153 // FIXME: Emit a note if we hit the limit?
6155 for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
6156 Element.setElementIndex(i);
6157 ExprResult Init = S.Owned(InitList->getInit(i));
6158 if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
6165 case FK_ExplicitConstructor: {
6166 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6167 << Args[0]->getSourceRange();
6168 OverloadCandidateSet::iterator Best;
6169 OverloadingResult Ovl
6170 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
6172 assert(Ovl == OR_Success && "Inconsistent overload resolution");
6173 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6174 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6179 PrintInitLocationNote(S, Entity);
6183 void InitializationSequence::dump(raw_ostream &OS) const {
6184 switch (SequenceKind) {
6185 case FailedSequence: {
6186 OS << "Failed sequence: ";
6188 case FK_TooManyInitsForReference:
6189 OS << "too many initializers for reference";
6192 case FK_ArrayNeedsInitList:
6193 OS << "array requires initializer list";
6196 case FK_ArrayNeedsInitListOrStringLiteral:
6197 OS << "array requires initializer list or string literal";
6200 case FK_ArrayTypeMismatch:
6201 OS << "array type mismatch";
6204 case FK_NonConstantArrayInit:
6205 OS << "non-constant array initializer";
6208 case FK_AddressOfOverloadFailed:
6209 OS << "address of overloaded function failed";
6212 case FK_ReferenceInitOverloadFailed:
6213 OS << "overload resolution for reference initialization failed";
6216 case FK_NonConstLValueReferenceBindingToTemporary:
6217 OS << "non-const lvalue reference bound to temporary";
6220 case FK_NonConstLValueReferenceBindingToUnrelated:
6221 OS << "non-const lvalue reference bound to unrelated type";
6224 case FK_RValueReferenceBindingToLValue:
6225 OS << "rvalue reference bound to an lvalue";
6228 case FK_ReferenceInitDropsQualifiers:
6229 OS << "reference initialization drops qualifiers";
6232 case FK_ReferenceInitFailed:
6233 OS << "reference initialization failed";
6236 case FK_ConversionFailed:
6237 OS << "conversion failed";
6240 case FK_ConversionFromPropertyFailed:
6241 OS << "conversion from property failed";
6244 case FK_TooManyInitsForScalar:
6245 OS << "too many initializers for scalar";
6248 case FK_ReferenceBindingToInitList:
6249 OS << "referencing binding to initializer list";
6252 case FK_InitListBadDestinationType:
6253 OS << "initializer list for non-aggregate, non-scalar type";
6256 case FK_UserConversionOverloadFailed:
6257 OS << "overloading failed for user-defined conversion";
6260 case FK_ConstructorOverloadFailed:
6261 OS << "constructor overloading failed";
6264 case FK_DefaultInitOfConst:
6265 OS << "default initialization of a const variable";
6269 OS << "initialization of incomplete type";
6272 case FK_ListInitializationFailed:
6273 OS << "list initialization checker failure";
6276 case FK_VariableLengthArrayHasInitializer:
6277 OS << "variable length array has an initializer";
6280 case FK_PlaceholderType:
6281 OS << "initializer expression isn't contextually valid";
6284 case FK_ListConstructorOverloadFailed:
6285 OS << "list constructor overloading failed";
6288 case FK_InitListElementCopyFailure:
6289 OS << "copy construction of initializer list element failed";
6292 case FK_ExplicitConstructor:
6293 OS << "list copy initialization chose explicit constructor";
6300 case DependentSequence:
6301 OS << "Dependent sequence\n";
6304 case NormalSequence:
6305 OS << "Normal sequence: ";
6309 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
6310 if (S != step_begin()) {
6315 case SK_ResolveAddressOfOverloadedFunction:
6316 OS << "resolve address of overloaded function";
6319 case SK_CastDerivedToBaseRValue:
6320 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
6323 case SK_CastDerivedToBaseXValue:
6324 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
6327 case SK_CastDerivedToBaseLValue:
6328 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
6331 case SK_BindReference:
6332 OS << "bind reference to lvalue";
6335 case SK_BindReferenceToTemporary:
6336 OS << "bind reference to a temporary";
6339 case SK_ExtraneousCopyToTemporary:
6340 OS << "extraneous C++03 copy to temporary";
6343 case SK_UserConversion:
6344 OS << "user-defined conversion via " << *S->Function.Function;
6347 case SK_QualificationConversionRValue:
6348 OS << "qualification conversion (rvalue)";
6351 case SK_QualificationConversionXValue:
6352 OS << "qualification conversion (xvalue)";
6355 case SK_QualificationConversionLValue:
6356 OS << "qualification conversion (lvalue)";
6359 case SK_LValueToRValue:
6360 OS << "load (lvalue to rvalue)";
6363 case SK_ConversionSequence:
6364 OS << "implicit conversion sequence (";
6365 S->ICS->DebugPrint(); // FIXME: use OS
6369 case SK_ListInitialization:
6370 OS << "list aggregate initialization";
6373 case SK_ListConstructorCall:
6374 OS << "list initialization via constructor";
6377 case SK_UnwrapInitList:
6378 OS << "unwrap reference initializer list";
6381 case SK_RewrapInitList:
6382 OS << "rewrap reference initializer list";
6385 case SK_ConstructorInitialization:
6386 OS << "constructor initialization";
6389 case SK_ZeroInitialization:
6390 OS << "zero initialization";
6393 case SK_CAssignment:
6394 OS << "C assignment";
6398 OS << "string initialization";
6401 case SK_ObjCObjectConversion:
6402 OS << "Objective-C object conversion";
6406 OS << "array initialization";
6409 case SK_ParenthesizedArrayInit:
6410 OS << "parenthesized array initialization";
6413 case SK_PassByIndirectCopyRestore:
6414 OS << "pass by indirect copy and restore";
6417 case SK_PassByIndirectRestore:
6418 OS << "pass by indirect restore";
6421 case SK_ProduceObjCObject:
6422 OS << "Objective-C object retension";
6425 case SK_StdInitializerList:
6426 OS << "std::initializer_list from initializer list";
6429 case SK_OCLSamplerInit:
6430 OS << "OpenCL sampler_t from integer constant";
6433 case SK_OCLZeroEvent:
6434 OS << "OpenCL event_t from zero";
6438 OS << " [" << S->Type.getAsString() << ']';
6444 void InitializationSequence::dump() const {
6448 static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
6449 QualType EntityType,
6450 const Expr *PreInit,
6451 const Expr *PostInit) {
6452 if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
6455 // A narrowing conversion can only appear as the final implicit conversion in
6456 // an initialization sequence.
6457 const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
6458 if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
6461 const ImplicitConversionSequence &ICS = *LastStep.ICS;
6462 const StandardConversionSequence *SCS = 0;
6463 switch (ICS.getKind()) {
6464 case ImplicitConversionSequence::StandardConversion:
6465 SCS = &ICS.Standard;
6467 case ImplicitConversionSequence::UserDefinedConversion:
6468 SCS = &ICS.UserDefined.After;
6470 case ImplicitConversionSequence::AmbiguousConversion:
6471 case ImplicitConversionSequence::EllipsisConversion:
6472 case ImplicitConversionSequence::BadConversion:
6476 // Determine the type prior to the narrowing conversion. If a conversion
6477 // operator was used, this may be different from both the type of the entity
6478 // and of the pre-initialization expression.
6479 QualType PreNarrowingType = PreInit->getType();
6480 if (Seq.step_begin() + 1 != Seq.step_end())
6481 PreNarrowingType = Seq.step_end()[-2].Type;
6483 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
6484 APValue ConstantValue;
6485 QualType ConstantType;
6486 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
6488 case NK_Not_Narrowing:
6489 // No narrowing occurred.
6492 case NK_Type_Narrowing:
6493 // This was a floating-to-integer conversion, which is always considered a
6494 // narrowing conversion even if the value is a constant and can be
6495 // represented exactly as an integer.
6496 S.Diag(PostInit->getLocStart(),
6497 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
6498 diag::warn_init_list_type_narrowing
6499 : S.isSFINAEContext()?
6500 diag::err_init_list_type_narrowing_sfinae
6501 : diag::err_init_list_type_narrowing)
6502 << PostInit->getSourceRange()
6503 << PreNarrowingType.getLocalUnqualifiedType()
6504 << EntityType.getLocalUnqualifiedType();
6507 case NK_Constant_Narrowing:
6508 // A constant value was narrowed.
6509 S.Diag(PostInit->getLocStart(),
6510 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
6511 diag::warn_init_list_constant_narrowing
6512 : S.isSFINAEContext()?
6513 diag::err_init_list_constant_narrowing_sfinae
6514 : diag::err_init_list_constant_narrowing)
6515 << PostInit->getSourceRange()
6516 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
6517 << EntityType.getLocalUnqualifiedType();
6520 case NK_Variable_Narrowing:
6521 // A variable's value may have been narrowed.
6522 S.Diag(PostInit->getLocStart(),
6523 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
6524 diag::warn_init_list_variable_narrowing
6525 : S.isSFINAEContext()?
6526 diag::err_init_list_variable_narrowing_sfinae
6527 : diag::err_init_list_variable_narrowing)
6528 << PostInit->getSourceRange()
6529 << PreNarrowingType.getLocalUnqualifiedType()
6530 << EntityType.getLocalUnqualifiedType();
6534 SmallString<128> StaticCast;
6535 llvm::raw_svector_ostream OS(StaticCast);
6536 OS << "static_cast<";
6537 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
6538 // It's important to use the typedef's name if there is one so that the
6539 // fixit doesn't break code using types like int64_t.
6541 // FIXME: This will break if the typedef requires qualification. But
6542 // getQualifiedNameAsString() includes non-machine-parsable components.
6543 OS << *TT->getDecl();
6544 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
6545 OS << BT->getName(S.getLangOpts());
6547 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
6548 // with a broken cast.
6552 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
6553 << PostInit->getSourceRange()
6554 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
6555 << FixItHint::CreateInsertion(
6556 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
6559 //===----------------------------------------------------------------------===//
6560 // Initialization helper functions
6561 //===----------------------------------------------------------------------===//
6563 Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
6565 if (Init.isInvalid())
6568 Expr *InitE = Init.get();
6569 assert(InitE && "No initialization expression");
6571 InitializationKind Kind
6572 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
6573 InitializationSequence Seq(*this, Entity, Kind, InitE);
6574 return !Seq.Failed();
6578 Sema::PerformCopyInitialization(const InitializedEntity &Entity,
6579 SourceLocation EqualLoc,
6581 bool TopLevelOfInitList,
6582 bool AllowExplicit) {
6583 if (Init.isInvalid())
6586 Expr *InitE = Init.get();
6587 assert(InitE && "No initialization expression?");
6589 if (EqualLoc.isInvalid())
6590 EqualLoc = InitE->getLocStart();
6592 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
6595 InitializationSequence Seq(*this, Entity, Kind, InitE);
6598 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
6600 if (!Result.isInvalid() && TopLevelOfInitList)
6601 DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
6602 InitE, Result.get());